Bootstrap DataTable Sparkline Get data from comma separated string instead of array

Question: I'm using a Bootstrap DataTable component and I'm able to get data from my db and showing it on my Asp.net Core MVC App. Now in a column I want to add a sparkline,the component requires the sparkline column to be an array of values but I have a comma separated string and I need help to understand how to change the JS in order to use my values type.
To make it more simple I created a new App without DB and using data defined directly in the JS as shown in this example:
https://datatables.net/examples/basic_init/stocks.html
This works perfectly.
Now I have to change the value in "last" from:
  var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": [2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59]
        },
.....
]

To:
  var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": "2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59"
        },
.....
]

This is the js that needs to be changed:
$(document).ready(function () {
    debugger;
    var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": [2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59]
        },
        {
            "name": "Spry Media Productions",
            "symbol": "SPMP",
            "last": [1.12, 1.11, 1.08, 1.08, 1.09, 1.11, 1.08]
        },
        {
            "name": "Widget Emporium",
            "symbol": "WDEMP",
            "last": [3.40, 3.39, 3.46, 3.51, 3.50, 3.48, 3.49]
        },
        {
            "name": "Sole Goodman",
            "symbol": "SGMAN",
            "last": [16.20, 16.40, 16.36, 16.35, 16.61, 16.46, 16.19]
        },
        {
            "name": "Stanler Bits and Bobs",
            "symbol": "SBIBO",
            "last": [82.51, 83.47, 83.40, 83.68, 83.81, 83.29, 83.72]
        }
    ];

    let table = $('#example').DataTable({
        ajax: function (dataSent, callback, settings) {
            let data = this.api().ajax.json();
            if (data == undefined) {
                data = stock_data;
            } else {
                data = data.data;
                for (i = 0; i < data.length; i++) {
                    data[i].last.push(data[i].last.shift())
                }
            }

            callback({ data: data });
        },
        paging: false,
        initComplete: function () {
            let api = this.api();
            setInterval(function () {
                api.ajax.reload();
            }, 5000);
        },
        drawCallback: function () {
            $('.sparkline')
                .map(function () {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })
        },
        columns: [
            {
                data: 'name'
            },
            {
                data: 'symbol'
            },
            {
                data: null,
                render: function (data, type, row, meta) {
                    return row.last[row.last.length - 1].toFixed(2);
                }
            },
            {
                data: null,
                render: function (data, type, row, meta) {
                    var val = (row.last[row.last.length - 1] - row.last[row.last.length - 2]).toFixed(2);
                    var colour = val < 0 ? 'red' : 'green'
                    return type === 'display' ?
                        '' + val + '' :
                        val;
                }
            },
            {
                data: 'last',
                render: function (data, type, row, meta) {
                    return type === 'display' ?
                        '' + data.toString() + '' :
                        data;
                }
            }
        ]
    });
});

I tried to play around using some .split(", ") in the "data: 'last',render" but with no luck, also it is very difficult for me to debug the js (in site.js), I tried to put some console.log but nothing gets written in the output.
UPDATE
Thanks to @andrewJames now my code is working fine and for some reason it doesn't even need any data trasformation, it's like automatically converting the csv string to the array needed.
I added also some other functionalities as grouping by a columns and transform datetime disply format with moment.js
Here is the full code:
$(document).ready(function () {
    var groupColumn = 0;

    let table = $('#example').DataTable({
        responsive: true,
        autoWidth: true,
        processing: true,
        ordering: true,
        scrollY: '50vh',
        scrollCollapse: true,
        paging: false,
        searching: true,

        "ajax": {
            "url": "api/ApartmentsAvailables",
            "type": "GET",
            "contentType": "application/json; charset=utf-8",
            "dataType": "json",
        },
        columnDefs: [{ visible: false, targets: groupColumn },

        {
            targets: 7,
            render: DataTable.render.datetime('YYYY-MM-DDT00:00:00', 'MMMM D, YYYY', 'en'),
        },
        { responsivePriority: 1, targets: 0 },

        ],
        order: [[groupColumn, 'asc']],

        drawCallback: function (settings) {
            $('.sparkline')
                .map(function () {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })

            var api = this.api();
            var rows = api.rows({ page: 'current' }).nodes();
            var last = null;

            api
                .column(groupColumn, { page: 'current' })
                .data()
                .each(function (group, i) {
                    if (last !== group) {
                        $(rows)
                            .eq(i)
                            .before('
' + group + '
');

                        last = group;
                    }
                })
        },
        columns: [

            { "data": "building" },
            { "data": "floor_Plan" },
            { "data": "apt_Number" },
            { "data": "rent" },
            { "data": "bedrooms" },
            { "data": "bathrooms" },
            { "data": "sqft" },
            { "data": "available_Date" },
            {
                data: 'prices',
                render: function (data, type, row, meta) {

                    return type === 'display' ?
                        '' + data.toString() + '' :
                        data;
                }
            },
        ]
    });
    new $.fn.dataTable.FixedHeader(table);
    // Order by the grouping
    $('#example tbody').on('click', 'tr.group', function () {
        var currentOrder = table.order()[0];
        if (currentOrder[0] === groupColumn && currentOrder[1] === 'asc') {
            table.order([groupColumn, 'desc']).draw();
        } else {
            table.order([groupColumn, 'asc']).draw();
        }
    });
});

The only issue I'm facing now is that once I enable responsive: true, the sparkline column becomes hidden and when I click to expand the row to show the hidden columns it shows the whole array of Value and not the sparkline.
I guess that the
drawCallback: function (settings) {
            $('.sparkline')
                .map(function () {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })

is not able to be applied to column that is hidden.
Without the responsive option the html generated for the td is:

        <canvas style="display: inline-block; width: 250px; height: 21px; vertical-align: top;"
                width="250"
                height="21"/>

With the responsive set to true:

    3446,3446,3416,3416,3416,3546,3546,3546,3546,3546,3546,3561,3556,3551,3396,3396,3396,3346,3306,3306,3306

I presume that I should somehow capture the mouse click on the expand icon and then re-inject the canvas but I don't know how to do that.
Answer: stock_data[n].last.toSring();

n like the index of elements.
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
Comment: I'm not really sure how would I implement that in my code
Comment: maybe iterate the array and update the proerty last with the spread operator.. or create a copy like

` let stock_data_update= stock_data.forEach(item=>return ...item, item.last: item.last.toString())`
Answer: You can convert each string containing comma-separated numbers back to an array of numbers using this:
for(i = 0; i < data.length; i++) {
    data[i].last = data[i].last.split(",").map(element => {
        return Number(element);
    });
}

This performs a standard split() - but that gives you string values in the array. So we also use the map() function to convert each mumber-as-string back to a number.
Where to place this?
In your code in the question, it goes after this line:
data = stock_data;

Here is a self-contained demo:

$(document).ready(function() {
    var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": "2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59"
        },
        {
            "name": "Spry Media Productions",
            "symbol": "SPMP",
            "last": "1.12, 1.11, 1.08, 1.08, 1.09, 1.11, 1.08"
        },
        {
            "name": "Widget Emporium",
            "symbol": "WDEMP",
            "last": "3.40, 3.39, 3.46, 3.51, 3.50, 3.48, 3.49"
        },
        {
            "name": "Sole Goodman",
            "symbol": "SGMAN",
            "last": "16.20, 16.40, 16.36, 16.35, 16.61, 16.46, 16.19"
        },
        {
            "name": "Stanler Bits and Bobs",
            "symbol": "SBIBO",
            "last": "82.51, 83.47, 83.40, 83.68, 83.81, 83.29, 83.72"
        }
    ];

    let table = $('#example').DataTable({
        ajax: function(dataSent, callback, settings) {
            let data = this.api().ajax.json();
            if(data == undefined) {
                data = stock_data;
                for(i = 0; i < data.length; i++) {
                    data[i].last = data[i].last.split(",").map(element => {
                        return Number(element);
                    });
                }
            } else {
                data = data.data;
                for(i = 0; i < data.length; i++) {
                    data[i].last.push(data[i].last.shift())
                }
            }

            callback({data: data});
        },
        paging: false,
        initComplete: function() {
            let api = this.api();
            setInterval(function() {
                api.ajax.reload();
            }, 5000);
        },
        drawCallback: function() {
            $('.sparkline')
                .map(function() {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })
        },
        columns: [
            {
                data: 'name'
            },
            {
                data: 'symbol'
            },
            {
                data: null,
                render: function(data, type, row, meta) {
                    return row.last[row.last.length - 1].toFixed(2);
                }
            },
            {
                data: null,
                render: function(data, type, row, meta) {
                    var val = (row.last[row.last.length - 1] - row.last[row.last.length - 2]).toFixed(2);
                    var colour = val < 0 ? 'red' : 'green'
                    return type === 'display' ?
                        '' + val + '' :
                        val;
                }
            },
            {
                data: 'last',
                render: function(data, type, row, meta) {
                    return type === 'display' ?
                        '' + data.toString() + '' :
                        data;
                }
            }
        ]
    });
});
<!doctype html>

  <meta charset="UTF-8">
  <title>Demo</title>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

                Name
                Symbol
                Price
                Difference
                Last

                Name
                Symbol
                Price
                Difference
                Last

Update
Regarding the comment: If you are actually using the following as your real data source...
ajax: "api/ApartmentsAvailables"

...then you can adapt the same logic as above.
To do this you will need to expand your DataTables ajax option to use the DataTables dataSrc option. Using this option allows you to pre-process the JSON you receive from the Ajax URL - and convert those comma-separated strings back to arrays of numbers, using basically the same logic as I used above.
"ajax": {
    "url": "api/ApartmentsAvailables",
    "dataSrc": function ( json ) { // the JSON containing strings

      // transform the received JSON here...

      return json;  // the updated JSON containing arrays
    }
}

You can console.log( json ) if you need to double-check the exact structure of the JSON before and after you have transformed it.
I don't know the structure of the JSON you are receiving from your URL, so you may need to adjust my original code to fit your actual JSON. Give it a try and if you get stuck you can ask a new question - but there are  a lot of questions about dataSrc on Stack Overflow.
Here is the official documentation: ajax.dataSrc. As you can see from my example above, you need to look at the syntax and examples for the function syntax.
Comment: ok now that the example works, I need to apply the same to my "real" project.. the problem is that in the real project the ajax part is like this

`ajax: "api/ApartmentsAvailables",`

How can I apply a similar concept with this?
Comment: I added some notes - they should point you in the right direction.
Comment: Thank you andrewJames! I'll try to take a look at it as soon as I get Home. I'll keep you posted!
Comment: So.. I don't know exactly why but I was starting to play with the `dataSrc` when I realized that it's not really needed. For some reason using `ajax: "api/ApartmentsAvailables"` would require some data transformation but using it like this:

`"ajax": {`
            `"url": "api/ApartmentsAvailables",`
            `"type": "GET",`
            `"contentType": "application/json; charset=utf-8",`
            `"dataType": "json",`
        `},`
 doesn't require any change..it seems to be converting the String to Array automatically.. it's just working as is :-)
Comment: I edited my original post with Updates and a new issue
Comment: If you have a new issue, you can create a new question for that


Cartesian Plane and Number Lines

Question: good day. May I ask how many number lines are there in a cartesian plane? I'm clueless. Thank you so much
Comment: Tell us what you mean by "number line".  If it is just line then the number is very large.
Comment: an infinity. Pick any number (say, 10000), I'll always be able (if patient enough) to show more (say, 10001) lines.
Comment: like a lot of lines
Comment: The number of lines is equal to the number of points, i. e. set of all lines on the plane has cardinality of the continuum.
Answer: There is an unique line through any two points of the Euclidean plane. By assigning $0$ to one, and $1$ to the other point, you uniquely specify an uniform numbering of the line, which in my interpretation of the word makes it a number line.
Therefore there are as many number lines as there are pairs $(p,q)$ of points with $p\ne q$. Now from set theory, we know that there are exactly as many such pairs as there are real numbers.
Now you might use another definition. Noting that you speak of the "cartesian plane", I assume you've already been given a coordinate system. So maybe you only consider a line to be a number line if it goes through the origin and has its $0$ there. In that case, the number line is specified by one single point other than the origin. But again, there are as many such points as there are real numbers, so we again get the same number of number lines.
You might also add the additional requirement that the distance between $0$ and $1$ on the number line is $1$. In that case, the number line is uniquely determined by the angle to the $x$ axis. But again, the angle is a real number from the interval $[0,2\pi)$ (other intervals of the same length can be chosen by convention), and there are as many real numbers in an interval as there are in total, so again we get as many number lines as there are real numbers.
Now you might also restrict it further to define a number line to just be one of the axes of the Cartesian coordinate system. In that case, there would of course be only two number lines. But if that had been the definition you had in mind, you probably wouldn't have asked to begin with.
So to summarize:
For any likely definition of "number line", there are as many number lines as there are real numbers.

Cartesian Plane and Number Lines


print star or "X" patterns

Question: Please help me finish my homework.
I would like to produce pattern like this using looping c language
X X X
 XXX
XXXXX
 XXX
X X X

XXXXX
X   X
X   X
X   X
XXXXX

X
XX
X X
X  X
XXXXX

    X
   XX
  X X
 X  X
XXXXX

this is my code
#include <stdio.h>

int main()
{
for(int i=1;i<=26;i++){
    if(i==1){
        for(int a = 1;a<=5;a++){
            if(a==1 || a==3 || a==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==2){
        for(int b = 1;b<=5;b++){
            if(b==2 || b==3 || b==4){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==3){
        for(int c = 1;c<=5;c++){
            printf("X");
        }
    }
    else if(i==4){
        for(int d = 1;d<=5;d++){
            if(d==2 || d==3 || d==4){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==5){
        for(int e = 1;e<=5;e++){
            if(e==1 || e==3 || e==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==8){
        for(int f = 1;f<=5;f++){
            printf("X");
        }
    }
    else if(i==9){
        for(int g = 1;g<=5;g++){
            if(g==1|| g==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==10){
        for(int h = 1;h<=5;h++){
            if(h==1|| h==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==11){
        for(int jtmp = 1;jtmp<=5;jtmp++){
            if(jtmp==1|| jtmp==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==12){
        for(int f = 1;f<=5;f++){
            printf("X");
        }
    }
    else if(i==15){
        for(int k = 1;k<=5;k++){
            if(k==1){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==16){
        for(int l = 1;l<=5;l++){
            if(l==1 || l==2){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==17){
        for(int m = 1;m<=5;m++){
            if(m==1 || m==3){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==18){
        for(int n = 1;n<=5;n++){
            if(n==1 || n==4){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==19){
        for(int o = 1;o<=5;o++){
            printf("X");
        }
    }
    else if(i==22){
        for(int p = 1;p<=5;p++){
            if(p==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==23){
        for(int q = 1;q<=5;q++){
            if(q==4 || q==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==24){
        for(int r = 1;r<=5;r++){
            if(r==3 || r==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==25){
        for(int s = 1;s<=5;s++){
            if(s==2 || s==5){
                printf("X");
            }
            else{
                printf(" ");
            }
        }
    }
    else if(i==26){
        for(int t = 1;t<=5;t++){
            printf("X");
        }
    }
    else{
        printf("\n");
    }
    printf("\n");
}
}

but my code so long not simple, because i'm so newbie
but i want simple code using method like this
#include <stdio.h>

int main()
{
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                if (j == 1 || j == 5 || i == 1 || i == 5)
                    printf("X");
                else
                    printf(" ");
            }
            printf("\n");
        }

    return 0;
}

Output:
XXXXX
X   X
X   X
X   X
XXXXX

Comment: Are you sure this i c++ code and not c?
Comment: is not homework a learning opportunity? why would someone want to rob you of it?
Comment: @πάνταῥεῖ i mean c, sorry
Comment: Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/).
Comment: In the case of box, the condition was simple (based on constants): `if (j == 1 || j == 5 || i == 1 || i == 5)`. In the case of a triangle, (I would continue on this as I feel it has next higher level of "handicap") the condition has to be based on the relation of `i` and `j` to each other. Any idea? (May be, start with horizontal and vertical bar first. If you got it running for an "L", then think about the diagonal line.)
Answer: You would really benefit from using functions. Before your main program declare a function for each shape e.g.
function square()
{
       for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                if (j == 1 || j == 5 || i == 1 || i == 5)
                    printf("X");
                else
                    printf(" ");
            }
            printf("\n");
        }

    return 0;
}

Now in your main program you can write :-
main()
{
 square();
 square();
 triangle();
 star();
 triangle();

 return 0;
}

When you have done that read about parameters. Then you will be able to write :-
main()
{
 square(2);
 triangle(1);
 star(1);
 triangle(1);

 return 0;
}

to do exactly the same thing. he he... square(128); should be fun ;)

print star or "X" patterns


Pass the item DataContext in CommandParameter

Question: I have a treeview which is created from ItemsSource of SecondViewModel instances, different from my Window DataContext.
I want to send the ViewModel that belongs to the TreeViewItem via a `CommandParameter.
The window data context is: MyViewModel.
The treeviewitems data context is: SecondViewModel
I want to pass the SecondViewModel and not MyViewModel.
Therefore,
CommandParameter ="{Binding}"

Won't work (as it will send MyViewModel)
Edit: Some Code:
 <TreeView Name="treeView" ItemContainerStyle="{StaticResource TreeViewItemStyle}"  Grid.Row="1" Grid.Column="1">
        <TreeViewItem Header="{Binding ProjectName}">
            <TreeViewItem commandBehaviors:MouseDoubleClick.Command="{Binding SelectOtherTab}"
                          commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}" //this returns the data context of the window, I want to return the Item Source
                ContextMenu="{StaticResource AddClassMenu}" ItemTemplate="{DynamicResource ClassDataTemplate}" ItemsSource="{Binding ClassCollection}">

How can I send the SecondViewModel?
EDIT:
I want to enable deleting the current item, but the command never gets called for some reason.
Here's the code:
<TreeViewItem x:Name="treeViewItem"
                ContextMenu="{StaticResource AddClassMenu}" ItemTemplate="{DynamicResource ClassDataTemplate}" ItemsSource="{Binding ClassCollection}">
                <TreeViewItem.ItemContainerStyle>

</TreeViewItem>

My Context Menu:
 <ContextMenu x:Key="RemoveClassMenu">
    <MenuItem Header="Delete" Command="{Binding ElementName=treeViewItem, Path=DataContext.RemoveClass}" CommandParameter="{Binding}"/>
</ContextMenu>

As mentions before, the command just never gets called. What is the problem with my code?
Comment: May I ask why you want the whole ItemSource to be bound in the CommandParameter? And how you set the ItemSource of the TreeView.
Comment: I'm a bit confused about how your `SecondViewModel` relates to your `MyViewModel`, and where the `ItemsSource` comes in at. Can you include some more code showing how those 3 relate to each other? If you build your `TreeView` using an `ItemsSource` property instead of manually defining each `TreeViewItem`, then you can set your command behaviors in the `ItemContainerStyle` and `{Binding }` will refer to the each item in the `ItemsSource`. Right now, I don't see where your `SecondViewModel` is in your code at all.
Comment: @MatsMagnem I don't want the whole ItemSource, just the one who relates to the treeviewitem. (1 item)
Comment: @Rachel I'm sorry, I said 'SecondViewModel' just so it will be easier to understand, it is actually the ItemSource - ClassCollection, the ClassCollection is an observablecollection created from ClassViewModel (This is actually the SecondViewModel I used as an example before).
Comment: @idish Can't you use `{Binding ClassCollection}` instead of `{Binding }` to pass it your SecondViewModel?
Comment: @Rachel That's what I want to ask, can I?
Comment: @Rachel Isn't it going to send as parameter the whole collection?
Answer: I think what you're looking to do is set your DoubleClick commands on your child TreeViewItems, not your parent TreeViewItem which sets the ItemsSource
Right now your XAML is saying to build a parent TreeViewItem, and under that build a bunch of child TreeViewItems for each item in ClassCollection. When you double click on the parent TreeViewItem then run the SelectOtherTab command, however there's nothing to specify which child TreeViewItem got clicked.
Here's a simplified view of the XAML you have now.
<TreeView x:Name="treeView">
    <TreeViewItem OnDoubleClick="SelectOtherTab">
        <TreeViewItem />
        <TreeViewItem />
        <TreeViewItem />
        ...
    </TreeViewItem>
</TreeView>

Instead you want to attach the Command and CommandParameter properties to each child  TreeViewItem, like this:
<TreeViewItem.ItemContainerStyle>

</TreeViewItem.ItemContainerStyle>

Which will make your simplified XAML look something like this:
<TreeView x:Name="treeView">
    <TreeViewItem>
        <TreeViewItem OnDoubleClick="SelectOtherTab" />
        <TreeViewItem OnDoubleClick="SelectOtherTab"/>
        <TreeViewItem OnDoubleClick="SelectOtherTab" />
        ...
    </TreeViewItem>
</TreeView>

I'm still a bit confused by why you have a parent TreeViewItem and are building child TreeViewItems using it's ItemsSource, however if that's not necessary you can simplify your VisualTree by eliminating the parent TreeViewItem like this:
<TreeView Name="treeView"
          ItemsSource="{Binding ClassCollection}"
          ItemContainerStyle="{StaticResource TreeViewItemStyle}"
          Grid.Row="1" Grid.Column="1">
    <TreeView.Resources>

    </TreeView.Resources>
</TreeView>

Which will make your TreeView look like this:
<TreeView x:Name="treeView">
    <TreeViewItem OnDoubleClick="SelectOtherTab" />
    <TreeViewItem OnDoubleClick="SelectOtherTab"/>
    <TreeViewItem OnDoubleClick="SelectOtherTab" />
    ...
</TreeView>

Comment: Wow, I really apperciate your effort helping me, thank you!          I'm so sorry.. I guess I made a mistake.. that lead you giving me a solution for something I didn't want. I don't want only the parent treeviewitem to be able to click on, I want the opposite, I want to enable all it's child items to be able to click and implement the command. On that way, each treeviewitem(the child items) is built from the ClassCollection Items. I just want to pass the ViewModel that is "responsible" for the item. Thank you once again, sorry for my bad English, let me know if anything is incomprehensible
Comment: @idish I think so :) The code I posted will make it so that each `TreeViewItem` that is generated from `ClassCollection` will have a doubleClick event that calls `SelectOtherTab`, and passes the item from `ClassCollection` in as a parameter
Comment: Then yes, it is. Great! I'm going to try it out in a few. BTW, about your last tip with the treeview, I'm not doing that, because I have another set of TreeViewItem(I showed only the neccasary code).
Comment: @idish I was wondering if that was the case because of your `Header` binding. Let me know how it goes though :)
Comment: It is working!!! Thank you so much, really, you helped me understand a little more how WPF works.. I'm pretty new to that, I started around 2 weeks ago. Anyway, thanks alot!
Comment: Can you just explain me please why in the Path it is Path="DataContext.SelectOtherTab" and not Path="SelectOtherTab"?
Comment: Rachel, I would be very thankfull if you could help me with my other little problem(refers to same context). Please see my edited post.
Comment: @idish ContextMenus are not part of the same VisualTree as the rest of your application, so Bindings can't find their values. You'll need to use `PlacementTarget` in your bindings to find the `TreeViewItem`, then find your command from there. See [this answer of mine](http://stackoverflow.com/a/11211901/302677) for an example
Answer: you must declare a property of type SecondViewModel in MyViewModel.then you can bind the data to inner items too.
CommandParameter ="{Binding SecondViewModelProp.CommandParam}"
if command parameter is defined inside the SecondViewModelProp.
Let me know if I understood something wrong.
 public class MyViewModel
 {
    public SecondViewModel  SecondViewModelProp
    {
        get { return new SecondViewModel(); }
    }

   public MyViewModel()
   {

   }
 }

Comment: If I'll declare a property of type SecondViewModel, how can I bind it to my treeviewitem's commandparameter?
Comment: Hmm sorry, didn't realy understand. What is SecondViewModelProp? What will this property do? and what is the CommandParam?
Comment: SecondViewModelProp  is property for the  SecondViewModel inside myViewModel.
Comment: But what will it return? I want to return the current SecondViewModel(the one who is responsible for the treeviewitem)
Comment: Ahh, sorry for digging too much, but I want to understand before I try, how would getting new SecondViewModel will help me? I want to return the current existing SecondViewModel.(It is already inside an observableCollection)


Is there a way in Snowflakes to get the list of tables used from given set of views

Question: I'm looking for a SQL script or some metadata table for views which have the source info.
Comment: Have you tried [GET_DDL](https://docs.snowflake.com/en/sql-reference/functions/get_ddl.html)?
Comment: Get DDL gets the entire view definition or table create statement, not only the source of the view.
Answer: You can use the function GET_OBJECT_REFERENCES to return the list of objects referenced by a view.
Please review the below documentation for more information and example:
https://docs.snowflake.com/en/sql-reference/functions/get_object_references.html#get-object-references


List of Strings in multiple buttons

Question: I have a list of Strings (Video tags) and I wanna show each of them in a button (same as when you want to send a text for multiple users) and when I click on each an action happens for that box. I took a look at:
https://github.com/kpbird/chips-edittext-library
It generate each string in a box but finally I don't have access to specific item onclick.
Does anyone has any suggestion what to use or how to make it?!
Comment: Please show your code then we may suggest something.
Comment: @soulreaver I don't have a code for that yet. Imagine there is a ArrayList and I want each item to be a Button and place after each other.
Comment: http://stackoverflow.com/questions/7195056/how-do-i-programmatically-add-buttons-into-layout-one-by-one-in-several-lines
Comment: @Rudi, have you read this ? http://stackoverflow.com/about
what you want is creating a button programmatically ... http://bit.ly/17wycbp
Answer: Read out the array of strings and
programmatically add a button with the text of each
string to for example a LinearLayout.
pseudo code:
<code>ArrayList<string> list = getResources.array("id");

LinearLayout l = (Linearlayout) findViewById(R.id.linearlayout);
foreach(String s in list)
{
   l.addView(new Button(s));
}
</code>
Something like that.

List of Strings in multiple buttons


Triangulation of Torus in three different ways, but two of them are wrong.

Question: In my geometry notes the writer states that the following two, are not triangulations for the torus:

On the contrary this is a good triangulation:

I tried to wrap a piece of paper in order the check the issues with the first two examples, but I'm not a good artist! As I could read here in a similar question, the first one can't be a triangulation since the $AD$ segment becomes a circle. By the way in the second example this doesn't happen since every edge is divided into two pieces. What's the problem with the second one?
Comment: This may depend on the exact definition of what a "good" triangulation is. I assume you are using *piecewise linear triangulations*, in which case it is a no-no that two triangles share two vertices without also sharing the edge between these.
Comment: If $T_1 \cap T_2 \not= \emptyset$ then they share exactely a vertex or exactely an edge.
Comment: So the problem is the diagonal? Since it is divided into 2 pieces that stay different, but  they have both vertices in common?
Answer: A triangulation has the property that two simplices are only allowed to intersect in another simplex (For the two dimensional case this is a point or edge). In the first picture the two triangles intersect in a union of three edges, which is not a simplex. I think you can see what goes wrong in the second picture now.


How to split regular expression in PHP?

Question: I have problem to split this variable. I just want the 1088 number.
http://ebook.com/php+in+100+days-1088.aspx

I've tried, but no luck, my code
print_r(preg_split("/[a-zA-Z]+-[0-9]+.aspx/", 'http://ebook.com/php+in+100+days-1088.aspx'));

Answer: preg_match( '/(\d+)\.aspx$/', 'http://ebook.com/php+in+100+days-1088.aspx', $matches );

$matches[1] gives you the 1088 number.
Comment: +1 for including the .aspx in regex. other suggestions may fail with certain URLs such as `ebook.com/php.in+1000-days-1088.aspx`
Answer: Not quite sure why the regex, but this one works for me:
$parts = preg_split("/(-|\.)/", 'http://ebook.com/php+in+100+days-1088.aspx');
echo $parts[2];

How to split regular expression in PHP?


How to implement operator[] for a class which holds a std::vector

Question: I'd like to override the [] operator for an object which holds a std::vector object (that is, have the subscripting act as though it were directly applied to the member vector).
This is what I have so far
using namespace std;
#include <string>
#include <iostream>
#include <vector>

class VectorWrapper
{
public:
    VectorWrapper(int N): _N(N), _vec(N) {}

    ~VectorWrapper() {delete &_vec;}

    string operator[](int index) const
    {
        return _vec[index];
    }

    string& operator[](int index)
    {
        return _vec[index];
    }

private:
    int _N;
    vector<string> _vec;
};

int main()
{
    VectorWrapper vo(5);
    vo[0] = "str0";
    std::cout << vo[0];
}

Which upon running produces the following error
Process finished with exit code 11

What am I doing wrong?
Comment: `~VectorWrapper() {delete &_vec;}` nonono very bad idea.
Comment: Don't call delete on something that was not created with new.
Comment: Handy reading: [The Rules of Three, Five, and Zero](https://en.cppreference.com/w/cpp/language/rule_of_three). Because `vector` observes the Rule of Five for you, your class can observe the Rule of Zero and do nothing. You want to write classes that use the Rule of Zero unless you need special resource handling, and in that case you observe Three or Five so everyone depending on the class can observe Zero.
Answer: You are trying to delete your member in the destructor. Only use delete on objects that you created with new. Remove that destructor completely, the language will handle the destruction for you.
Also, your first index operator should return a const reference
string const& operator[](int index) const

instead of a value.
Furthermore, _N is an illegal name. You're not allowed to name things starting with an underscore followed by an uppercase letter.
Comment: Reference: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783/14065)
Comment: see "https://www.tutorialspoint.com/What-are-the-rules-to-declare-variables-in-Cplusplus":  2. All variable names must begin with a letter of the alphabet or an underscore(_).  and other places.  Is the "followed by an uppercase letter' a new rule?
Comment: @2785528 Quite old. At least as old as C++03, and possibly inherited from C. It doesn't get you very often, but when it does, the error messages and program behaviour (if you're unlucky enough for the code to still compile) are utterly bizarre. If you don't know the naming rules ahead of time debugging this can be a real mind.


Update dict em List Comprehensions

Question: Tenho alguns dicionários que preciso preencher recursivamente e para isso gostaria de usar list comprehensions desta forma
list_dict = [{'a':'b'},{'a':'c'}]

list_dict = [dict.update({'b':dict['a']}) for dict in list_dict]

O objetivo era trabalhar com datetime onde eu adicionaria um valor a cada dicionario.
O problema é que ao utilizar dict.update() ele retorna None ao invés do valor do dicionário o que me devolve mais ou menos isso:
[None,None]

Tentei utilizar também um map() desta forma:
list(map(lambda dict: dict.update({'novo_valor':100}),list_dict))

Porém recebi o mesmo retorno.
Tentei algumas outras coisas como utilizar and dentro do list comprehension mas sem sucesso.
Alguém tem algum idéia que possa ajudar.
Exemplo pratico:
MAX_DAYS_TO_INACTIVE = 15
MAX_DAYS_TO_EXPIRATION = 30
Entrada = {
        'UserName':'user.1',
        'AccessKeyId':'CCCCCCCCCCCCCCCCCCCC',
        'Status':'Inactive',
     'CreateDate':datetime.datetime(2019,9,10,20,12,45,tzinfo=tzutc())
    },
    {
        'UserName':'user.2',
        'AccessKeyId':'BBBBBBBBBBBBBBBBBBBB',
        'Status':'Active',
      'CreateDate':datetime.datetime(2020,4,16,1,26,18,tzinfo=tzutc())
    }
]

Função que criei:
def add_date_paramters(complete_access_key_list):
    key_list = list()
    for acess_key in complete_access_key_list:
        acess_key.update(
            {
                'InvalidationDate':acess_key['CreateDate']+datetime.timedelta(days=MAX_DAYS_TO_INACTIVE),
                'ExpirationDate':acess_key['CreateDate']+datetime.timedelta(days=MAX_DAYS_TO_EXPIRATION),
            }
        )
        key_list.append(acess_key)
    return key_list

Espero ter algo parecido com isso:
saida = [ {
        'UserName':'user.1',
        'AccessKeyId':'CCCCCCCCCCCCCCCCCCCC',
        'Status':'Inactive',
        'CreateDate':datetime.datetime(2019,9,10,20,12,45,tzinfo=tzutc()),
        'InvalidationDate':datetime.datetime(2019, 9, 25, 20, 12, 45, tzinfo=tzutc()),
        'ExpirationDate':datetime.datetime(2019, 10, 10, 20, 12, 45, tzinfo=tzutc())
    },
    {
        'UserName':'user.2',
        'AccessKeyId':'BBBBBBBBBBBBBBBBBBBB',
        'Status':'Active',
        'CreateDate':datetime.datetime(2020,4,16,1,26,18,tzinfo=tzutc()),
        'InvalidationDate':datetime.datetime(2020, 5, 1, 1, 26, 18, tzinfo=tzutc()),
        'ExpirationDate':datetime.datetime(2020, 5, 16, 1, 26, 18, tzinfo=tzutc())
    }, ]

Comment: Você tem ao menos um exemplo prático com uma entrada e a saída esperada ?
Comment: desculpe não pude responder tudo aqui, completei na pergunta
Comment: @Lacobus Obrigado consegui resolver.
Answer: Solução básica na qual a lista de dicionarios é atualizada in-place:
from dateutil.tz import tzutc
from datetime import timedelta, datetime

MAX_DAYS_TO_INACTIVE = 15
MAX_DAYS_TO_EXPIRATION = 30

list_dict = [
    {
        'UserName'   : 'user.1',
        'AccessKeyId': 'CCCCCCCCCCCCCCCCCCCC',
        'Status'     : 'Inactive',
        'CreateDate' : datetime(2019,9,10,20,12,45,tzinfo=tzutc())
    },
    {
        'UserName'   : 'user.2',
        'AccessKeyId': 'BBBBBBBBBBBBBBBBBBBB',
        'Status'     : 'Active',
        'CreateDate' : datetime(2020,4,16,1,26,18,tzinfo=tzutc())
    }
]

for dic in list_dict:
    dic['InvalidationDate'] = dic['CreateDate'] + timedelta(days=MAX_DAYS_TO_INACTIVE)
    dic['ExpirationDate'] = dic['CreateDate'] + timedelta(days=MAX_DAYS_TO_EXPIRATION)

print(list_dict)

Saída:
[
  {
    'UserName': 'user.1',
    'AccessKeyId': 'CCCCCCCCCCCCCCCCCCCC',
    'Status': 'Inactive',
    'CreateDate': datetime.datetime(2019, 9, 10, 20, 12, 45, tzinfo=tzutc()),
    'InvalidationDate': datetime.datetime(2019, 9, 25, 20, 12, 45, tzinfo=tzutc()),
    'ExpirationDate': datetime.datetime(2019, 10, 10, 20, 12, 45, tzinfo=tzutc())
  },
  {
    'UserName': 'user.2',
    'AccessKeyId': 'BBBBBBBBBBBBBBBBBBBB',
    'Status': 'Active',
    'CreateDate': datetime.datetime(2020, 4, 16, 1, 26, 18, tzinfo=tzutc()),
    'InvalidationDate': datetime.datetime(2020, 5, 1, 1, 26, 18, tzinfo=tzutc()),
    'ExpirationDate': datetime.datetime(2020, 5, 16, 1, 26, 18, tzinfo=tzutc())
  }
]

Veja funcionando no Repl.it
Encapsulando em uma função:
def add_date_parameters(lst):
    for dic in lst:
        dic.update({
            'InvalidationDate': dic['CreateDate'] + timedelta(days=MAX_DAYS_TO_INACTIVE),
            'ExpirationDate'  : dic['CreateDate'] + timedelta(days=MAX_DAYS_TO_EXPIRATION)
        })
    return lst

Comment: Crie os testes unitários para as duas funções e realmente sua forma é mais performática.
1.000.000 de requisições a função obtive os seguintes resultados.
feito um teste de stress com
=== 1 passed, 1 warning in 8.28s ===
contra:
===1 passed, 1 warning in 15.78s ===
Para poucas requisições costuma ficar perto de 0.50.

Sempre ouvi que esses map() filter() e comprehension eram mais performáticos, essa diferença se da por que estou aplicando errado ou algo do tipo?
Answer: Liguei para um amigo e expliquei o caso.
Ele me sugeriu utiliza o operado or para quando o dict.update() retornar None a expressão considerar o retorno como o que vem depois:
solução:
def add_date_paramters(complete_access_key_list):
    return map( lambda acess_key: acess_key.update(
        {
            'InvalidationDate':acess_key['CreateDate']+datetime.timedelta(days=MAX_DAYS_TO_INACTIVE),
            'ExpirationDate':acess_key['CreateDate']+datetime.timedelta(days=MAX_DAYS_TO_EXPIRATION)
        }
    ) or acess_key ,complete_access_key_list)

Meu erro foi tentar utilizar o and que acabava sendo falso na primeira verificação e não retornava nada.
Agradeço a atenção.

Update dict em List Comprehensions


Configuring Logger in Razor Pages application

Question: I'm trying to get up to speed on ASP.NET Core Razor Pages so I was trying to step through the article Logging in .NET Core and ASP.NET Core.
A lot of the documentation I've been finding is not panning out for one reason or another, and I didn't get very far through this article either. Near the top, it contains the following code snippet.
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

But that code just won't even compile for me.

I've tried Ctrl+. and everything else I could think of, but WebHostBuilderContext just doesn't have the methods shown in this article.
Can someone tell me what I'm doing wrong?
Comment: You should try reading further through the documentation before quitting; directly under the code snippets is the following statement: *"`LoggerFactory` and `AddConsole` require a `using` statement for `Microsoft.Extensions.Logging`."* Additionally, if you followed the link near the top of the page to [View or download sample code](https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/logging/index/samples) you would have found complete working code examples.
Answer: Assuming you are also using .NET Core 3,
the sample works for me out of the box with no issues if i create a new ASP.NET Core MVC app in VS 2019 selecting .NET Core 3,
you might not have created a project in that way, are you sure you have this using at the top? if not, add this at top of program.cs and if does not resolve means you have to first add the reference to this assembly.
using Microsoft.Extensions.Logging;

Comment: Adding the `using` statement fixed it. I'm using the very latest version of Visual Studio, but I'm building a Razor Pages app and not MVC (that shouldn't matter). Don't understand why *Ctrl+.* wasn't smart enough to suggest the `using`.
Comment: @JonathanWood It's an extension method, which is complicated for IntelliSense to figure out. With VS2019 16.1, experimental support for more inclusive IntelliSense was added, but it is still opt-in even in 16.3.7 and must be enabled by checking "Show items from unimported namespaces (experimental)" under the C# IntelliSense options. I'm not entirely sure if even that will detect extension methods like that, however.
Comment: @Herohtar: Oh, that would explain it.


How to parse a list of sentences?

Question: I want to parse a list of sentences with the Stanford NLP parser.
My list is an ArrayList, how can I parse all the list with LexicalizedParser?
I want to get from each sentence this form:
Tree parse =  (Tree) lp1.apply(sentence);

Answer: Although one can dig into the documentation, I am going to provide code here on SO, especially since links move and/or die.  This particular answer uses the whole pipeline.  If not interested in the whole pipeline, I will provide an alternative answer in just a second.
The below example is the complete way of using the Stanford pipeline.  If not interested in coreference resolution, remove dcoref from the 3rd line of code.  So in the example below, the pipeline does the sentence splitting for you (the ssplit annotator) if you just feed it in a body of text (the text variable).  Have just one sentence?  Well, that is ok, you can feed that in as the text variable.
   // creates a StanfordCoreNLP object, with POS tagging, lemmatization, NER, parsing, and coreference resolution
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

    // read some text in the text variable
    String text = ... // Add your text here!

    // create an empty Annotation just with the given text
    Annotation document = new Annotation(text);

    // run all Annotators on this text
    pipeline.annotate(document);

    // these are all the sentences in this document
    // a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
    List<CoreMap> sentences = document.get(SentencesAnnotation.class);

    for(CoreMap sentence: sentences) {
      // traversing the words in the current sentence
      // a CoreLabel is a CoreMap with additional token-specific methods
      for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
        // this is the text of the token
        String word = token.get(TextAnnotation.class);
        // this is the POS tag of the token
        String pos = token.get(PartOfSpeechAnnotation.class);
        // this is the NER label of the token
        String ne = token.get(NamedEntityTagAnnotation.class);
      }

      // this is the parse tree of the current sentence
      Tree tree = sentence.get(TreeAnnotation.class);

      // this is the Stanford dependency graph of the current sentence
      SemanticGraph dependencies = sentence.get(CollapsedCCProcessedDependenciesAnnotation.class);
    }

    // This is the coreference link graph
    // Each chain stores a set of mentions that link to each other,
    // along with a method for getting the most representative mention
    // Both sentence and token offsets start at 1!
    Map<Integer, CorefChain> graph =
      document.get(CorefChainAnnotation.class);

Answer: Actually documentation from Stanford NLP provide sample of how to parse sentences.
You can find the documentation here
Comment: Also look at the ParserDemo examples that come with the parser. You can call apply() directly on a String that is a sentence.
Answer: So as promised, if you don't want to access the full Stanford pipeline (although I believe that is the recommended approach), you can work with the LexicalizedParser class directly.  In this case, you would download the latest version of Stanford Parser (whereas the other would use CoreNLP tools).  Make sure that in addition to the parser jar, you have the model file for the appropriate parser you want to work with.  Example code:
LexicalizedParser lp1 = new LexicalizedParser("englishPCFG.ser.gz", new Options());
String sentence = "It is a fine day today";
Tree parse = lp.parse(sentence);

Note this works for version 3.3.1 of the parser.

How to parse a list of sentences?


Algorithm for 'Shift + Clicking' items in a collection to select them

Question: I am trying to mimic the file selecting from Windows Explorer in Javascript. I notice Windows Explorer has two types of "selecting". One is the normal selection which highlights the file and the other one is a dotted line which means that file is currently focussed on. So I am using "selected" and "focus" as css classes.
Here you can find an example of my code working in a webpage.
In my code it just finds the rows between the focussed item and the current item and select those.
<code>select: function (e) {
    if (e.ctrlKey) {
        rs.removeFocus();
        $(this).toggleClass("selected");
        $(this).addClass("focus");
    }
    else if (e.shiftKey) {
        var focusItem = $("#Items p.focus");
        var currentItem = $(this);
        var betweenItems = rs.betweenItems(currentItem, focusItem);

        rs.unSelectAll();
        rs.removefocus();

        $(betweenItems).each(function () {
            this.addClass("selected");
        });

        focusItem.addClass("selected");
        $(this).addClass("focus");
        $(this).addClass("selected");
    }
    else {
        rs.unSelectAll();
        rs.removeFocus();
        $(this).addClass("selected");
        $(this).addClass("focus");
    }
}
</code>
This works "okay" but it's not exactly as advanced as the Windows Explorer selecting. In Windows Explorer they don't always select the rows between last focussed item and the current one. If there are no "gaps" in the selection they will add those items to the selection. But if there is a gap it will start from the focussed item.
I am not sure how I should do this. It seems the algorithm they use in Windows is a little to complex for me. So if anybody can help me or push me into the right direction I would appreciate it.
Comment: Way to much code. And you shouldn't ask question like this as you are in fact asking others to do your work. Perhaps you should refrase this as an algorithm question?
Comment: I believe the 'dotted line' box in Windows more precisely means focused, but not selected. You can hold down the control key and use the arrows to change which item has focus and use the spacebar to select.
Comment: @Sean Kinsey: Thanks for the input I adjusted my question and made it smaller. @JC: Thanks, I changed 'last' into 'focus' which is a better name for it.
Answer: The shift-click algorithm for Windows (at least Windows 7, which is what I'm running) is: Track the last item selected not by a shift-click.  On a shift-click, select all items between that item and the current click inclusive.
Examples:
1) If you have just item 5 selected, and shift-click 8, it will select 5-8.
2) If you have item 5 selected, then ctrl-click 3, then shift-click 8, then it will select 3-8.  But if you have item 3 selected, then ctrl-click 5, then shift-click 8, it will select 5-8 instead.  So the history matters.
3) If you have item 5 selected, then shift-click 8, it will select 5-8; if you follow that with shift-click 3, it will unselect 5-8 and select 3-5.  Even though the last item selected was 8, it uses 5 as the anchor, since it was the last item that was not selected with a shift-click.  So items selected with shift-click are excluded from the history.
This means to emulate Windows shift-click, you can't just know what is selected, you need to know how it was selected as well.
Mac OS behaves differently from Windows in two ways.  First, if you shift-click outside the bounds of the currently selected items, it always expands.  For example, if you have item 5 selected, then shift-click 8, it will select 5-8.  If you then shift-click 3, it will expand the selection to 3-8, not unselect 5-8 and select 3-5 as Windows would.  Second, if you click inside the bounds of the current selection, it will fill in from the topmost selected item to the item you clicked on.  If you have items 3 and 8 selected, and shift-click 5, it will select 3-5, regardless of whether you clicked 3 or 8 more recently.  So to emulate Mac OS, you don't need to track the history.
Answer: On macOS the rules are a bit subtle / nuanced. I documented them and created an implementation in javascript here: https://github.com/ibash/better-multiselect
Basically it's:

Click

move anchor and selection to the element clicked
selection is the element clicked

Command click

if the element is not selected

move anchor and selection to the element clicked
add it to the selection

if the element is selected

remove it from the selection
anchor / focus move to: the next greatest selected, or the least index (backwards) from click point

shift click

remove everything between anchor and focus
move focus to where clicked
add everything between focus and anchor
Answer: Try this plugin: https://github.com/luckyseven/jquery-multiselector
An easy way to make page elements selectable using Shift and Ctrl/Command keys with left mouse click.


The largest negative number that fulfills the congruence equation 8x+7≡3 mod 35

Question: So as an exercise I'm trying to figure out which largest negative fulfills 8x+7≡3 (mod 35)
I have solved the x, x=17, but honestly I have no idea where to go from here.
Maybe 17-35=(-18)?
I'd appreciate any pointers and help.
Thanks for your time.
Comment: As you say, we have $x \equiv 17 \,(\text{mod } 35)$.  So $17$ is a solution, but also any number which is of the form $35k + 17$ for some $k \in \mathbb{Z}$ will work. Setting $k= -1$ gives you the largest negative number, namely $-18$, as you said.
Comment: Yes, $-18$ (there is no solution inbetween because 35 and 8 are coprime: if $8x+7\equiv3\equiv8\cdot17+7\bmod{35}$, i.e. if $35\mid8(x-17)$, then $35\mid x-17$).
Answer: If $$8x + 7 \equiv 3 \pmod {35}$$ this means that $8x + 7$ leaves a remainder of $3$ when divided by $35$; i.e., $$8x + 7 = 35q + 3$$ for some integer $q$ (which is called the quotient).  This gives us $$35q = 8x + 4 = 4(2x+1).$$  Since $4$ does not divide $35$, it must divide $q$.  So suppose $q = 4m$; we get
$$35m = 2x+1.$$
What is the largest $x < 0$ that satisfies this equation for integers $m$?  well, the largest $m$ such that $35m$ is a negative integer is $m = -1$; hence $2x + 1 = -35$ or $$x = -18.$$
We can also characterize the full set of $x$ that satisfies the original congruence:  we have $$x \in \{\ldots, -88, -53, -18, 17, 52, 87, \ldots \}.$$  That is, $x = 35m + 17$ for any integer $m$.


how to properly move one or more packages into another package in java using code

Question: I am developing an application [desktop swing application] which requires me to do refactoring via code. [I know the interface and feature is already provided by the eclipse IDE but I am required to do this via code
the first phase of refactoring that i require to do is move selected package [the option to select is given via checkboxes that displays all the available packages in the workspace using the idea of JDT. I used tutorial at this location: http://www.vogella.de/articles/EclipseJDT/article.html ]
Now that I have selected the packages that I wish to move to another package,
I used this piece of code
<code>233.   for (IPackageFragment mypackage : packages) {
234.                    if ((mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) && (searchifSelected(mypackage.getElementName())==true) ){
235.                        IJavaElement container = newModule.getPrimaryElement();
236.                        mypackage.move(container, null, null, true, null);
                }
     }
</code>
searchifSelected(mypackage.getElementName())==true tells me if I have selected this particular package to be moved
IJavaElement container = newModule.getPrimaryElement(); is the container [new package] that will contain the selected packages
mypackage.move(container, null, null, true, null); as far as I read it, this command is supposed to move "mypackage" to "container" as a "child".
however, I am facing this problem:
<code> Java Model Exception: Java Model Status [Invalid destination: 'devFromSupplier [in src [in test]]']
at org.eclipse.jdt.internal.core.MultiOperation.processElements(MultiOperation.java:175)
at org.eclipse.jdt.internal.core.CopyResourceElementsOperation.processElements(CopyResourceElementsOperation.java:417)
at org.eclipse.jdt.internal.core.MultiOperation.executeOperation(MultiOperation.java:90)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:728)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:793)
at org.eclipse.jdt.internal.core.JavaModel.runOperation(JavaModel.java:297)
at org.eclipse.jdt.internal.core.JavaModel.move(JavaModel.java:258)
at org.eclipse.jdt.internal.core.PackageFragment.move(PackageFragment.java:420)
at newmodulewizrd.ui.Integrate.printPackageInfos(Integrate.java:236)
at newmodulewizrd.ui.Integrate.printProjectInfo(Integrate.java:177)
at newmodulewizrd.ui.Integrate.getWorkSpace(Integrate.java:149)
at newmodulewizrd.ui.Integrate.moveToOneModule(Integrate.java:120)
at newmodulewizrd.ui.Integrate$1.actionPerformed(Integrate.java:79)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
</code>
which I think means that I am giving the wrong arguments.
can somebody help what should I do about it?
Comment: @carl: i mentioned it earlier, i have to do this via code, without using the feature by IDE
Comment: can you include the line numbers to your code segment..
Comment: i am sorry, i did not get ur point?
Comment: @ rana, i have added line numbers
Answer: I posted the problem on eclipse forum [the IDE that I m using] and then found that the problem/bug with the method that it will not work in the loop. You will have to explicitly call this function one by one. A similar bug has been reported in this link too :
https://bugs.eclipse.org/bugs/show_bug.cgi?id=240286 [w.r.t delete method]
Answer: For those who r facing the same problem, i found another way to do it, i.e use rename method and make it work as move function. although, it might/might not be the best option.
i replace above code with this code
<code>     for (IPackageFragment mypackage : packages) {
                if ((mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) && (searchifSelected(mypackage.getElementName())==true) ){
                    mypackage.rename(textfield.getText()+"."+mypackage.getElementName(), true, null);
                }
            }
</code>


Don't know why XML Schema isn't well-formed?

Question: I got a very simple problem, which is related to a given XML Schema file you can see below my post. It's from an exam I have to write in a week and its a question about the schema being well-formed.
The error is already marked yellow and I got the hint that it's about namespaces, but in the end I have no idea how to resolve the problem. My first thought was that the type-definition Type="Book" needs a prefix like Type="urn:Book", but I'm not sure at all.
I thank you for any advice that may help me to fix my lack of knowledge in this case.
Answer: That is because you are specifying that Book is in the urn:schemaS namespace using targetNamespace attribute. For this to work, you need to define a namespeace prefix for urn:schemaS and the qualify it in type="nsPrefix:Book".
Read this tutorial
Comment: Thank you very much for this fast answer, it helped me a lot and I guess I got an idea about the function of namespaces, especially in this case :)
Answer: When you declare a named complexType its name is a qualified one, associated with the target namespace - so what you are declaring is a type Book in the urn:schema5 namespace.
When you reference the type you have to specify its qualified name, and the schema does NOT default to the target namespace, it uses the normal XML namespace declarations. Because you have none, you are trying to use a type Book in the default namespace (''), that does not exist.
You have to either add a namespace declaration:
<xs:schema
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:schema5="urn:schema5"
  targetNamespace="urn:schema5"
  elementFormDefault="qualified">

and then use it
    <xs:element name="book" type="schema5:Book" maxOccurs="3"/>

or (my preferred choice) declare you target namespace as the default one:
<xs:schema
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns="urn:schema5"
  targetNamespace="urn:schema5"
  elementFormDefault="qualified">

and then you don't have to do anything else.


React 18: React Router V6 on route change rerenders complete react app on safari

Question: I have a React App and updated it today to React 18 and ReactRouter v6. On Chrome everything is running fine. But on Safari every time I change a Route to another the complete React App rerender. The console is completely cleared and I see my loading screen, which normally shown when the react app is building.
My App.tsx:
import {
    Route,
    Routes,
    Navigate,
    useLocation,
} from "react-router-dom";
import Typography from '@mui/material/Typography';
import React from "react";
import { useApi } from "./api";
import SidebarLayout from "./components/SidebarLayout";
import LHome from "./pages/lazy/LHome";
import LService from "./pages/lazy/LService";
import LDashbord from "./pages/lazy/LDashbord";
import LMasterplan from "./pages/lazy/LMasterplan";
import LWeekPlanSchedule from "./pages/lazy/LWeekPlanSchedule";
import LEmployeeManager from "./pages/lazy/LEmployeeManager";
import LVacationManager from "./pages/lazy/LVacationManager";
import LLogin from "./pages/lazy/LLogin";
import LJumperDays from "./pages/lazy/LJumperDays";
import LUserVacation from "./pages/lazy/LUserVacation";
import LDebugTools from "./pages/lazy/LDebugTools";
import LAdminPanel from "./pages/lazy/LAdminPanel";
import LCarInterface from "./components/lazy/LCarInterface";
import LCarService from "./components/lazy/LCarService";
import LUserCreate from "./components/lazy/LUserCreate";
import LUserEdit from "./components/lazy/LUserEdit";
import LUserInterface from "./components/lazy/LUserInterface";
import LCarManager from "./pages/lazy/LCarManager";
import LCarCreate from "./components/lazy/LCarCreate";
import LCarEdit from "./components/lazy/LCarEdit";

const App = () => {
const api = useApi();
return (
        <SidebarLayout>
            <Routes>
                {api.isLoggedIn && (
                    <>
                        <Route path="/home" element={ <LHome
                                setNotificationsCount={
                                    setNotificationsCount
                                }
                                group={userGroup}
                            />}/>
                        <Route path="/admin" element={<LAdminPanel />}/>
                        <Route path="/debug" element={<LDebugTools />}/>
                        <Route path="/dashboard" element={<LDashbord />}/>
                        <Route path="/uservacation" element={<LUserVacation />}/>
                        <Route path="/vacationverwaltung" element={<LVacationManager />}/>
                        <Route path="/jumperDays" element={<LJumperDays />}/>
                        <Route path="/weekplan" element={<LWeekPlanSchedule />}/>
                        <Route path="/masterplan" element={<LMasterplan />}/>
                        <Route path="/employees" element={<LEmployeeManager />}/>
                        <Route path="/employees/create" element={<LUserCreate />}/>
                        <Route path="/employees/edit/:id" element={<LUserEdit />}/>
                        <Route path="/employees/show/:id" element={<LUserInterface />}/>
                        <Route path="/cars" element={<LCarManager />}/>
                        <Route path="/cars/create" element={<LCarCreate />}/>
                        <Route path="/cars/edit/:id" element={<LCarEdit />}/>
                        <Route path="/cars/show/:id" element={<LCarInterface />}/>
                        <Route path="/service" element={<LService />}/>
                        <Route path="/service/car/:id" element={<LCarService />}/>
                        <Route path="/lohnverwaltung" element={<Lohn />}/>
                        <Route path="/moneypost" element={<Typography
                                color={(theme) =>
                                    theme.palette.text.primary
                                }
                            >
                                In Entwicklung
                            </Typography>}/>
                        <Route path="/monitorplan" element={<MonitorPlan />}/>
                        {<Route path="*" element={<Navigate to={"/home"} />}/>}
                    </>
                )}
                <Route path="/login" element={<LLogin key="lp" />}/>
                {!api.isLoggedIn && <Route path="*" element={<Navigate to={"/login"} />}/>}
            </Routes>
        </SidebarLayout>
    );
}

and my index.ts:
import { createRoot } from "react-dom/client";
import "./index.css";
import Providers from "./Providers";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = createRoot(document.getElementById("root")!);
root.render(
    <Providers>
        <App />
    </Providers>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();

Hope you understand my Problem and can help me.
Comment: What is the loading screen? How are you changing the routes? Are you *sure* this only reproduces in Safari? Could you create a *running* codesandbox demo that reproduces this issue that we could inspect and debug live? Please include your *exact* steps to reproduce the issue.
Comment: @DrewReese - My loading screen is just an image with an animated div which is turning. It is inside the "root" div, so when the react app is loaded it is out of the DOM three. Until now I just see the problem in safari. I'm changing the routes via useNavigate() which is toggled by clicking buttons on my Sidebar.
Answer: my guess is you forgot the BrowserRouter from 'react-router-dom'.
In the basic concepts it says its the component ' creates a history, puts the initial location in to state, and subscribes to the URL.'
Applied to your code:
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import {BrowserRouter} from "react-router-dom";
const root = createRoot(document.getElementById("root")!);
root.render(
     <BrowserRouter>
        <App />
     </BrowserRouter>
);

Comment: If the router was missing there'd be ***tons*** of invariant violations and warnings/errors. OP surely would have noticed these in other browsers.
Comment: @OrysB no, '!' after a statement is a part of TypeScript syntax, meaning 'this value here is definitely not null' =)
Comment: Good Idea, but the BrowserRouter is inside the Providers Component. I forget it in my Code example
Comment: True. My bad. ^^ | By the way the '!' in 'getElementById("root")!); ' is a typo, isn't it? But I don't know if it could cause something like this.
Answer: Try removing strict mode in your app, if it is enabled.

With Strict Mode in React 18, React will simulate unmounting and remounting the component in development mode.
Comment: "strict mode" isn't a configuration that I know of, it's a component, `React.StrictMode`. It also doesn't appear that the OP is using the `StrictMode` component in their `index.ts` file.


Use polar coordinates to evaluate the integral

Question: use polar coordinates to evaluate the following integral
$\int^{a}_{-a} \int^{\sqrt{a^2-x^2}}_0 e^{-(x^2+y^2)}dydx$
i did in my paper was
my limit are after converting it to polar coordinates
$\int^{\pi}_0 \int^{{a}}_0 e^{-r^2}rdrd\theta$
Are the limits in the above integral true?
Comment: $x^2+ y^2= r^2$, not $r$.  Your integral should have $e^{-r^2}$ rather than $e^{-r}$.  Then use the substitution $u= r^2$.
Comment: Shouldnot the value be $x^2+y^2=a^2$?
Answer: The domain is a half-disk of radius $a$, on the side of the positive $y$.
In Cartesian coordinates, $x$ runs from $-a$ to $a$ and $y$ is between $0$ and $\sqrt{a^2-x^2}$ (where $x^2+y^2=a^2$).
In polar coordinates, $\theta$ runs from $0$ to $\pi$ and $r$ from $0$ to $a$.

In both cases,
$$x^2+y^2\le a^2\land y\ge0.$$
Indeed
$$x^2\le a^2\implies x^2+(a-x^2)\le a^2,$$
and
$$r^2\le a^2\land \theta\in[0,\pi]\implies\sin\theta\ge0.$$
Comment: yes thanks i exatly did it like this


R predict function and Model Object

Question: I'm doing machine learning in R. I would like to know how we can create a model object that we can pass to "predict" function along with new data so that we obtain predicted values.
To elaborate, I'm trying to write a new machine learning algorithm in R. Till now I have only used predict function but don't know how to create "model" objects to pass to predict function. If we're doing a linear regression, calling lm would create "lm" object. If we're doing naiveBayes classifier, and call it from e1071 package, it would create naiveBayes classifier object, which we will pass to predict function. Now, if I'm writing a new algorithm, how do I create an object of that algorithm? And how exactly predict function will process that? What class variables/methods that "model" object should have so that it can be processed by "predict" function available in R? I know this is a bit open ended question, but I couldn't find any proper documentation. A basic/prototype example in terms of code would be highly appreciated. Though I've been using R, I'm not familiar to classes/objects concept in R. Thank you very much.
Answer: You should check out Hadley Wickham's Advanced R Programming guide, especially the part about object oriented programming in R. To provide a couple of useful keywords: you are talking about S3 methods and generic functions.
Basically, predict is a generic function, so when you call predict(obj, data) for, say, an lm model obj, R looks through its list of known names to find the function predict.lm, which provides thecae necessary to make predictions from an lm model.
The model object itself is just a list, with an attribute identifying its class (lm, in the example I'm citing). You'll need to return this list from the function that runs your algorithm, via code like
result <- list(obj=model, data=data, parameters=params)
class(result) <- 'whatever'
return(result)

...or whatever is appropriate output from your algorithm. OK, now you call your function like
myobj <- whatever(y~X, data=dat, weights=wt)

And finally if you run
predict(myobj, newdata, wt.new)

R will look for an call your prediction function as
predict.whatever(myobj, newdata, wt.new)

Read Hadley's page for more details - it can get kind of confusing.
Comment: Thanks so much for the elaborate answer and the link. Will try to understand and get back to you if I've more questions. Just a quick question though - Are you saying we explicitly need to create a function called "predict.whatever"?
Comment: May be it was a stupid question. I think we need to create function "predict.whatever"... how else R would get that..
Comment: Yes you need to write the function predict.whatever yourself. It's first parameter must be the model object (a list with class "whatever"). Good luck!
Comment: Haha, well the only problem is that it was all wrong.

R predict function and Model Object


Understanding the notation $a \equiv b \bmod p \mathbb{Z} [\zeta]$

Question: Im trying to follow Keith Conrad's notes on Fermats Last Theorem for regular primes but I'm having trouble with some unfamiliar notation. Half way down page three he begins talking about a congruence which I'm not sure about. Namely, $y(\zeta - \zeta^{-1})$$  \equiv 0 $ mod p$\mathbb Z[\zeta]$.
My initial thought was that perhaps it's just reminding me what ring we are working in and I just just treat it as (mod p) but  he uses (mod p) many times so there must be some subtle difference I'm not grasping. (He also uses mod p$\mathbb Z$)
Comment: Presumably it is a typo that you have no term on the RHS of the conrgrience. right?  The definition of congruences extends to general rings in the obvious way. You might find [this answer](http://math.stackexchange.com/a/16157/242) illuminating.
Comment: Are you familiar with ideals and quotient rings?
Comment: Yes I am, just never seen it written like that before. Dietrich Burde's answer below is more than sufficient :)
Comment: Oh yes, sorry my mistake. There is supposed to be a 0 there. And thank you! I'll check that out now
Answer: The notation is $a\equiv b\bmod I$ for elements $a,b$ of a ring $R$ and an ideal $I$ of $R$. It means that $b-a\in I$. For $R=\mathbb{Z}$ we would have $I=n\mathbb{Z}$ for some integer $n$, and then we obtain the usual congruence.
In the text on Fermat the ring is $R=\mathbb{Z}[\zeta]$, the ring of integers in the cyclotomic field $\mathbb{Q}[\zeta]$, with the ideal $I=(p)=p\mathbb{Z}[\zeta]$.
Comment: Oh i see, that's simple enough then. Perfect explanation, thank you.
Comment: You are welcome!


Theme and subtheme basics

Question: I am a newbie to Drupal, and I really don't understand the difference between sub-theme and base theme. Why can't I directly edit the base theme?
I am working on a website which is live and has bartik as default theme. I don't know where to start.
Comment: Welcome to Drupal Answers. Please take a moment to review the [FAQ](http://drupal.stackexchange.com/faq) and understand the Drupal Answers community even better!
Answer: You haven't really asked a question. But i'll assume that you want to know what a base and sub-theme is in drupal.
TLDR version
A drupal subtheme inherits the template files (*.tpl.php) and assets (javascript, css, images) of the base theme. If you need to modify or change the template files.
More on subthemes
I think your best bet is to google it. I googled, "drupal subtheme" and found you  drupal documentation regarding subthemes:

Sub-themes are just like any other theme, with one difference: They
inherit the parent theme's resources. There are no limits on the
chaining capabilities connecting sub-themes to their parents. A
sub-theme can be a child of another sub-theme, and it can be branched
and organized however you see fit. This is what gives sub-themes great
potential.

Source: Creating a sub-theme (drupal.org)
In addition to the node page, if you're more inclined to watch a video this is probably a good bet: Drupal Subthemes (youtube.com)
Why should you avoid modifying a base theme

Flexibility: Base themes maintain flexibility. If there is an update, your child theme inherit these changes
Losing your changes: Modifying your base theme means that when an update to the theme comes along your modifications could potentially be lost
Maintain simpler code base: The base theme allows you to abstract a lot of functionality and reduce the code base. This means less maintenance in the long run.

Best Practices with subthemes:

Copy files from the base theme or use the drush command (when available)
Utilize subtheme theme hooks to override your theme
Comment: Great answer, this question could easily have been closed as not constructive but I think your response is more than enough to keep it open :)
Comment: I have one more question, Why can't we use css injector in place of sub-theme?
Answer: Besides the reasons stated on the other answer, you should not modify the base themes because of updates.
Think about a situation where you get a base theme and heavily modify it, then a bug, or worse a security bug is found in the base theme. If you apply the update, you will loose the changes made to that theme and if you don't apply the update, well who knows what could happen.
More here about upgrading and subtheming in general.

Theme and subtheme basics


Como baixar um arquivo através do download do navegador com C#?

Question: Eu tenho uma aplicação MVC Razor Pages, nessa aplicação eu salvo arquivos no banco de dados MySQL definindo como longblob, preciso que o cliente aperte no botão de "Download" e o navegador pergunte para ele onde salvar o arquivo, e consequentemente salvar, tentei através do WriteAllBytes mas não consegui.
<code>        public async Task<IActionResult> getFile(string codProjeto)
    {
        ArrayList diretorio = new ArrayList();
        var arquivo = _context.anexo.Where(x => x.COD_PROJETO == Int32.Parse(codProjeto)).ToArray();
        diretorio.Add(@"C:\Users\Miguel\Downloads\" + arquivo[0].DS_NOME);

        await System.IO.File.WriteAllBytesAsync(diretorio[0].ToString(), arquivo[0].DS_ANEXO);
        return View();
    }
</code>
Comment: System.IO.File é utilizado para a máquina que esta executando o código. ou seja, isso irá gravar um arquivo no seu servidor e não na máquina do cliente.
Comment: Voce deve deixar o navegador cuidar disso para voce. Se o seu endpoint esta retornando uma View, o navegador espera que seja retornado html.  No seu caso, voce deve retornar o arquivo mesmo. De uma olhada nessa resposta: [https://stackoverflow.com/a/72948065/12429763](https://stackoverflow.com/a/72948065/12429763)
Answer: Você pode utilizar um dos métodos: DownloadFile ou DownloadFileTaskAsync da classe WebClient
Exemplo:
<code>public async Task<IActionResult> getFile(string codProjeto)
    {
     ArrayList diretorio = new ArrayList();
     var arquivo = _context.anexo.Where(x => x.COD_PROJETO == Int32.Parse(codProjeto)).ToArray();
     string localFilePath = @"C:\Users\Miguel\Downloads\" + arquivo.DS_NOME;

   // WebClient
    using (WebClient webClient = new WebClient())
    {
      // Baixa o arquivo da URL especificada
      await webClient.DownloadFileTaskAsync(new Uri("URL_DO_SEU_ARQUIVO"), localFilePath);
    }
      return View();
    }
</code>
Comment: A classe WebClient não é mais recomendada para desenvolvimento. Use [HttpClient](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-8.0) ao invés disso.


Java Swing: Allow scroll when textfields are out out of range of scrollpane's view

Question: I have a tabbed pane tabbedPane_1 with scrollpane scrlPnAddServer, which has viewport view set to pnlAddServer. How can i add textfields or other items below the viewable section of the scrollpane. (and allow the user to scroll down to view the items) Currently the items are just not shown when out of range.
        JTabbedPane tabbedPane_1 = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane_1.setBounds(672, 20, 350, 400);
        panel.add(tabbedPane_1);
        JPanel tab = new JPanel();
        tabbedPane_1.add("Build", tab);
        tab.setLayout(null);
        JPanel tab2 = new JPanel();
        tabbedPane_1.add("More...", tab2);
        tab2.setLayout(null);

        JScrollPane scrlPnAddServer = new JScrollPane();
        scrlPnAddServer.setBounds(0, 0, 350, 370);
        tab2.add(scrlPnAddServer);
        scrlPnAddServer.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel pnlAddServer = new JPanel();
        pnlAddServer.setBounds(0, 0, 350, 370);
        scrlPnAddServer.setViewportView(pnlAddServer);
        pnlAddServer.setLayout(null);

Then i add items that I want the user to scroll down to see:
    tfSaveAs = new JTextField("Save As");
    tfSaveAs.setBounds(10, 600, 125, 20);
    pnlAddServer.add(tfSaveAs);
    tfSaveAs.setColumns(10);

Comment: Make use of an appropriate layout manager which is capable of calculating the required information which is used the `JScrollPane` to make decisions whether it should display the scrollbars or not.
Answer: Make use of an appropriate layout manager which is capable of calculating the required information which is used the JScrollPane to make decisions whether it should display the scrollbars or not.
This is just one of the many "auto magical" aspects that the layout management API provides
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design.  There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
See Laying Out Components Within a Container for more details
Comment: Thanks, I was hoping not to have to use a different layout, but Gridlayout seems to do close enough to what I want. :)


where is this SPF problem occuring

Question: Inbound mail to a specific user is been forwarded to his external mailbox at another domain. Add mails are routed correctly with the exception of one domain. When mail are sent to users of my domain, including that user, the mails are delivered to everyone except him...as the mail admin I am getting the message

The following recipient(s) cannot be
  reached:
<code>  usermailbox on 1/10/2011 1:27 PM
        There was a SMTP communication problem with the
</code>
recipient's email server.  Please
  contact your system administrator.
              email.speedimpex.com #5.5.0 smtp;587 email@example.com sender domain does not match SPF
  records>

I am sure this has nothing to do with my mail server, however, can someone confirm?
Answer: You are trying to forward emails from a domain that has SPF records, but that domain does not list your server as a valid source of email for that domain.
Your choices are:

Contact somedomain.co.uk and tell them you're forwarding their mail and want to be added to their SPF record.
Contact the "external mailbox at another domain" and tell them you're forwarding email to one of their users and to whitelist you in their SPF checking.
Use Sender Rewriting Scheme on your server to reflect that you are resending this mail from the original sender.
Comment: I am running exchange server 2003...I came across this http://www.msexchange.org/articles_tutorials/exchange-server-2007/compliance-policies-archiving/exchange-2007/2003-address-rewrite-feature.html however I am not sure if this will fix the problem. If I rewrite the mail going out to this user mailbox would he be able to reply to them at their domain?
Comment: @Saif: that looks to be something different.  http://www.microsoft.com/downloads/en/details.aspx?familyid=c29487ee-ef0a-49f6-a205-f23e0a98f794&displaylang=en&pf=true says its basically for mergers, it replaces the from addresses entirely with the new company's address, not for hiding the sender's domain in a way it can be used.  http://www.libsrs2.org/docs/mta-users.html says an Exchange extension is still "in progress" so your user will have to whitelist you in their "external mailbox". Or send mail directly from "somedomain.co.uk" to "external mailbox" rather than through you.
Answer: Your mail server is not a fault here, but there is a conceptual fault in SPF, that breaks email forwarding.
Explanation:
In this case your mail server is a standard non sender rewriting forwarding service, that is in the mail delivery path. This is completely valid according to RFC_822 (page 18).
The SPF Council prescribes that the ESP that is receiving the email must consider possible Forwarding Services and not reject emails delivered via forwarding services only because of an SPF fail. It states: "For non-sender-rewriting forwarders, accept all mail without checking SPF (any SPF results are meaningless)". See the official SPF website at: SPF: Best Practices/Forwarding

where is this SPF problem occuring


Is it faster to loop through JavaScript objects with fewer properties?

Question: If there are two object definitions and one of the objects has a lot more properties than the other -
Example objects:
var personObjectType1 =
       {
          name: [a string],
          age: [an int]
       };

var personObjectType2 =
       {
          name: [a string],
          age: [an int],
          address: [a string],
          photo: [a link],
          spouse: [a string],
          cars: [an array of strings],
          children: [an array of strings],
          pets: [an array of strings],
          father: [a string],
          mother: [a string],
          birthdate: [a date]
       };

And you have an equal length array of each of those objects, will looping through the array of objects be faster for the objects with fewer properties?
(NOTE: The same action is being performed on each type of object)
Example code:
//personObjectType1Array is an array of 10000 personObjectType1's
//personObjectType2Array is an array of 10000 personObjectType2's

for (var i = 0; i < personObjectType1Array.length; i++)
{
    console.log(personObjectType1Array[i].age);
}

for (var j = 0; j < personObjectType2Array.length; j++)
{
    console.log(personObjectType2Array[i].age);
}

Would one loop run faster than the other? Why or why not?
EDIT:
Responses are saying that there is no difference, can anyone say why?
Comment: Did you try it and see?
Comment: Possible duplicate of [How can I benchmark JavaScript code?](https://stackoverflow.com/questions/1003855/how-can-i-benchmark-javascript-code)
Comment: `Object` is not iterable.
Comment: This is fact that there is no time difference of running both of code, The time consumption of accessing the property value is seems same whether it is more of less.
Still do you have any demo where the performance is varies than put here we can explore
Answer: The performance is seems almost same with both the array

var personObjectType1Array = [];
var personObjectType2Array = [];

for(var i=0; i<10000; i++)
  {
    personObjectType1Array.push({
          name: '[a string]',
          age: 25
       });

    personObjectType2Array.push(
      {
          name: '[a string]',
          age: 25,
          address: '[a string]',
          photo: '[a link]',
          spouse: '[a string]',
          cars: '[an array of strings]',
          children: '[an array of strings]',
          pets: '[an array of strings]',
          father: '[a string]',
          mother: '[a string]',
          birthdate: '[a date]'
       }
    );
  }

//personObjectType1Array is an array of 10000 personObjectType1's
//personObjectType2Array is an array of 10000 personObjectType2's

var startTimeArray1 = window.performance.now();

for (var i = 0; i < personObjectType1Array.length; i++)
{
    //console.log(personObjectType1Array[i].age);
}

console.log('TimeArray1 : ' + (window.performance.now() - startTimeArray1));

var startTimeArray2 = window.performance.now();

for (var j = 0; j < personObjectType2Array.length; j++)
{
    //console.log(personObjectType2Array[i].age);
}

console.log('TimeArray2 : ' + (window.performance.now() - startTimeArray2));

Here I have created a demo
https://jsbin.com/hurewod/edit?js,console
Answer: you can check time taken of both in console.Execution time of those having more property will be more.

var personObjectType1 =
       {
          name : 'xyz',
          age : 12,
          roll : 23,
          code :29,
          height :26,
          address:{"streetNo":121,"City":"New Delhi"}
       };

var personObjectType2 = {name : 'xyz'};

 var t0 = performance.now();
        for (var i = 0; i < personObjectType1.length; i++){
         //console.log(personObjectType1[i].name);
      }
     var t1 = performance.now();
     console.log("Call to personObjectType1 took " + (t1 - t0) + " milliseconds.")
     var t2 = performance.now();
     for (var j = 0; j < personObjectType2.length; j++){
       //console.log(personObjectType2[j].name);
     }
      var t3 = performance.now();
     console.log("Call to personObjectType2 took " + (t3 - t2) + " milliseconds.")
Answer: Probably because the code needs to be compiled the first time through. You'll get the best metrics by calling all methods first, then execute.
Incidentally, the difference in performance between loop will be negligible and the readability benefits of using loop have a marginal performance benefit.


Determine whether the sequence converge or diverge

Question: The sequence is
$$a_{n+1} = 2a_n - 1$$
and
$$a_1 = 1$$
The sequence should be
$$\{1, 1, 1, 1, 1, 1, ...\}$$
and I get
$$\lim_{n\to\infty}a_n = 1$$
However
$$\lim_{n\to\infty}s_n = s = \infty$$
So is the sequence convergent or divergent? In other words, how do I judge the sequence?
Comment: What is $s_n$?  You have only defined what $a_n$ is and have not told us anything about $s_n$... is it the sequence of partial sums or what?  Keep in mind the difference between the words **sequence** and **series**
Comment: It is the sequence of partial sum. s1 = 1, s2 = 2, s3 = 3, ..., sn = n.
Comment: The *sequence* $a_n$ is convergent.  The *sequence* $s_n$, i.e. the *series* $\sum\limits_{n=1}^\infty a_n$, is divergent.  These two facts are not in conflict with one another.  When you say "the sequence is divergent/convergent" and you have talked about multiple sequences, you need to be clear which you are referring to.
Answer: $\displaystyle a_{n + 1} - 1 = 2\left(a_{n} - 1\right) \implies
a_{n + 1} = 2^{n}\left(a_{1} - 1\right) = 0\quad\mbox{because}\ a_{1} = 1$.

In general, the sequence diverges whenever $\displaystyle a_{1} \not= 1$.
Answer: The sequence $a_n$ is convergent, as you pointed out, because the limit is $1$.
The sequence of partial sums, $s_n$, diverges, but this does not mean that $a_n$ does not converge.
Answer: If the seq. is convergent, then $\lim_n a_{n+1}=\lim_n a_{n}$. Now for this limit, let $x=\lim a_{n+1}=\lim a_n$, then
$$
x=2x-1
$$
has solution $x=1$. Can you now prove that for every $\epsilon>0, \exists n \in \mathbb{N}$ s.t $\forall m>n$ we have $|a_m-1|<\epsilon$?
Comment: "If a sequence is convergent then for big enough $n$, $a_{n+1}=a_n$" is false.  The sequence $a_n=\frac{1}{n}$ converges to zero but there exists no $n$ such that $a_n=a_{n+1}$.
Comment: Im refering to that $\lim a_n = \lim a_{n+1}$ @jmoravitz


Menu does not translate on second language

Question: I have a multi language Drupal 8 site. But when I change the language of the Drupal site to the second language everything changes to the selected language except the main menu.
When I change the language when I'm logged in, the main menu will be translated to the selected language.
Can someone help me to make the menu change language when a normal user select his preferenced language?
Answer: Your menu link translations are likely not published. Check the translation details element on the translate form and make sure the published checkbox is checked.
The default behavior around that is a bit weird, especially if you create the menu links before enabling translations, there is an issue that should improve that, might already be better in 8.4
Comment: What do you mean with 'translate form'?
Comment: The place where you translated the menu link?
Comment: Everything is published but the menu is still in the original language