text:
Q: ExtJS grouping grid cannot load JSON data I am not able to load data in ExtJS grouping grid.
I have following code for ExtJS grouping.js.
Ext.onReady(function() {

    Ext.QuickTips.init();

    var xg = Ext.grid;

    var documentType = "";
    var fileName = "";
    var size = "";
    var fileGPath = "";

    // shared reader
    var reader = new Ext.data.ArrayReader({}, [{
            name: 'filename'
        }, {
            name: 'size'
        }, {
            name: 'author'
        }, {
            name: 'date',
            type: 'date',
            dateFormat: 'Y-m-d H:i:s'
        }, {
            name: 'action'
        }, {
            name: 'document'
        }

    ]);

    var store = new Ext.data.GroupingStore({
        reader: reader,
        url: 'DocumentListService.jsp',
        root: 'Documents',
        sortInfo: {
            field: 'filename',
            direction: "ASC"
        },
        fields: [{
            name: 'filename',
            mapping: 'FileName'
        }, {
            name: 'size',
            mapping: 'Size'
        }, {
            name: 'author',
            mapping: 'Author'
        }, {
            name: 'date',
            mapping: 'Date'
        }, {
            name: 'action',
            mapping: ''
        }, {
            name: 'document',
            mapping: 'Document'
        }],
        groupField: 'document'
    });

    var grid = new xg.GridPanel({
        id: 'myGridId',
        store: store,
        columns: [{
            id: 'filename',
            header: "File Name",
            width: 60,
            sortable: true,
            dataIndex: 'filename'
        }, {
            header: "Size",
            width: 20,
            sortable: true,
            dataIndex: 'size'
        }, {
            header: "Author",
            width: 20,
            sortable: true,
            dataIndex: 'author'
        }, {
            header: "Date",
            width: 20,
            sortable: true,
            dataIndex: 'date'
        }, {
            header: "Action",
            width: 20,
            sortable: true,
            dataIndex: 'action'
        }, {
            header: "Document",
            width: 20,
            sortable: true,
            dataIndex: 'document',
            hidden: 'true'
        }],

        view: new Ext.grid.GroupingView({
            forceFit: true,
            groupTextTpl: '{text} ({[values.rs[0].get("filename")=="" ? "0" : values.rs.length]} {[values.rs.length > 1 ? "Documents" : "Document"]}) '
        }),

        frame: true,
        width: 700,
        height: 450,
        collapsible: true,
        animCollapse: false,
        title: 'Document Library',
        iconCls: 'icon-grid',
        renderTo: 'docUpload'
    });

    var fp = new Ext.FormPanel({
        renderTo: 'fi-form',
        fileUpload: true,
        width: 500,
        frame: true,
        title: 'File Upload Form',
        autoHeight: true,
        bodyStyle: 'padding: 10px 10px 0 10px;',
        labelWidth: 50,
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{
            xtype: 'fileuploadfield',
            id: 'form-file',
            emptyText: 'Select a File to import',
            fieldLabel: 'File',
            name: 'file',
            buttonCfg: {
                text: '',
                iconCls: 'upload-icon'
            },
            listeners: {
                'fileselected': function(v) {
                    if (fp.getForm().isValid()) {
                        fp.getForm().submit({
                            url: 'FileUpload.jsp',
                            waitMsg: 'Uploading your file...',
                            success: function(fp, jsonObj) {

                                fileName = jsonObj.result.fileName;
                                size = jsonObj.result.size;
                                fileGPath = jsonObj.result.fileGPath;

                                documentType = (document.getElementById("hdnId").value).replace("Document: ", "");
                                addDataToGrid(fileName, fileGPath, size, documentType);
                                Ext.getCmp('myGridId').getStore().loadData(xg.dummyData);
                                msg('Success', 'Successfully uploded on the server');
                            },
                            failure: function(fp, o) {
                                msg('Failure', 'Failed to upload');
                            }
                        });
                    }
                }
            }
        }]

    });

});

And I have following as json string in DocumentListService.jsp:
{
    "DocumentList": [{
        "DocumentGroup": "Invoice",
        "isDocumentBundle": true,
        "isWritable": true,
        "Documents": [{
            "FileName": "ABC.doc",
            "Size": "123",
            "Author": "xyz",
            "Date": "\\/Date(1238025600000)\\/",
            "FileGPath": "xyz doc",
            "Document": "Invoice"
        }, {
            "FileName": "ABC.doc",
            "Size": "123",
            "Author": "xyz",
            "Date": "\\/Date(1238025600000)\\/",
            "FileGPath": "abc doc",
            "Document": "Invoice"
        }]
    }, {
        "DocumentGroup": "SOP",
        "isDocumentBundle": true,
        "isWritable": true,
        "Documents": [{
            "FileName": "ABC.doc",
            "Size": "123",
            "Author": "xyz",
            "Date": "\\/Date(1238025600000)\\/",
            "FileGPath": "xyz doc",
            "Document": "SOP"
        }]
    }]
}

Still I am not able to load data.

A: Well your problem is the store reader, which has set as root "Documents" but the Json received has the root DocumentList. So the problem is mapping the json data to your store.

EDIT
The problem is that you are using incorectly the grouping store. The data does not need to be grouped when you are getting it from the backend.

Here is my suggestion

Json sent from back-end just a list of documents in which you have the type:
{
    "Documents": [{
        "Type": "invoice",
        "FileName": "ABC.doc",
        "Size": "123",
        "Author": "xyz",
        "Date": "\/Date(1238025600000)\/",
        "FileGPath": "xyz doc",
        "Document": "Invoice"
    }, {
        "Type": "invoice",
        "FileName": "ABC.doc",
        "Size": "123",
        "Author": "xyz",
        "Date": "\/Date(1238025600000)\/",
        "FileGPath": "abc doc",
        "Document": "Invoice"
    }, {
        "Type": "SOP",
        "FileName": "ABC.doc",
        "Size": "123",
        "Author": "xyz",
        "Date": "\/Date(1238025600000)\/",
        "FileGPath": "xyz doc",
        "Document": "SOP"
    }]
}

And for the grouping store just use groupField: "Type" , And the reader should have the root Documents. This will simplify your load but it means you have to duplicate the extra data you need for each group and attach it to each document.
Is just a suggestion.


text:
Q: Using the .map method on a list of constructors in flutter I have a class for transactions with a constructor. Using the constructor method, I created a list of transaction, with the aim of looping through these transactions and displaying it's contents in a card but I'm getting errors while trying to use the .map method on the list.
The error message i'm getting is The element type 'List<Map<dynamic, dynamic>>' can't be assigned to the list type 'Widget'.
I have the error on [transactions.map((transaction) => {}).toList()]
Here's the code:
class Hompage extends StatelessWidget {
  final List<Transaction> transactions = [
    Transaction(
      id: 't1',
      title: 'First Transaction',
      amount: 1000,
      date: DateTime.now(),
    ),
    Transaction(
      id: 't2',
      title: 'Second Transaction',
      amount: 500,
      date: DateTime.now(),
    )
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Event Planner'),
      ),
      body: Column(
        // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        // crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            width: double.infinity,
            child: Card(
              color: Colors.blue,
              child: Text('CHART'),
            ),
          ),
          Column(
            // children: [
            //   (transactions as List<Map<dynamic, dynamic>>)
            //       .map((transaction) => {})
            //       .toList()
            // ],

            children: [transactions.map((transaction) => {}).toList()],
          )
        ],
      ),
    );
  }
}

A: children: [transactions.map((transaction) => {}).toList()]

First, remove the brackets, you now have a list of lists:
children: transactions.map((transaction) => {}).toList()

Okay, better, but since children expects Widget type elements, you cannot just map to nothing.
children: transactions.map((transaction) => Text(transaction.title)).toList()

A lot better. You may want to find something fancier than a simple Text though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 3 and tkinter, thread join blocks main thread forever So basically I have a class, let's say SerialClass, that creates a local thread to update a combobox, the constructor looks like this:
def __init__(self, master):

    ...
    # Local thread.
    self.__thread = threading.Thread(target=self.__thread_handler)
    self.__thread_finished = False
    self.__thread.start()

This is the function that the thread executes, it just updates a combobox with values.
def __thread_handler(self):
    while not self.__thread_finished:
        # Update the ports continously.
        self.update_ports()
    ...

This the function I use to exit the thread:
def thread_exit(self):
    self.__thread_finished = True
    self.__thread.join()

Another class, let's say App, instantiates the class SerialClass. App creates a Tk object and starts the main application using this method:
def run(self):
    # Handle the close window event.
    self.__root.protocol("WM_DELETE_WINDOW", self.__on_close)
    # Start the application and wait for user events.
    self.__root.mainloop()

This is the on_close method:
def __on_close(self):
    # When the application finishes, handle the rest of the threads.
    self.__serialui.thread_exit()
    # Destroy the root window as expected.
    self.__root.destroy()

The problem I have is that the program flow never reaches the root.destroy() function, for some reason the main thread is blocked forever when I call thread_exit function. If I comment the self.update_ports() in the thread_handler function, all the processes close gracefully.
Any ideas?


text:
Q: Macro Code to Number Lines based on if there is Data I am newish at VBA but I cannot figure out how to make this work. I am copying a ton of data from a another Excel sheet and then deleting the unneeded rows. The problem is that I need my data numbered in column A and when I delete the row it skips numbers. I want a macro that will number my data after I delete the unneeded lines. I do need it to stop when my data stops but the number of lines will be different each time. Any tips? Thank you.

A: You may try something like this...
After deleting rows, run the following code which will add the sequence number in column A starting from row2.
Sub SqNumber()
Dim lr As Long
lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With Range("A2:A" & lr)
    .Formula = "=Row()-1"
    .Value = .Value
End With
End Sub

A: Use union  method.  You collect range and at the last line,  delete them.
Sub test()
    Dim rngU As Range
    Dim i As Integer

    For i = 1 To 100
        If Range("a" & i) = "" Then
            If rngU Is Nothing Then
                Set rngU = Range("a" & i)
            Else
                Set rngU = Union(rngU, Range("a" & i))
            End If
        End If
    Next i
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete 'rngu is collected ranges.
    End If
End Sub


text:
Q: Getting client ID using jquery Im trying to validate a textbox by getting the client ID using the below and then testing its value
The textbox is in a ModalPopupExtender which is in a updatepanel
However JQuery doesnt seem to be returning anything, the control is always NULL
This textbox is inside a gridview
  <asp:TemplateField HeaderText="Quick Donate">
                                <ItemTemplate>
                                    <asp:Button ID="btnQuickDonate" runat="server"
                                        CommandName="Insert"
                                        CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
                                        OnClick="btnQuickDonate"
                                        Text="Quick Donate" />
                                    <ajaxToolkit:ModalPopupExtender ID="ModalDonationPopup" runat="server" TargetControlID="btnQuickDonate" PopupControlID="Panel1" BackgroundCssClass="modalBackground">
                                    </ajaxToolkit:ModalPopupExtender>
                                    <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Style="display: none">
                                        Enter Donation Amount

                                                    <asp:Button ID="btnOnePound" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="1" />
                                                    <asp:Button ID="btnFivePound" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="5" />
                                                    <asp:Button ID="btnTenPound" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="10" />
                                                    <asp:Button ID="btnFifteenPound" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="15" />
                                                    <asp:Button ID="btnTwentyPounds" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="20" />
                                                    <asp:Button ID="btnTwentyFivePounds" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="25" />
                                                    <asp:Button ID="btnThirtyPounds" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="30" />
                                                    <asp:Button ID="btnFiftyPounds" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" OnClick="btnQuickDonate" Text="50" />

                                            <%--  --%>

                                        <asp:TextBox ID="txtFreeDonationAmount" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"  ></asp:TextBox>
                                        **<asp:Button ID="btnOK" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="OK" OnClientClick="return valtxtBoxFreeDonation();" OnClick="btnQuickDonate"></asp:Button>**

                                        <asp:Button ID="btnCancel" runat="server" Text="Cancel" />

                                    </asp:Panel>

Javascript below I have also tried $('#txtFreeDonationAmount') with no joy...
function valtxtBoxFreeDonation() {
    var txtDonation = $('#<%=txtFreeDonationAmount.ClientID %>');

     if (txtDonation.val().length < 0) {
        // do something
        apprise("Please Enter a Donation Amount before click okay");
        return false;
    }

}

A: The bold solution is jsut to take this id 'GridView1_btnOK_1` and use it in your JS.
$('#GridView1_txtFreeDonationAmount_0')

And as mentiones about the $('#<%=txtFreeDonationAmount.ClientID %>') will work only if your JS is in the same .aspx file.

A: This code:
var txtDonation = $('#<%=txtFreeDonationAmount.ClientID %>');

will work properly only when JavaScript is inside .aspx file.


text:
Q: div not showing up I have some problem with the following code:
<input type="radio" name="subscription" id="subscription" value="yes" checked="checked"  />Yes
<input type="radio" name="subscription" id="subscription" value="no" />No

    [ some code here ]

Now I have jQuery as
if(jQuery('input[name|="subscription"]').val()=='yes') {
  jQuery('#sub_yes').fadeIn(0, function(){
                                 jQuery(this).slideDown('slow','swing');
                                });
}

When document get ready, jQuery checks value of "subscription" and if it's yes, then it should show div named "sub_yes", But this code is not working.
Please help

A: You are just checking the value of subscription radio button. There should be a click event checker also, so that whenever you click the radio button it should check the value and react accordingly.
jQuery('input[name|="subscription"]').click(function(){
if(jQuery('input[name|="subscription"]').val()=='yes') {
  jQuery('#sub_yes').fadeIn(0, function(){
                                 jQuery(this).slideDown('slow','swing');
                                });
}
});

Hope this solves the problem

A: found the solution:
I added :checked
jQuery('input[name|="subscription"]:checked').val()=='yes'

Thanks all

A:     <input type="radio" name="subscription" id="subscription" value="yes" checked="checked"  />Yes
    <input type="radio" name="subscription2" id="subscription2" value="no" />No

        [ some code here ]

    $(document).ready(function(){

    $('input[type="radio"]').each(function(){
    var val=$(this).val();
    if(val=="yes"){
    $('#sub_yes').fadeIn(0, function(){
                                     $(this).slideDown('slow','swing');
                                    });
    return;
    }

    });

});

hope it helps
Edit:
instead of display:none u can use
$("#sub_yes").hide();

in document ready and to show the div u can use .show()


text:
Q: Poco::Base64Decoder stream not returning complete string not sure if i am just using it wrong because this is not really my field of expertise but i was under the impression that this should give me a complete decoded openframeworks buffer (or a simple string, i tried various ways all resulting in the same too short string):
string str; // string is a line from a file handle and shows to be ok in the debugger
istringstream istr(str);
Poco::Base64Decoder b64in(istr);
ofBuffer buffer;
b64in >> buffer;

now an example base64 string i am decoding is this line:
I2J1bmRsZQAAAAAAAAAAAQAAABwvT1NDL1NwYWNlSW50ZW5zaXR5ACxmAAA6nUlSAAAAFC9PU0MvU3BlZWQAACxmAAA90/fPAAAAGC9PU0MvU21vb3RobmVzcwAsZgAAP2Wu5gAAABQvT1NDL1JlYWNoAAAsZgAAPnxQSAAAABgvT1NDL0RlbnNpdHkAAAAALGYAAAAAAAAAAAAYL09TQy9Db2hlcmVuY2UAACxmAAA+tYEGAAAAIC9PU0MvVHJhdmVsSW50ZW5zaXR5AAAAACxmAAA8eQlsAAAAFC9PU0MvUmh5dGhtACxmAAA+6LQ5AAAAGC9PU0MvSGFybW9ueQAAAAAsZgAAPui0OQAAABQvT1NDL0VuZXJneQAsZgAAPYznBA==

the line does not resolve to a simple ascii text but rather a raw osc packet dumped in base64 by some vvvv patch i do not have access to... so i guess it could also be an encoding issue?
and all i get in the output, no matter if i use a streamcopier or an operator like above, is only "#bundle". could this somehow be related to the / character or other non-standard stuff following the "#bundle"? i was under the impression that the Base64Decoder doesn't care about whitespace or whatever it finds in the decoded data.

A: so i ended up not using the operator but rather copying the output of the base64decoder to a stream and then getting a string from that:
istringstream istr(str);
ostringstream ostr;
Poco::Base64Decoder b64in(istr);
copy(std::istreambuf_iterator<char>(b64in),
    std::istreambuf_iterator<char>(),
    std::ostreambuf_iterator<char>(ostr));
cout << ostr.str(); // returns full decoded output

A: This has actually nothing to do with Poco::Base64Decoder. The stream extraction operator for std::string will stop at the first whitespace character it encounters in your input stream (which in case of Base64Decoder would be the decoded data).


text:
Q: iOS in-app purchases - best way to tell if user has purchased I need to set a global variable when a user makes an in-app purchase. I could use NSUserDefaults, and just have a key called "Purchased", but that doesn't seem very secure.
What is the best way to securely store data so that I know whether or not users have made a purchase?
For example in a particular view I need to know whether or not to display a "Purchase" button. Obviously it should be hidden if they've already made the purchase.

A: For secure data you should use the iOS keychain. Here's the documentation:
http://developer.apple.com/library/mac/#documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html
Hope this helps.

A: There is no need to store that information. There is a method to restore all the user purchases. Look for restoreCompletedTransactions.
You can check all the user's purchases in your view and then show the "Purchase" button for all the items that can still be bought.
UPDATE:
Oh! I misunderstood your question. The above method will get you the purchases the user has made in case of an app reinstall for instance. Regarding your question, it is completely fine to store information relative to the purchased products in NSUserDefaults to give the user the goods, levels or whatever he has paid for.
I recommend this step by step tutorial that helped me implement in-app purchases to answer all your questions.


text:
Q: Pull URL's referral info with NextJS I'm trying to create a referral system for an app by adding a referral link defined as:
const link = `${global.origin}?ref=${address}`;

which returns something like
http://localhost:3000/?ref='address'
I'm struggling to find a way to get Nextjs to pull just the 'address' part of the url (and define it to be used in a function).

A: If I get it right you can use router.query["ref"] from Next router.


text:
Q: MYSQL syntax error 1064 I just cant figure out why am getting error 1064 from this query
//prep the data for database use
$manufacturer_id = $_GET['id'];
$manufacturer_display_name = mysql_prep($_POST['manufacturer_display_name']);
$manufacturer_name = mysql_prep($_POST['manufacturer_name']);

$query = "UPDATE IT_manufacturer SET
        manufacturer_name = '{$manufacturer_name}',
        manufacturer_display_name = '{$manufacturer_display_name}',
        WHERE manufacturer_id = {$manufacturer_id}
        ";

$result = mysql_query($query, $connection);
confirm_query ($result);

If I echo the variables $manufacturer_name, $manufacturer_display_name, $manufacturer_id they all have values but am getting this error
could not excecute queryYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE manufacturer_id = 1' at line 4 error number 1064
Any help

A: Remove the comma before where, should be
    $query = "UPDATE IT_manufacturer SET manufacturer_name = '{$manufacturer_name}',
                 manufacturer_display_name = '{$manufacturer_display_name}'
                 WHERE manufacturer_id = {$manufacturer_id} ";

commas only separate different variables being set, not the set from the where.

A: Remove the comma before the where:
'{$manufacturer_display_name}', WHERE manufacturer_id
                             ^^^


text:
Q: jQuery Datatables filtering a column when the columns content is html I have a column in a dataTable that I want to filter. I can filter by columns which are defined like this:
"columns": [
    {
        "data": function (data) {
             return data['columnToFilter'];
        }
    },
];

But, I can't find a way to filter columns which are more than the original value, such as this one:
"columns": [
    {
        "data": function (data) {
            return '
' + data['columnToFilter'] + '
';
         }
    }
];

How can I tell dataTables what raw the value (without the html) of the second column is?
Here is my code that does the filtering:
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        // tabLocation can only be filtered if the value is returned without additional html
        var tabLocation = data[0];
        if ($("#myFilter").hasClass("down")) {
            return true;
        } else {
            if (tabLocation == 0) {
                return true;
            }
        }
    }
);

$.fn.toggleText = function(t1, t2){
    if (this.text() == t1) this.text(t2);
    else                   this.text(t1);
    return this;
};

A: The solution I used was this:
"columns": [
    {
        "data": function (data) {
            return data['columnToFilter'];
        },
        "render": {
            "display": function ( data, type, row, meta ) {
                return '
' + data['columnToFilter'] + '
';
            },
        },
        "bSortable": false,
    },
];


text:
Q: Reading a symmetric matrix from file that omits upper triangular part Using R, what is the best way to read a symmetric matrix from a file that omits the upper triangular part.  For example,
1.000
.505  1.000
.569  .422  1.000
.602  .467  .926  1.000
.621  .482  .877  .874  1.000
.603  .450  .878  .894  .937  1.000

I have tried read.table, but haven't been successful.

A: I copied your text, and then used tt <- file('clipboard','rt') to import it. For a standard file:
tt <- file("yourfile.txt",'rt')
a <- readLines(tt)
b <- strsplit(a,"  ") #insert delimiter here; can use regex
b <- lapply(b,function(x) {
  x <- as.numeric(x)
  length(x) <- max(unlist(lapply(b,length)));
  return(x)
})
b <- do.call(rbind,b)
b[is.na(b)] <- 0
#kinda kludgy way to get the symmetric matrix
b <- b + t(b) - diag(b[1,1],nrow=dim(b)[1],ncol=dim(b)[2]

A: Here's a read.table and loopless and *apply-less solution:
txt <- "1.000
.505  1.000
.569  .422  1.000
.602  .467  .926  1.000
.621  .482  .877  .874  1.000
.603  .450  .878  .894  .937  1.000"
 # Could use clipboard or read this from a file as well.
mat <- data.matrix( read.table(text=txt, fill=TRUE, col.names=paste("V", 1:6))  )
mat[upper.tri(mat)] <- t(mat)[upper.tri(mat)]
> mat
        V1    V2    V3    V4    V5    V6
[1,] 1.000 0.505 0.569 0.602 0.621 0.603
[2,] 0.505 1.000 0.422 0.467 0.482 0.450
[3,] 0.569 0.422 1.000 0.926 0.877 0.878
[4,] 0.602 0.467 0.926 1.000 0.874 0.894
[5,] 0.621 0.482 0.877 0.874 1.000 0.937
[6,] 0.603 0.450 0.878 0.894 0.937 1.000

A: I'm posting but I like Blue Magister's approach wat better.  But maybe there's something in this that's of use.
mat <- readLines(n=6)
1.000
.505  1.000
.569  .422  1.000
.602  .467  .926  1.000
.621  .482  .877  .874  1.000
.603  .450  .878  .894  .937  1.000

nmat <- lapply(mat, function(x) unlist(strsplit(x, "\\s+")))
lens <- sapply(nmat, length)
dlen <- max(lens) -lens
bmat <- lapply(seq_along(nmat), function(i) {
    as.numeric(c(nmat[[i]], rep(NA, dlen[i])))
})
mat <- do.call(rbind, bmat)
mat[upper.tri(mat)] <- t(mat)[upper.tri(mat)]
mat

A: Here is an approach which also works if the dimensions of the matrix are unknown.
# read file as a vector
mat <- scan("file.txt", what = numeric())

# calculate the number of columns (and rows)
ncol <- (sqrt(8 * length(mat) + 1) - 1) / 2

# index of the diagonal values
diag_idx <- cumsum(seq.int(ncol))

# generate split index
split_idx <- cummax(sequence(seq.int(ncol)))
split_idx[diag_idx] <- split_idx[diag_idx] - 1

# split vector into list of rows
splitted_rows <- split(mat, f = split_idx)

# generate matrix
mat_full <- suppressWarnings(do.call(rbind, splitted_rows))
mat_full[upper.tri(mat_full)] <- t(mat_full)[upper.tri(mat_full)]

   [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
0 1.000 0.505 0.569 0.602 0.621 0.603
1 0.505 1.000 0.422 0.467 0.482 0.450
2 0.569 0.422 1.000 0.926 0.877 0.878
3 0.602 0.467 0.926 1.000 0.874 0.894
4 0.621 0.482 0.877 0.874 1.000 0.937
5 0.603 0.450 0.878 0.894 0.937 1.000

A: This won't work in the OP's case because the diagonal was 1, but if the diagonal is zero or missing, then you can use as.dist%>%as.matrix to copy the lower diagonal to the upper diagonal and set the diagonal to zero:
input=" Pop0    Pop1    Pop2
Pop0
Pop1    0.015
Pop2    0.079   0.083
Pop3    0.014   0.016   0.073"

as.matrix(as.dist(cbind(read.table(text=input,fill=T),NA)))

Result:
      Pop0  Pop1  Pop2  Pop3
Pop0 0.000 0.015 0.079 0.014
Pop1 0.015 0.000 0.083 0.016
Pop2 0.079 0.083 0.000 0.073
Pop3 0.014 0.016 0.073 0.000

In my case the input had column names, so read.table(fill=T) was automatically able to determine the number of columns and IRTFM's trick of specifying col.names=1:4 was not neeeded.


text:
Q: Failed to deploy path that does not exist I am following this guide to create and deploy a web app on Azure. I am using VSCode and when I am trying to deploy via VSCode I get the following error:
Failed to deploy path that does not exist:
MyFirstAzureWebApp/bin/Release/net5.0/publish

My resource group and plan and web service are all created just fine, but if I look in the "MyFirstAzureWebApp/bin" directory there are no "Release" directory only a "Debug" directory.
Why is this and how can I fix it?
Thank you
Søren

A: I have tried with two web apps in VS Code and observed the issue:
Release folder will be added to the bin when adding config file during deployment to Azure Web App Service.
I followed the below steps:

*

*Open Vs Code > Create a folder 'MyAzureFirstWebApp' > Open Terminal > Run the below command:
dotnet new webapp -f net5.0

*Then next command dotnet run and got some files in bin folder but no release folder created.

*Next, I have Created the App Service Plan and Web App Service in the Azure Portal.

*In the VS Code, Install Azure Extension and Select that Azure Icon from the left index, where you will see your Subscriptions, resource groups, app services, functions etc.

Select Your subscription, resource group and then app service you create just now.

*Click on deploy option. It will ask you "Add Config to your current project" click on add and then immediately you'll get the release folder.

Below screenshot shows you the added release folder while adding config to the project:
This is my second web app

This is my first web app:

And the deployed successfully and the


text:
Q: How can I perform an inspect element in Chrome on my Galaxy S3 Android device? How can I perform an inspect element in Chrome on my Galaxy S3 Android device?
I've tried a couple of guides online, one saying to use this android SDK thing to run adb forward tcp:9222 localabstract:chrome_devtools_remote, but all that says is "error:device not found".
Anyone have any ideas on how to do this?

A: To start with you'll need the Android SDK to get started: http://developer.android.com/sdk/index.html BUT select for existing IDE so you get the tools rather than all of Android Studio.
In Chrome Beta on your Android device do the following:
Menu > Settings > Developer Tools > Enable USB Debugging
Hit the home key on the device and go to Settings > Developer Options > Enable USB Debugging
[Note: If you can't see Developer Options, go to Settings > About Device > Then tap the Build Number a number of times and eventually you'll see a message saying you are now a developer or something similar]
Connect your phone to your Computer via USB
On your Desktop open Chrome Canary (I think stable and Beta currently have issues):
In the address bar type: chrome://flags and enable - "Enable Developer Tools experiments" and hit the Relaunch button that appears.
Once it's relaunched open a terminal and run adb devices, you should now see your device appear in the list. When it has, in Canary go to chrome://inspect there you will see your device, so now click inspect.
This will open up devtools for your Chrome on Android.
Now click on the cog in the corner, then go to Experiments > Enable Port Forwarding (If you don't see port forwarding, you might not be in Chrome Beta)
Once Port forwarding is enabled, close and open dev tools.
Go back to the cog and select Port Forwarding, then type in the port you want to forward (i.e. for locahost:9000 on my local machine I'd type 9000 [Device port] and 127.0.0.1:9000 [Target]
There is a bug open where the first port is ignored, so it might be worth hitting enter on the first line and re-entering the same details on the second line.
You can now put localhost:9000 (or your port number) in Chrome for Android and view the site and use DevTools to inspect the page.
More details under Reverse Port Forwarding section of this site: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

A: You can now do this without the use of Android SDK.
In the latest version of chrome (I am working on 34.0.x):

*

*Navigate to chrome://inspect/

*Check Discover USB Devices

*Plug in your phone via USB. A popup should spawn asking for permission to connect to your computer. Accept it.

There will now be an item on the chrome://inspect/ pages for your phone, and you can click inspect. Dev tools will spawn and voila!

A: for Remote Debugging on Android with Chrome:
try this https://developer.chrome.com/devtools/docs/remote-debugging

A: Update: 8-20-2015
Please note the instructions have changed since this question was asked 2 yrs ago.
So on Newer versions of Android and Chrome for Android. You need to use this.
https://developers.google.com/web/tools/setup/remote-debugging/remote-debugging?hl=en
Original Answer:
I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.
Try this with the SDK

*

*Chrome for Mobile - Settings > Developer Tools > [x] Enable USB Web debugging

*Device - Settings > Developer options > [x] USB debugging

*Connect Device to Computer

*Enable port forwarding on your computer by doing the following command below
C:\adb forward tcp:9222 localabstract:chrome_devtools_remote
Go to http://localhost:9222 in Chrome on your Computer
TroubleShooting:
If you get command not found when trying to run ADB, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it
C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote

If you get "device not found", then run adb kill-server and then try again.

A: I have an S3 and used this guide from Google:
https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Really easy, works flawlessly.

A: Mainly follow the guide here https://developers.google.com/chrome-developer-tools/docs/remote-debugging. But ...

*

*For Samsung devices don't forget to install Samsung Kies.

*For me it worked only with Chrome Canary, not with Chrome.

*You might also need to install Android SDK.

A: I wasn't able to ever accomplish this but rather used view html source apps available on the Play Store to simply look for the element.

A: Keep in mind that if you want to use the chrome inspect in Windows,
besides enabling usb debugging on you mobile, you should also install the usb driver for Windows.
You can find the drivers you need from the list here:
http://androidxda.com/download-samsung-usb-drivers
Furthermore, you should use a newer version of Chrome mobile than the one in your Desktop.


text:
Q: GCC 11: How to tell CMake I don't want the default C++ GNU extensions? So, back in GCC 10.2 (which used C++14 as the default), I could use this to tell CMake I wanted -std=gnu++17:
target_compile_features(mytarget PRIVATE cxx_std_17)
set_target_properties(mytarget PROPERTIES
    CXX_STANDARD_REQUIRED ON
)

...which I actually didn't want, so I used CXX_EXTENSIONS OFF to force -std=c++17:
target_compile_features(mytarget PRIVATE cxx_std_17)
set_target_properties(mytarget PROPERTIES
    CXX_STANDARD_REQUIRED ON
    CXX_EXTENSIONS OFF  # -std=c++17 instead of gnu++17
)

Enter GCC 11.1. The default now is the 2017 version of the ISO C++ standard, so that the first snippet above doesn't generate any -std flag for GCC, which is compatible with GCC 11's man page:

c++17: The 2017 ISO C++ standard plus amendments.
gnu++17: GNU dialect of -std=c++17.  This is the default for C++ code.

The problem is that the second CMake snippet above also doesn't generate any -std flag. How do I do it now, is this a bug in CMake? How to I tell it I want an explicit -std=c++17 flag?
Remark 1: I know I can just stick -std=c++17 in target_compile_options, but I don't want to do that, do I?
Remark 2: Sanity check: if I change cxx_std_17 to cxx_std_20, then CXX_EXTENSIONS OFF correctly switches from -std=gnu++2a to -std=c++2a.

A: The answer to this question is that it is a bug in CMake 3.21 (but technically not 3.20, which is older than the compiler in question) that will be fixed in 3.22, most likely by the following merge request: https://gitlab.kitware.com/cmake/cmake/-/merge_requests/6177


text:
Q: galleria jquery plugin slow with lots of images Has anyone extended the galleria plugin to handle lots of images (over 200)?  The large number of thumbnails makes the initial load take a really long time.

A: You need to use separate thumbnail files and option preload.


text:
Q: Shutdown/reboot freezes this is my first time on this forum. I have a problem on my ubuntu installation, every time I restart or shut down my computer it freezes. Every time I get the error that I attach below, I have been using Ubuntu for years and this is the first time that I have not been able to solve this problem. My computer is a 4th generation intel i7 with 16gb of RAM. My laptop hardware info here.
Screenshot error
I appreciate any comments to solve this problem, thank you.

A: Do you need to have a device plugged into your SD card at all times? From the looks of the error, the SD reader is losing power (as part of the shut down process) before /oldroot is unmounted. As a result, when the OS tries to unmount that device, there is no SD reader anymore and the system waits ... and waits ... and waits ... until it times out.
There are a couple of options for you:

*

*Remove SD cards before shutting down

*Add a script that runs whenever you shut down (or restart) the computer to first unmount any SD cards before initiating the shut down sequence


text:
Q: Iterating through a Multidimensional Array in php without known keys I am writing a web application and I believe one of the parts requires a
multidimensional array. The array holds a list of applications in a database.
I want to be able to display the list of applications by the individuals name or
a unique ID. I have this part working. Then I want to click on an individual
application and only pull up that particular row of information to fill in a form.
Currently when I do this it either brings up all of the rows from the database or
the first row only. Does anyone have any suggestions?
I am not great with explanations so I am including parts of my code. I am sorry
it's so long. I tried to reduce it as much as possible. Even though its included
in the code, i didn't include config.php because it's just my database connection.
userList.php:
<?php
include("config.php");

?>
<!DOCTYPE html>

Test

Users

<?php
require_once("/class/users.php");
$rowt = array(array());
$rowt = users::fillForm($rowt);
foreach($rowt as $test) {
    if(is_array($test))
    {
    echo "".$test['name']."
";
    }
}
?>

userDisplay.php:
<!DOCTYPE html>

Tester

      <?php
      include("config.php");
      //declare array
      $rowt = array(array());
      //pass array into class function
      //since functions can't return more than one variable, you have to pass the
      //array and set it equal to the original variable while calling the pdo function
      $rowt = users::fillForm($rowt);
        foreach($rowt as $test=> $rowt){
      ?>

Application for <?php echo $rowt['name']?>

Name
             Phone Number
             Best Time to Call

<output type='text' maxlength="30" required name='name'><?php echo $rowt['name']?></output>
             <output type="text" maxlenth="30" required  name="p_num"><?php echo $rowt['phone_number']?></output>
             <output type='text' maxlength="30" required name='bc_time'><?php echo $rowt['best_call_time']?></output>

             Visa Status
             IT Experience
             Relevant Experience

<output type='text' maxlength="30" required name='v_status'><?php echo $rowt['visa_status']?></output>
             <output type='text' maxlength="30" required name='it_exp'><?php echo $rowt['it_exp']?></output>
             <output type='text' maxlength="30" required name='rel_exp'><?php echo $rowt['relevant_exp']?></output>

             Description

             <output name="description" rows="4" cols="100"></output><?php echo $rowt['description']?>>

<?php
}
echo "Back";
?>

Functions from users.php users class:
public function insertForm() {
    $correct = false;
    try {
          $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
          $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $sql = "INSERT INTO user(name, phone_number, best_call_time, description,
          visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
          :v_status, :it_exp, :rel_exp)";

          $stmt = $con->prepare($sql);
          $stmt->bindValue("name", $this->name, PDO::PARAM_STR);
          $stmt->bindValue("p_num", $this->p_num, PDO::PARAM_STR);
          $stmt->bindValue("bc_time", $this->bc_time, PDO::PARAM_STR);
          $stmt->bindValue("v_status", $this->v_status, PDO::PARAM_STR);
          $stmt->bindValue("it_exp", $this->it_exp, PDO::PARAM_STR);
          $stmt->bindValue("rel_exp", $this->rel_exp, PDO::PARAM_STR);
          $stmt->bindValue("description", $this->description, PDO::PARAM_STR);
          $stmt->execute();
          return "Entry Successful
 Home";
        }catch(PDOException $e) {
          return $e->getMessage();
        }
    }
  public static function fillForm($rowt) {
      $successt = false;
      try{
        $conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql1 = "SELECT * FROM user";
        $stmt1 = $conn->prepare($sql1);
        $stmt1->execute();
        $rowt = $stmt1->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
        return $rowt;
      }catch (PDOException $et) {
        echo $et->getMessage();
        return $successt;
      }
    }

A: There is a lot going on here, but if I get the gist of your question you want to be able to return one individual user when a row in a list of users is clicked. To do that you would need to update your SQL query to pull a particular user. Something along the lines of:
// Formatting into a class to cut down on repetition.
<?php
class User {
  private $dbConnect;

  // functionally these two are similar but I separated users and user
  // for clarity of purpose.
  public function getUsers()
  {
    // Enumerating your select columns is clearer, and more efficient.
    $sql = "SELECT name, phone_number, best_call_time, description,
      visa_status, it_exp, relevant_exp
      FROM user";

    $result = $this->makeQuery($sql);

    return ($result) ? $result : array();
  }

  public function getUser($name)
  {
    // Enumerating your select columns is clearer, and more efficient.
    $sql = "SELECT name, phone_number, best_call_time, description,
      visa_status, it_exp, relevant_exp
      FROM user
      WHERE name = :name";

    $param = $this->prepareUserInfo(array('name' => $name));

    $result = $this->makeQuery($sql, $param);

    return ($result) ? $result : array();
  }

  public function createUser($userInfo)
  {
    $sql = "INSERT INTO user(name, phone_number, best_call_time, description,
    visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
    :v_status, :it_exp, :rel_exp)";
    $params = $this->prepareUserInfo($userInfo);

    try {
      $this->connect();

      $stmt = $this->dbConnect->prepare($sql);
      $stmt = $this->bindParams($stmt, $data);
      $stmt->execute();
      return "Entry Successful
 Home";
    } catch(PDOException $e) {
      return $e->getMessage();
    }

  }

  private function prepareUserInfo($userInfo)
  {
    $infoArray = array();

    foreach ($userInfo as $key => $value) {
      // Going with your original code I'm hardcoding param type here, but
      // you could easily write a check for data type and set param dynamically.
      $infoArray[] = array(
        'key' => $key,
        'value' => $value,
        'type' => PDO::PARAM_STR,
      );
    }
    return $infoArray;
  }

  private function makeQuery($sql, $data = array())
  {
    try{
      $this->connect();
      $stmt = $this->dbConnect->prepare($sql);

      if (!empty($data)) {
        $stmt = $this->bindParams($stmt, $data);
      }

      $stmt->execute();
      $result = $stmt->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
      return (!empty($result)) ? $result : false;
    } catch (PDOException $e) {
      echo $e->getMessage();
      return false;
    }
  }

  private function bindParams($stmt, $data)
  {
    foreach ($data as $item) {
      $stmt->bindValue("name", $this->name, PDO::PARAM_STR);
      $stmt->bindValue($item['key'], $item['value'], $item['type']);
    }
    return $stmt;
  }

  private function connect()
  {
    $dbConnect = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
    $dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->dbConnect = $dbConnect;
  }
}

?>

From there your click handler would need to trigger a User->getUser('some name'); request. You could take this abstraction further by separating your PDO connect into it's own class and handle query building and execution from there.
Seconding the above comment about not mixing your presentation with your data layer. Check out a templating engine like Twig or (less advisable but sometimes necessary) roll your own by building a view loader that loads template files to an output buffer, adds dynamic variables, and returns a rendered string.


text:
Q: Determine if two lines are parallel and distinct. Ok, so I have a vector equation: $\langle x,y\rangle = \langle 2,0,9\rangle + t\langle -1,5,2\rangle$ and another line $\langle x,y\rangle = \langle 3,-5, 10\rangle + t\langle 1,-5,-2\rangle$. How do I know whether the two lines are parallel distinct?
What I did:
$n_1 = \langle -1,5,2\rangle$;
$n_2 = -\langle -1,5,2\rangle$
Since the direction vectors are the same, they are parallel.
But how do I know they are distinct? My teacher tried to explain this to me, but didn't do a very good job.

A: As long as the direction vectors are scalar multiples, the lines will be parallel. To show they are distinct, you need to show, for example, that $(3,-5,10)$ is not on the first line. You'd need $3=2-t$, so $t=-1$. Do the other coordinates match up?


text:
Q: Use Jsoup to select an HTML element with no class Consider an html document like this one

...

...

    ...

...

    ...

How could we select all of the p elements, but excluding the p element with random_class_name class?

A: Elements ps = body.select("p:not(.random_class_name)");

You can use the pseudo selector :not
If the class name is not known, you still can use a similar expression:
Elements ps = body.select("p:not([class])");

In the second example I use the attribute selector [], in the first the normal syntax for classes.
See the Jsoup docu about css selectors

A: Document doc = Jsoup.parse(htmlValue);
    Elements pElements = doc.select("p");
    for (Element element : pElements) {
        String class = element.attr("class");
        if(class == null){
            //.....
        }else{
             //.....
        }
    }


text:
Q: Converting binary to hex: error only on 2-7 I'm converting 4digit binary to single digit hex using a basic switch-case statement and the code will not run for digits 0010-0111 for some reason and I have no idea why.
Here is what I have:
void BinHex() {
        int binin;
        cout << "Enter Binary(####): " << endl;
        cin >> binin;

        switch(binin){
                case 0000: cout << "Hex: 0" << endl; break;
                case 0001: cout << "Hex: 1" << endl; break;
                case 0010: cout << "Hex: 2" << endl; break;
                ...
        }
}

All numbers 0,1,8-15 work perfectly fine but the middle numbers do not. Any ideas on what could be causing this to error out/not run?

A: This case:
case 0010: cout<<"Hex: 2\n"; break;

Will not fire for binin == 10. It will fire for binin == 8, because 0010 is an octal literal. Just drop the leading 0s so that the value gets interpreted as a decimal literal instead.


text:
Q: Dapper: custom type handler for struct My aim is to create custom struct that wrapping double and save it to database using Dapper. Unfortunately I've faced a problem I can't fix.
I've created following struct:
public struct MyDouble
{
        private readonly double value;
        public static implicit operator MyDouble(double val)
        {
            return new MyDouble(val);
        }

        public static explicit operator double(MyDouble val)
        {
            return val.value;
        }

        public static explicit operator MyDouble(int val)
        {
            return new MyDouble(val);
        }

        public MyDouble(double val)
        {
            this.value = Process(val);
        }

        public double GetDouble()
        {
            return this.value;
        }
}

and added custom type handler as it described here (https://medium.com/dapper-net/custom-type-handling-4b447b97c620)
public class MyDoubleTypeHandler : SqlMapper.TypeHandler<MyDouble>
{
    public override MyDouble Parse(object value)
    {
        return (MyDouble)value;
    }

    public override void SetValue(IDbDataParameter parameter, MyDouble value)
    {
        parameter.DbType = DbType.Double;
        parameter.Value = value.GetDouble();
    }
}

My custom objects with MyDouble prop inside:
public class MyObject
{
    public MyDouble Prop1 { get; set; }
}

And save method looks like:
public async Task<bool> Save(List<MyObject> data)
{
    SqlMapper.ResetTypeHandlers();
    SqlMapper.AddTypeHandler(new MyDoubleTypeHandler());
    parameters.AddTable("@Data", "dbo.MyObject", data.AsList());

    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        return await connection.ExecuteAsync("name-of-sp", parameters, commandType: CommandType.StoredProcedure);
    }
}

As a result I get this error: "System.ArgumentException: The type of column 'Prop1' is not supported.  The type is 'MyDouble'".
It seems to be that my custom type handler hasn't been registered despite the fact I do it directly by calling SqlMapper.AddTypeHandler(new MyDoubleTypeHandler());
Could anyone help with that problem?
P.S. I'm using Dapper 1.50.5, Dapper.ParameterExtensions 2018.12.7.1 inside Asp.NET Core app (2.1)

A: Looking at the tests in the source code it seems you need to use a different overload to set the Type Handler:
https://github.com/StackExchange/Dapper/blob/master/Dapper.Tests/TypeHandlerTests.cs#L101
and also the Type Handler class is slightly different:
https://github.com/StackExchange/Dapper/blob/master/Dapper.Tests/TypeHandlerTests.cs#L116
as the constructor is set to be private in order to make sure the usual methon
SqlMapper.AddTypeHandler<T>(TypeHandler<T>)
won't be used
.


text:
Q: How do i print a table in C without having to move the vertical lines? I  have to shift the vertical lines like this because the output displays misaligned lines.
    printf("DAY 10                           DAILY SUMMARY REPORT                             ");
    printf("\n+---------------------+--------------++-------------+-------------+------------+");
    printf("\n| Today's             | Total        || Total       | Total       | Under      |");
    printf("\n| Cases               | Cases        || Deaths      | Recovered   | treatment  |");
    printf("\n+---------------------+--------------++-------------+-------------+------------+");
    printf("\nLocal :   %d           |              ||             |             |            |",day10localcase);
    printf("\nImported :%d           |              ||             |             |            |", day10importcase);
    printf("\n          %d          |%d           ||%d            |%d           |%d          |", day10case,day10casetotal,day10deathtotal,day10rectotal,day10treattotal);
    printf("\n+------------------------------------++-------------+-------------+------------+");
    printf("\n                                     ||%.1lf%%         |%.1lf%%        |%.1lf%%       |",day10deathtotalpercent,day10rectotalpercent,day10treattotalpercent);
    printf("\n                                     ++----------------------------------------+");
    printf("\n----------------------------End of Day 10 Reporting-----------------------------");
}


text:
Q: C++ Qt - QTcpSocket - File not found I am using Qt and QTcpSocket to create a small chat client/server application.
When I compile my code, the compiler returns the following error:
main.cpp:3:22: fatal error: QTcpSocket: No such file or directory

This refers to #include <QTcpSocket>.
Where is this library located and how can I install it?

A: You need
QT += network

in your .pro file.  Otherwise the module in which those headers are defined/libraries are built won't be loaded.

A: As I faced the problem and the obvious solution proposed by the documentation and Matt Phillips seemed not to work, I would add to check ALL your .pro files of all your potential subprojects.
As far I'm concerned, addind QT *= network did not work in the main .pro and had to be put in the one actually using the QTcpSocket and QTcpServer objects.


text:
Q: Durandal null/empty route I have a master/detail situation. I'd like to employ a child router so that I can (a) make full use of the history module and (b) trigger the entrance transition on only the child. Here's my setup:
Shell.js
// configure the shell router
router.map([{
    ...
},{
    route: 'users*edit',
    title: 'User List',
    moduleId: 'viewmodels/users'
}]).activate();

Users.js
this.router = router
    .createChildRouter()
    .makeRelative({ fromParent: true })
    .map({ route: ':id', moduleId: 'viewmodels/edit' })

When I navigate to #/users/5 it works brilliantly. However, when I navigate to #/users, as expected, it fires a route not found, cancels navigation, and returns me to #/users/5. How should I configure this to disable the child view when the route is not found? Ideally, I'd like to have something like this:
Users.js
this.router = router
    .createChildRouter()
    .makeRelative({ fromParent: true })
    .map([
        { route: ':id', moduleId: 'viewmodels/edit' },
        { route: '', moduleId: null }
])

where the router will successfully navigate to the '' route but the null parameter will instruct it to simply empty the router binding handler.

A: This is not currently a feature of Durandal. I have added support for this kind of thing in a pull request, which you can find here, in case you would like to add support for null routes to your app.


text:
Q: NVME issue |nvme2: Failed to configure AEN (cfg 200) I have installed 8 NVMEs and 2 M.2 SSD drives in my server but the system only shows 6 NVMEs and 2 M.2 SSD,
do you know what this error means?

*

*nvme2: Failed to configure AEN (cfg 200)

*nvme4: Failed to configure AEN (cfg 200)

*

*dmesg command shows:

~$ dmesg | grep nvme
[  495.699325] nvme nvme0: pci function 10000:01:00.0
[  495.704738] nvme nvme1: pci function 10000:02:00.0
[  495.712038] nvme 10000:01:00.0: PCI INT A: no GSI
[  495.717508] nvme nvme2: pci function 10000:03:00.0
[  495.717561] nvme nvme3: pci function 10000:04:00.0
[  495.717612] nvme nvme4: pci function 10001:01:00.0
[  495.717659] nvme nvme5: pci function 10001:02:00.0
[  495.717707] nvme nvme6: pci function 10001:03:00.0
[  495.717747] nvme 10000:03:00.0: PCI INT A: no GSI
[  495.717757] nvme nvme7: pci function 10001:04:00.0
[  495.717881] nvme 10000:04:00.0: PCI INT A: no GSI
[  495.717992] nvme 10001:01:00.0: PCI INT A: no GSI
[  495.718066] nvme 10001:02:00.0: PCI INT A: no GSI
[  495.718150] nvme 10001:03:00.0: PCI INT A: no GSI
[  495.718243] nvme 10001:04:00.0: PCI INT A: no GSI
[  495.837239] nvme 10000:02:00.0: PCI INT A: no GSI
[  495.931032] nvme nvme2: Shutdown timeout set to 6 seconds
[  495.931079] nvme nvme5: Shutdown timeout set to 6 seconds
[  495.931120] nvme nvme7: Shutdown timeout set to 6 seconds
[  495.931186] nvme nvme6: Shutdown timeout set to 6 seconds
[  495.931228] nvme nvme4: Shutdown timeout set to 6 seconds
[  495.931261] nvme nvme4: Could not set queue count (16390)
[  495.931264] nvme nvme4: IO queues not created
[  495.931289] nvme nvme4: Failed to configure AEN (cfg 200)
[  495.931295] nvme nvme3: Shutdown timeout set to 6 seconds
[  495.936094] nvme nvme6: 32/0/0 default/read/poll queues
[  495.936173] nvme nvme3: 32/0/0 default/read/poll queues
[  495.937101] nvme nvme2: Could not set queue count (16390)
[  495.938696] nvme nvme7: 32/0/0 default/read/poll queues
[  495.938815] nvme nvme0: Shutdown timeout set to 6 seconds
[  495.942455] nvme nvme0: 32/0/0 default/read/poll queues
[  495.947018] nvme nvme5: 32/0/0 default/read/poll queues
[  495.949142] nvme nvme2: IO queues not created
[  496.044019] nvme nvme2: Failed to configure AEN (cfg 200)
[  496.058879] nvme nvme1: Shutdown timeout set to 6 seconds
[  496.068279] nvme nvme1: 32/0/0 default/read/poll queues
*
~$ lsblk
NAME      MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0       7:0    0    12G  0 loop
`-live-rw 253:0    0    12G  0 dm   /
sda         8:0    0 447.1G  0 disk
sdb         8:16   0 447.1G  0 disk
nvme6n1   259:0    0   1.8T  0 disk
nvme3n1   259:1    0   1.8T  0 disk
nvme7n1   259:2    0   1.8T  0 disk
nvme0n1   259:3    0   1.8T  0 disk
nvme5n1   259:4    0   1.8T  0 disk
nvme1n1   259:5    0   1.8T  0 disk
thanks


text:
Q: Reducing a system of Linear Recurrences The number of ways to lay unit-length matchsticks on a $2 \times n$ grid (with respect to vertices) appears to be given by OEIS sequence A093129, but I found it a different way, and I'm looking for insight into how to move from one to the other.
In particular, it looks like $A093129(n) = a_1(n + 1) + a_5(n + 1)$ where
$$
\begin{align}
a_1(n+1) &= a_1(n) + a_5(n)\\
a_2(n+1) &= a_1(n) + a_2(n) + 2a_5(n) + a_6(n) + a_7(n)\\
a_3(n+1) &= a_3(n) + a_5(n) + a_6(n)\\
a_4(n+1) &= a_4(n) + a_5(n) + a_6(n)\\
a_5(n+1) &= a_2(n) + a_5(n) + a_6(n) + a_7(n) \\
a_6(n+1) &= a_3(n) + a_5(n) + a_7(n)\\
a_7(n+1) &= a_4(n) + a_5(n) + a_6(n)
\end{align}
$$
with initial conditions $$
  a_1(0) = a_2(0) = 1\\
  a_3(0) = ... = a_7(0) = 0.
$$
In particular, it appears that $$
\begin{align}
a_1(n + 1) + a_5(n + 1) &= (a_1 + a_5)(n + 1) \\
  &= A093129(n)\\
  &= 5\cdot(A093129(n - 1) + A093129(n - 2))\\
  &= 5\cdot((a_1 + a_5)(n) - (a_1 + a_5)(n - 1)).
\end{align}
$$

Questions

*

*How does one prove this recursion?

*Is there a general strategy for transforming such "systems of linear recurrences" to a single linear recurrence? (Can this even be done in general?)

An Idea
One thing that I try is to write this as $$
  (a_1 + a_5)(n) = \begin{bmatrix}
    1 \\ 0 \\ 0 \\ 0 \\ 1 \\ 0 \\ 0
  \end{bmatrix}^T
  \begin{bmatrix}
    1 & 0 & 0 & 0 & 1 & 0 & 0 \\
    1 & 1 & 0 & 0 & 2 & 1 & 1 \\
    0 & 0 & 1 & 0 & 1 & 1 & 0 \\
    0 & 0 & 0 & 1 & 1 & 1 & 0 \\
    0 & 1 & 0 & 0 & 1 & 1 & 1 \\
    0 & 0 & 1 & 0 & 1 & 0 & 1 \\
    0 & 0 & 0 & 1 & 1 & 1 & 0
  \end{bmatrix}^n
  \begin{bmatrix}
     1 \\ 1 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0
  \end{bmatrix}
$$ and do some linear algebra trickery to see if I can come up with some sort of closed form—but in this case, I'm really more interested in getting a recurrence.


text:
Q: Keyboard shortcuts in iOS? Is it possible to capture command-key sequences in 3rd party iPad/iPhone apps?
Long version:
On my excellent journey of discovery vis-a-vis my new iPad with it's gleaming keyboard dock, I discovered, much to my joy, that when editing text in standard issue text views; commands ranging from ⌘C/⌘P for copy-paste and ^A, ^B, ^E and friends for line and character jumping works.
So far so good, yeah? Problem is, this enthralling behaviour seems limited to text fields, and more specifically, standard issue text fields. What I would really like is to capture events like these for my own use.
An issue I often find with a lot of apps is that they tend to either be close to useless, or at least cumbersome, without the keyboard dock (e.g. the iWork Suite), or close to useless, or at least cumbersome, with the keyboard dock (most other applications that don't rely heavily on text input, but rather touch gestures [that is to say, most other applications period]).
Many games, for instance Civilization Revolutions, and similar, would benefit massively from just the simple addition of the ability to use the arrow keys to move units and the enter key to end turn.
So the question, then, as stated above: Is there a way to capture and respond to these events in order to offer an alternative to touch commands for those that desire this and have the hardware?
Disclaimer: I have no intention of developing applications that rely exclusively on keyboard input, of course, and nor should anyone else. The touch interface is paramount. It's just not always completely practical.

A: The only way (that I know of) to get input from the keyboard in iOS is using the UITextInput protocol.  Unfortunately, the protocol doesn't give you the raw keys that were pressed, and instead sends you messages like "insert this string" and "move the caret to this position."  So in order to know that an arrow key was pressed would require you to do some digging.
As for shortcuts with modifier keys, like copy/paste or undo/redo, Apple only seems to support the basics, and doesn't allow you to create custom ones.  They use methods in UIResponder: –canPerformAction:withSender: and undoManager.
So if I were writing a game and wanted to take advantage of the keyboard I would subclass UIResponder and have it conform to the UITextInput protocol.  And then make it the first responder.  This however will probably bring up the software keyboard if a physical one is not present.
My own disclaimer: I haven't done all the hard work to use UITextInput in a way it wasn't meant to be used, so I don't know how feasible it would be to actually get it working.  And I don't really want to.  Rather, let's all file bug reports to get Apple to create an API that allows us to get more precise input from the keyboard.

A: In iOS 7, the UIResponder property keyCommands and the class UIKeyCommand were added to support shortcuts. Simply override keyCommands to return an array of UIKeyCommand and you should be good to go.

A: Worth mentioning: Though the details are currently under NDA, Apple is adding support for keyboard shortcuts/events in iOS 7.
I suspect it will work similarly to how it works on Mac OS X, which is briefly described in this answer to a similar question.


text:
Q: How to find the biggest values of (three values) without using looping them? [Python] i'm new to programming and this has got me stumbling and i was thinking of doing something like this but i can't got further
num1 = int(input('What is the first number?:'))
num2 = int(input('What is the second number?:'))
num3 = int(input('What is the third number?:'))

[[After this my mind is thinking of elif statements and using [and,or]]

A: Add all of your variables to a list and then you can use the max function like so max(lista)
num1 = int(input('What is the first number?: '))
num2 = int(input('What is the second number?: '))
num3 = int(input('What is the third number?: '))

lista = [num1, num2, num3]

biggest = max(lista)

print(f"{biggest} is the largest value.")

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 max.py
What is the first number?: 10
What is the second number?: 3
What is the third number?: 8
10 is the largest value.

Just for a little bonus, didn't include handling TypeErrors but want to give you some ideas where you can go with this little project:
while True:

    numbers = int(input("How many numbers would you like to enter: "))

    values = []

    for i in range(numbers):
        if i == numbers - 1:
            values.append(int(input(f"Enter 1 number: ")))
        else:
            values.append(int(input(f"Enter {numbers - i} numbers: ")))

    print(f"\nThe largest number entered was {max(values)}")

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 max.py
How many numbers would you like to enter: 5
Enter 5 numbers: 10
Enter 4 numbers: 8
Enter 3 numbers: 29
Enter 2 numbers: 13
Enter 1 number: 22

The largest number entered was 29

A: Python's max(list) does the job for you.
If you wish to create a function that accepts arbitrary amount of inputs, you can create a function like this.
def my_function(*args):
    return max(args)

A: num1=int(input('What is the first number?:'))
num2=int(input('What is the second number?:'))
num3=int(input('What is the third number?:'))
if(num1>num2 and num1>num2):
    print(num2, 'is the largest value')
elif(num2>num1 and num2>num3):
    print(num2, 'is the largest value')
else:
    print(num3, 'isenter code here the largest value')


text:
Q: split data on a column using pandas I got a column that got data which is comma separated like that
connect,ae8:2030-3062,bras02-ram,0
and need to split it into 3 columns one with 'connect' and second with 'ae8:2030-3062' and third with 'bras02-ram'

A: You can use the split method of pd.Series
df[['A', 'B', 'C']] = df['column_name'].str.split(',', expand=True)


text:
Q: Proper way to let airflow sensor continuous triggering? Is it possible to let airflow sensor continuous triggering?  By continuous triggering what I mean is that for example the sensor will listen to a Kafka topic, and will trigger different DAGs depend on the received message, this will keep running possible forever.

A: The sensor doesn't trigger the dag run, it's a part of the run, but it can block it by staying in running state (or up for rescheduling) waiting certain condition, then all the downstream tasks will stay waiting (None state).
To achieve what you want to do, you can create a sub class from TriggerDagRunOperator to read the kafka topic then trigger runs in other dags based on your needs.
Or you can create a stream application outside Airflow, and use the Airflow API to trigger the runs.

A: If you're using Deferable operators, you should be able to re-defer them after re-entering , untested pseudo code would be something like :

def execute(self,context) -> Any:

    self.defer(AwaitMessageTrigger(), method="execute_complete")

def execute_complete(self,context,event):

    TriggerDagRunOperator(conf=event)
    self.defer(AwaitMessageTrigger(), method="execute_complete")

A: This pattern has been implemented as part of the provider package here.
https://github.com/astronomer/airflow-provider-kafka/blob/main/airflow_provider_kafka/operators/event_triggers_function.py
Example here
https://github.com/astronomer/airflow-provider-kafka/blob/main/example_dags/listener_dag_function.py


text:
Q: how to get the earliest date Excel support programmatically Excel AddIn, C#, UDF,
MyUDF calls a web service to retrieve certain date. Sometimes the date returned is not in range of Jan-1-1900 to Dec-31-9999 (Excel Date Range). E.g. in one case returned date is Jan-2-0002 (valid in C# but not valid in Excel), then Excel crashes.  I do not hard code "Jan-1-1900", so wonder if there is a way that I can get it programmatically. thanks

A: Inside Excel, convert the date corresponding to 1 into a string that you can parse:
=TEXT(1,"dd-mm-yyyy")

which should give you 01-01-1900 or 02-01-1904 depending on the date system chosen (hat tip to barrowc!). Note how the date systems don't only differ by four years but also by the fact that in one case the value 1 corresponds to January 1st (in 1900) and in the other it is 0 which corresponds to January 1st (in 1904). For a given Workbook, the Workbook.Date1904 Property can tell you which date system is being used.


text:
Q: Script to save settings Is there a way to save some settings to the local computer that is not cookies with a user script?
It is difficult to make a user script that is for multiple domains if the settings are not global.
From a comment: "I am using scriptish ".

A: Absolutely, it's very easy. The Greasemonkey wiki documents four methods that allow you to deal with saving values, which can be settings or anything else you want to store:

*

*GM_setValue(name, string)

*GM_getValue(name[, default])

*GM_deleteValue(name)

*GM_listValues()
You might want to check out the main API page for other useful methods, and there's also a complete metadata block documentation page.
The only way this might not work is in a Google Chrome Content Script. There are a few solutions though: you can either use the Google Chrome GM_* userscript in addition to yours, or you can make the GM_setValue and GM_getValue methods available by including this at the beginning of your user script (from Devine.me):
if (!this.GM_getValue || (this.GM_getValue.toString && this.GM_getValue.toString().indexOf("not supported")>-1)) {
    this.GM_getValue=function (key,def) {
        return localStorage[key] || def;
    };
    this.GM_setValue=function (key,value) {
        return localStorage[key]=value;
    };
    this.GM_deleteValue=function (key) {
        return delete localStorage[key];
    };
}


text:
Q: recreate js regex match function in php I have a problem with recreation function written in Javascript, to make it work in php. I think that I am really close, but don't understand php syntax that well.
So I have something like that in JS:
function convertStr(str, id) {
  const regexExpression = new RegExp('PR|PD|DD|DPD|DP_AVG', 'g');
  return str.replace(regexExpression, match => match + id);
}

So I try to do the same in php and I have this:
$reg = "/PR|PD|DD|DPD|DP_AVG\g/";
$result = preg_replace($reg, ??, $str)

So I don't know what to put in "??", because as I understand in JS it is my match arrow function match => match + id, but I can't perform it in PHP.
Can anyone help?
Best,
Piotr

A: You should not use a global modifier in PHP preg functions, there are specific functions or arguments that control this behavior. E.g. preg_replace replaces all occurrences in the input string by default.
Use
function convertStr($str, $id) {
  $regexExpression = '~PR|PD|DD|DPD|DP_AVG~';
  return preg_replace($regexExpression, '$0' . $id, $str);
}

Here,

*

*~PR|PD|DD|DPD|DP_AVG~ is a the regex that matches several substring alternatives (note the ~ symbols used as a regex delimiter, in JS, you can only use / for this in the regex literal notation)

*In the replacement, $0 means the whole match value (same as $& in JS regex), and $id is just appended to that value.

So, in JS version, I'd recommend using
return str.replace(regexExpression, "$&" + id);

A: You can also use preg_replace_callback(): http://php.net/manual/en/function.preg-replace-callback.php
Thish method will accept a function as its second parameter which is the same as the JS version.
$str = "...";
$id = 0;
preg_replace_callback("Your regex expression", function($match) {
    return $match[0] + $id;
}, $str);


text:
Q: Creating Bilateral migration Matrix in Stata or R My data is similar to table given below. I have data to province where an individual is living and data on previous province where he was living last year. I want to construct the outflow rate and inflow rate of migrants in Stata or R

Province
Previous Province

Delhi
Mumbai

Mumbai
Kolkata

Kolkata
Mumbai

Delhi
Mumbai

Kolkata
Delhi

Mumbai
Mumbai

I want a matrix which is as follows

Delhi
Mumbai
Kolkata

Delhi
0
2
0

Mumbai
0
1
1

Kolkata
1
1
0

A: table(df)
         Previous_Province
Province  Delhi Kolkata Mumbai
  Delhi       0       0      2
  Kolkata     1       0      1
  Mumbai      0       1      1

In dataframe format:
as.data.frame.matrix(table(df))

        Delhi Kolkata Mumbai
Delhi       0       0      2
Kolkata     1       0      1
Mumbai      0       1      1

pivot_wider(df, names_from = Previous_Province,
             values_from = Previous_Province, values_fn = length,
             values_fill = 0)
# A tibble: 3 × 4
  Province Mumbai Kolkata Delhi
  <chr>     <int>   <int> <int>
1 Delhi         2       0     0
2 Mumbai        1       1     0
3 Kolkata       1       0     1

A: Here's a working example in Stata. First input the data (I added a move_indicator variable to save me a line below!):
clear
input str10(Province Previous_Province) move_indicator
"Delhi"      "Mumbai" 1
"Mumbai"    "Kolkata" 1
"Kolkata"   "Mumbai" 1
"Delhi"     "Mumbai" 1
"Kolkata"   "Delhi" 1
"Mumbai"    "Mumbai" 1
end

Then:
// Collapse to count moves for each pair of Province-PreviousProvince
collapse (sum) N_=move_indicator, by(Province Previous_Province)

// Reshape so that each previous province becomes a column
reshape wide N_, j(Previous_Province) i(Province) string

// Replace zeros with missing
foreach var of varlist N_* {
    replace `var' = 0 if missing(`var')
}

Here we verify that it matches the output you wanted:
* Order and sort to match your example
sort Province
order Province N_Delhi N_Mumbai N_Kolkata
list

The list output is below:
     +------------------------------------------+
     | Province   N_Delhi   N_Mumbai   N_Kolk~a |
     |------------------------------------------|
  1. |    Delhi         0          2          0 |
  2. |  Kolkata         1          1          0 |
  3. |   Mumbai         0          1          1 |
     +------------------------------------------+


text:
Q: Replicate the exact behavior of the FAB from "Inbox by Gmail" I would like to know what is currently the best way to replicate the exact behavior of the Floating Action Button from Inbox by Gmail.
I am talking about this:

In particular I am interested in:

*

*(collapsed) Having an icon A and no label on the FAB

*(clicked collapsed) Animate the expansion of the smaller FABs and the icon swap form A to B on the main FAB

*(expanded) The background of the Activity is faded

*(expanded) The labels have a white background and grey text

*(expanded) The big FAB button, red in the screenshot, has its own label

*(clicked expanded) It starts a custom action and is  toggling the FAB collapse.

I know that there are several similar questions on SO and several FAB libraries out there but I am not aware of a currently supported library that is providing most of this features.
The FAB libraries from Clan, makovkastar and futuresimple are all deprecated or abandoned from several years and anyway don't implement most of the features.
RapidFloatingActionButton seems the most promising but afaik doesn't have support for the label on the mail FAB when expanded (and is also missing the ripple effect for the clicks).
What is currently the best approach to replicate the same behavior of the FAB from Inbox? Should I implement the missing features that I need on top of the RapidFloatingActionButton? Should I build everything from scratch? Or is there a (still maintained) library that does almost everything Inbox is doing?

A: Since I was not able to find a library that fulfilled all my needs, I made my own library: https://github.com/leinardi/FloatingActionButtonSpeedDial


text:
Q: Parsing/serializing JSON with Scala In Scala, how can I de-serialize a JSON string, modify a value and serialize back to string?
There has to be a way to do this without using 3rd party libraries but I can't get it to work. Here is what I tried so far:
import scala.util.parsing.json

var lines = "{\"id\" : \"abc\", \"stuff\" : [1, 2, 3], \"more\" : {\"bro\" : \"science\"}}"

// Test 1
val myJSON = json.JSON.parseRaw(lines)
// myJSON: Option[scala.util.parsing.json.JSONType] = Some({"id" : "abc", "stuff" : [1.0, 2.0, 3.0], "more" : {"bro" : "science"}})
// I cannot modify fields on the JSONType instance but toString() works well.
// res1: String = Some({"id" : "abc", "stuff" : [1.0, 2.0, 3.0], "more" : {"bro" : "science"}})

// Test 2
// This way I can parse JSON into a map and manipulate its values.
// val myMap = json.JSON.parseFull(lines).get.asInstanceOf[Map[String, Any]] + ("id" -> "blah")
// myMap: scala.collection.immutable.Map[String,Any] = Map(id -> blah, stuff -> List(1.0, 2.0, 3.0), more -> Map(bro -> science))

// However, when converted to an instance of JSONObject and calling
// toString() only the top-level items are JSON-serialized
new json.JSONObject(myMap).toString()
// res2: String = {"id" : "blah", "stuff" : List(1.0, 2.0, 3.0), "more" : Map(bro -> science)}

If it's not possible with standard Scala, I'd appreciate and example of how to do this with a third party library.
Thanks,
/David

A: small silly/trivial example of what I mentioned. Could be written better too but wanted to break it into chunks. There is a lot you can do with them:
Here is old link in terms of play version but as far as I know up to date on features available in 2.3.x:
https://www.playframework.com/documentation/2.1.1/ScalaJsonTransformers
import play.api.libs.json._

var lines = "{\"id\" : \"abc\", \"stuff\" : [1, 2, 3], \"more\" : {\"bro\" :        \"science\"}}"

val jsonAsJsValue = Json.parse(lines)
//jsonAsJsValue: play.api.libs.json.JsValue = {"id":"abc","stuff":    [1,2,3],"more":{"bro":"science"}}
val updateIdTransformer =  (__ \"id").json.update(
 __.read[JsString].map{a => JsString("def")}
)

val updatedJson = jsonAsJsValue.transform(updateIdTransformer)

//updatedJson: play.api.libs.json.JsResult[play.api.libs.json.JsObject] =    JsSuccess({"id":"def","stuff":[1,2,3],"more":{"bro":"science"}},/id)


text:
Q: How to draw multiple lines with Google Charts The idea is to dynamically get the current month's, last month's and 2 month's back information about average download speeds which are stored in the mySQL database.
Database structure is:
+-----------+-----------+------+-----+---------------------+-------------------------------+
| Field     | Type      | Null | Key | Default             | Extra                         |
+-----------+-----------+------+-----+---------------------+-------------------------------+
| ping      | float     | NO   |     | NULL                |                               |
| download  | float     | NO   |     | NULL                |                               |
| upload    | float     | NO   |     | NULL                |                               |
| date_time | timestamp | NO   |     | current_timestamp() | on update current_timestamp() |
+-----------+-----------+------+-----+---------------------+-------------------------------+

By following the instructions at https://maker.pro/raspberry-pi/tutorial/how-to-extract-and-chart-data-from-mysql I was able to chart one line. Then by trial/error I was able to include two other lines as well, but they are not treated as separate information but just an addition to the first one drawn to the same image.
I'm totally lost on how to loop the data for current month, then the month before and then the data from 2 months back so that the lines would have different color and would be easy to see if there has been any signifcant changes in the download speeds.
The code that outputs everything to one chart is as follows:
<?php

# Prepare a connection to the mySQL database
$connection = new mysqli("192.168.x.x", "username", "password", "dnbname");

# If there are any errors or the connection is not OK
if ($connection->connect_error) {
        die ('Connection error: '.$connection->connect_error);
}

# Prepare a query to the mySQL database and get average hourly based download speed this month
$sql = "select hour(date_time), round(avg(download),0) from results where MONTH(date_time) = MONTH(CURDATE()) group by hour(date_time);";
$result = $connection->query($sql);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data1 = array();
        while ($row = $result->fetch_assoc()) {
                $data1[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }

# Prepare a query to the mySQL database and get average hourly based download speed last month
$sql2 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE
(), INTERVAL 1 MONTH)) group by hour(date_time);";
$result2 = $connection->query($sql2);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data2 = array();
        while ($row = $result2->fetch_assoc()) {
                $data2[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }

# Prepare a query to the mySQL database and get average hourly based download speed 2 months ago
$sql3 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 3 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE
(), INTERVAL 2 MONTH)) group by hour(date_time);";
$result3 = $connection->query($sql3);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data3 = array();
        while ($row = $result3->fetch_assoc()) {
                $data3[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }
?>
var data_currentmonth = <?php echo json_encode($data1); ?>;
var data_lastmonth = <?php echo json_encode($data2); ?>;
var data_monthb4lastmonth = <?php echo json_encode($data3); ?>;

Currently the image it outputs looks like this:

And here's some sample data:
var data_currentmonth = [["0","105"],["1","110"],["2","111"],["3","113"],["4","119"],["5","121"],["6","119"],["7","61"],["8","45"],["9","41"],["10","41"],["11","36"],["12","111"],["13","110"],["14","110"],["15","105"],["16","96"],["17","97"],["18","93"],["19","95"],["20","86"],["21","73"],["22","73"],["23","90"]];
var data_lastmonth = [["0","104"],["1","112"],["2","119"],["3","120"],["4","122"],["5","128"],["6","120"],["7","65"],["8","48"],["9","47"],["10","49"],["11","47"],["12","119"],["13","122"],["14","118"],["15","119"],["16","113"],["17","116"],["18","111"],["19","105"],["20","101"],["21","89"],["22","81"],["23","92"]];
var data_monthb4lastmonth = [["0","106"],["1","109"],["2","112"],["3","114"],["4","117"],["5","117"],["6","113"],["7","65"],["8","52"],["9","49"],["10","48"],["11","47"],["12","115"],["13","109"],["14","109"],["15","111"],["16","113"],["17","106"],["18","104"],["19","102"],["20","97"],["21","87"],["22","78"],["23","90"]];

A: in order to draw multiple lines,
you'll multiple columns in the google data table.
and since you want to compare multiple months,
we can load multiple data tables, then join them together.

in the php, recommend building the full arrays in php,
then encoding them as json when adding to the script.
rather than using echo as strings.
see following php snippet...
<?php
  # If there are any errors or the connection is not OK
  if ($connection->connect_error) {
    die ('Connection error: '.$connection->connect_error);
  }

  # Prepare a query to the mySQL database and get average hourly based download speed this month
  $sql = "select hour(date_time), round(avg(download),0) from results where MONTH(date_time) = MONTH(CURDATE()) group by hour(date_time);";
  $result = $connection->query($sql);

  # This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
  $data1 = array();
  while ($row = $result->fetch_assoc()) {
    $data1[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
  }

  # Prepare a query to the mySQL database and get average hourly based download speed last month
  $sql2 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) group by hour(date_time);";
  $result2 = $connection->query($sql2);

  # This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
  $data2 = array();
  while ($row = $result2->fetch_assoc()) {
    $data2[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
  }

  # Prepare a query to the mySQL database and get average hourly based download speed 2 months ago
  $sql3 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 3 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)) group by hour(date_time);";
  $result3 = $connection->query($sql3);

  # This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
  $data3 = array();
  while ($row = $result3->fetch_assoc()) {
    $data3[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
  }
?>

var data_month1 = <?php echo json_encode($data1); ?>;
var data_month2 = <?php echo json_encode($data2); ?>;
var data_month3 = <?php echo json_encode($data3); ?>;

then we can use the above month arrays to populate the google data table,
and draw the chart.
see following snippet...
google.charts.load('current', {
  packages: ['corechart']
}).then(function drawChart() {

  // month 1
  var data1 = new google.visualization.DataTable();
  data1.addColumn({label: 'Hour', type: 'number'});
  data1.addColumn({label: 'Month 1 Avg', type: 'number'});
  data1.addRows(data_month1);

  // month 2
  var data2 = new google.visualization.DataTable();
  data2.addColumn({label: 'Hour', type: 'number'});
  data2.addColumn({label: 'Month 2 Avg', type: 'number'});
  data2.addRows(data_month2);

  // month 3
  var data3 = new google.visualization.DataTable();
  data3.addColumn({label: 'Hour', type: 'number'});
  data3.addColumn({label: 'Month 3 Avg', type: 'number'});
  data3.addRows(data_month3);

  // join data tables
  var join1 = google.visualization.data.join(data1, data2, 'full', [[0,0]], [1], [1]);
  var join2 = google.visualization.data.join(join1, data3, 'full', [[0,0]], [1,2], [1]);

  // sort data
  join2.sort([
    {column: 0}
  ]);

  // Curved line
  var options = {
    title: '',
    curveType: 'function',
    legend: { position: 'bottom' }
  };

  // Curved chart
  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
  chart.draw(join2, options);
}); // End bracket from drawChart

see following working snippet for an example of how the result could look...

var data_month1 = [[1, 10],[2, 12],[3, 15],[4, 9],[5, 6]];
var data_month2 = [[1, 5],[2, 8],[3, 11],[4, 14],[5, 16]];
var data_month3 = [[1, 2],[2, 5],[3, 7],[4, 10],[5, 3]];

google.charts.load('current', {
  packages: ['corechart']
}).then(function drawChart() {

  // month 1
  var data1 = new google.visualization.DataTable();
  data1.addColumn({label: 'Hour', type: 'number'});
  data1.addColumn({label: 'Month 1 Avg', type: 'number'});
  data1.addRows(data_month1);

  // month 2
  var data2 = new google.visualization.DataTable();
  data2.addColumn({label: 'Hour', type: 'number'});
  data2.addColumn({label: 'Month 2 Avg', type: 'number'});
  data2.addRows(data_month2);

  // month 3
  var data3 = new google.visualization.DataTable();
  data3.addColumn({label: 'Hour', type: 'number'});
  data3.addColumn({label: 'Month 3 Avg', type: 'number'});
  data3.addRows(data_month3);

  // join data tables
  var join1 = google.visualization.data.join(data1, data2, 'full', [[0,0]], [1], [1]);
  var join2 = google.visualization.data.join(join1, data3, 'full', [[0,0]], [1,2], [1]);

  // sort data
  join2.sort([
    {column: 0}
  ]);

  // Curved line
  var options = {
    title: '',
    curveType: 'function',
    legend: { position: 'bottom' }
  };

  // Curved chart
  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
  chart.draw(join2, options);
}); // End bracket from drawChart

A: Here's the full working code:
<?php

# Prepare a connection to the mySQL database
$connection = new mysqli("192.168.x.x", "username", "password", "dbname");

# If there are any errors or the connection is not OK
if ($connection->connect_error) {
        die ('Connection error: '.$connection->connect_error);
}

# Prepare a query to the mySQL database and get average hourly based download speed this month
$sql = "select hour(date_time), round(avg(download),0) from results where MONTH(date_time) = MONTH(CURDATE()) group by hour(date_time);";
$result = $connection->query($sql);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data1 = array();
        while ($row = $result->fetch_assoc()) {
                $data1[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }

# Prepare a query to the mySQL database and get average hourly based download speed last month
$sql2 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) group by hour(date_time);";
$result2 = $connection->query($sql2);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data2 = array();
        while ($row = $result2->fetch_assoc()) {
                $data2[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }

# Prepare a query to the mySQL database and get average hourly based download speed 2 months ago
$sql3 = "select hour(date_time), round(avg(download),0) from results where DATE(date_time) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 3 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)) group by hour(date_time);";
$result3 = $connection->query($sql3);

# This while - loop formats and put all the retrieved data into ['timestamp', 'download'] way.
        $data3 = array();
        while ($row = $result3->fetch_assoc()) {
                $data3[] = [$row['hour(date_time)'], $row['round(avg(download),0)']];
                }
?>

This creates image with 3 lines in different colors.
Now it's very easy for me to follow how my 4G connection download speeds are developing over the time.
The "funny" drop between 07:00-12:00 is because the operator has decreased the transmit power due to escavators working near the base station.


text:
Q: CSS Responsive menu with h1 title (logo) centered So I want to center a h1 without an image at the center of my navigation which has 2 more elements and it has to be responsive. I tried almost everything I can find but...works mostly with background images, and with inline-block I can't center it perfectly.
Below I have the best I could do, but hover doesn't work, probably cause of h1 width which 100%;

* {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
  color: white;
  text-shadow: 1px 1px 1px black;
}
li {
  list-style: none;
}
header {
  margin: 0 auto;
  text-align: center;
}
ul li {
  float: left;
  display: block;
  background-color: #232323;
  width: 50%;
  padding: 10px 0 10px 0;
}
ul li:hover {
  background-color: black;
}
.logo {
  position: relative;
  top: -38px;
}

Blog

Portofolio

Tao SandBox

It has to be a better way!!!
http://codepen.io/taosx/pen/vNWojo?editors=110

A: The simplest method is just to make the logo` part of the menu like so:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
a {
  text-decoration: none;
  color: white;
  text-shadow: 1px 1px 1px black;
}
ul {
  overflow: hidden;
}
li {
  list-style: none;
}
header {
  margin: 0 auto;
  text-align: center;
  background-color: #232323;
}
ul li {
  float: left;
  width: 33%;
  vertical-align: middle;
}
ul li:hover {
  background-color: black;
}

Blog

Tao SandBox

Portofolio

A: http://codepen.io/anon/pen/OyOKrN
Make the h1 use the .logo class. Then set absolute position and center it.
 .logo {
    position:absolute;
    top:0;
    left:0;
   right:0;
   text-align:center;
 }

I'd also recommend adding the h1 markup prior to the nav, to maintain a better semantic flow.

Tao SandBox

Blog

Portofolio


text:
Q: Unit Testing in Visual studio 2010 Apparently i have been struggling to test an application built by Developers in my Ourteam.
The Class:Apis, Reads the connection string,id and error message from user.I return a dictionary of values name, and Qualification weight.Because am a newbie in Testing am facing alot problem to get my test working as expected.Please advise where am not doing wrong.
Class:
 public class Apis
{

    public Dictionary<String, String> getQualWeight(String sqlConStr, String inBin, Label lblResults)
    {
        Dictionary<String, String> qualList = new Dictionary<string, string>();
        string selectSQL = "select Name,qual_weight from Qualification_type "
                            + "where ID in (select Qualification_ID from Qualifications where BIN = @inBin)";
        con = getConn(sqlConStr);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        cmd.Parameters.AddWithValue("@inBin", inBin);
        SqlDataReader reader;
        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                qualList.Add(reader[0].ToString(), reader[1].ToString());
            }
            reader.Close();
            return qualList;
        }
        catch (Exception err)
        {
            lblResults.Text = "error fetching qualification weight " + err.Message;
            return null;
        }
        finally
        {
            con.Close();
        }
    }

My test:
[TestMethod()]
    public void getQualWeightTest()
    {
        Api target = new Api();
        string sqlConStr = "SERVER=ABC123; Database=DB; UID=id; PWD=passme;encrypt=no;enlist=false";
        string inBin = "2012-52-456";
        Label lblResults = null;

        lblResults.Text = " Failed";
        Dictionary<string, string> expected = new Dictionary<string,string>();
        expected.Add("Gohn", "50");
        Dictionary<string, string> actual;
        actual = target.getQualWeight(sqlConStr, inBin, lblResults);
        Assert.AreEqual(expected, actual);

    }

A: Just looking at your code I have a couple of suggestions.

*

*You don't want to rely on an external resource (in this case the Database) in your unit tests. Your code could be fine but the test could fail if this database is down.  Look at something like the Repository Pattern and pass in (or ideally inject using Dependency Injection) a repository rather than a connection string.  Using this approach you can use a 'Fake' repository and you have complete control over the data being passed back and you remove the dependency on the database.  You can also test your repository in isolation if need be.

*This code looks like it is in violation of the Single Responsibility Principle, it is responsible for Data Access and updating the UI. Calling out to a repository would remove the data access from the code and make it easier to test.

I find a good indicator of how decoupled your code is is how easy it is to test.  If your having difficulty testing your code, it could be a candidate for refactoring.


text:
Q: Record long videos using WebRTC I created Chrome extension based on this. This extension can record the screen with chrome.desktopCapture (link) and audio with <audio> tag and AudioContext, using WebRTC. My settings:
mimeType: 'video/webm;codecs=vp9',
audioBitsPerSecond: 60 * 1000,
videoBitsPerSecond: 512 * 1000

After stop, video opens in the new tab where users can manipulate with it. As a source I using blob from base64 string. Like this:
<video preload="auto">
    <source src="data:video/webm;codecs=vp9;base64,GkXfo59ChoEBQveBA..." type="video/webm">
</video>

Problem: I can't play video more that 3-4 minutes. It just stops. Also I can't move video backward and forward after this. In addition I can't get video duration (always Infinity - can get it only after full stop).
I also tried save blob as file: src="file:///C:/[username]/video_11162016.webm". Or open it in VLC. Same problem. Can't move forward or backward, only play and pause.
But If I save video locally and convert it with ffmpeg or any online converter (simply from webm to webm) - video plays excellent. No lags, artifacts.
Information from ffmpeg (ffmpeg.exe -i video.webm):
1.) Recorded file:
Input #0, matroska,webm, from 'RecordRTC.webm':
  Metadata:
    encoder         : Chrome
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0(eng): Audio: opus, 48000 Hz, stereo, fltp (default)
    Stream #0:1(eng): Video: vp9 (Profile 0), yuv420p(tv), 1858x1088, SAR 1:1 DAR 929:544, 15 fps, 15 tbr, 1k tbn, 1k tbc (default)

2.) Converted file:
Input #0, matroska,webm, from 'RecordRTC_converted.webm':
  Metadata:
    encoder         : Lavf57.57.100
  Duration: 00:06:12.53, start: 0.000000, bitrate: 1262 kb/s
    Stream #0:0(eng): Video: vp8, yuv420p(progressive), 1858x1088, SAR 1:1 DAR 929:544, 15 fps, 15 tbr, 1k tbn, 1k tbc (default)
    Stream #0:1(eng): Audio: vorbis, 44100 Hz, stereo, fltp (default)

I tried to use ffmpeg.js (link), but I always got "Invalid data found when processing input" error.
And tried change codec to vp8 - no results.
Question: how can I play recorded video without converting? Or it is necessarily?
Thanks.


text:
Q: How to see if a string ends with one of multiple characters I have this statement:
string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")

I would like to put all the tokens (",", "-", "&") into a constant and simplify the above to ask, "does the string end with any of these characters", but I'm not sure how to do that.

A: Yes.
CONST = %w(, - &).freeze
string_tokens[-1].end_with?(*CONST)

Usage:
'test,'.end_with?(*CONST)
#=> true
'test&'.end_with?(*CONST)
#=> true
'test-'.end_with?(*CONST)
#=> true

You use * (splat operator) to pass multiple args to the String#end_with?, because it accepts multiple.

A: You could also use a regex :
chars = %w(, - &)
ENDS_WITH_CHAR = Regexp.new("["+chars.map{|s| Regexp.escape(s)}.join+']\z')
"abc-" =~ ENDS_WITH_CHAR
# or with Ruby 2.4
"abc-".match? ENDS_WITH_CHAR

A: str = 'hello-'

',-&'.include? str[-1]
  #=> true

',$&'.include? str[-1]
  #=> false