text:
Q: How to hide labels with d3? I am making a timeline sort of project. As of right now, my code looks like the following:
var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
.charge(-300)
.linkDistance(30)
.size([width, height]);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

d3.json("input.json", function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();

var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); })
.style("visibility", function(d) {
                return d.value == 2 ? "hidden" : "visible";
              });

var node = svg.selectAll(".node")
              .data(graph.nodes)
              .enter().append("circle")
              .attr("class", "node")
              .attr("r", 20)
              .style("fill", function(d) { return color(d.group); })
              .call(force.drag)
              .style("visibility", function(d) {
                return d.group == 1 ? "hidden" : "visible";
              })
              .on("mouseover", function(d) {
                if(d.group == 2) {
                  node.filter(function(d) { return d.group == 1; }).style("visibility", "visible");
                  link.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
                  texts.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
                }
              }).on("mouseout", function(d) {
                if(d.group == 2) {
                  node.filter(function(d) { return d.group == 1; }).style("visibility", "hidden");
                  link.filter(function(d) { return d.value == 2; }).style("visibility", "hidden");
              }
            });

var texts = svg.selectAll("text.label")
                .data(graph.nodes)
                .enter().append("text")
                .attr("class", "label")
                .attr("fill", "black")
                .text(function(d) {  return d.name;  });

force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });

node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
texts.attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")";
    });
});
});

As of right now, the text, or labelsconstantly show, even when the nodes and links don't. I'm wondering what I need to do? I don't know if I can assign a value or group to the labels


text:
Q: AuthenticateAsServerAsync is failing Accepting connections from browsers AJAX requests and establishing secure connection:
var task = _stream.AuthenticateAsServerAsync(serverCertificate);
if (!task.Wait(60000, ct)) throw new Exception("Timeout");

one from ~20 clients with new browsers are disconnecting at this stage or connection times out. What can be wrong with this?

A: Turns out that this problem occur because browsers establish additional connections and not establishing ssl/tls. So everything works as expected and have to keep in mind that on AuthenticateAsServerAsync can be long waitings and timeouts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge Two Javascript Objects with Multiple Matches Per Key I have two objects which I am trying to merge. I am almost successfully worked with answer from this question (Merge two unordered objects with different keys but same value?).
The issue is that in my "transpatterns" object, I have two patterns that match "Intercom" key. However, in my output, it only takes the second one. I need it to list both under the same key.
Here is my code:

var hash = {};

var partitions = [{
        '$': {
            uuid: '{0F314A21-B066-B597-BCFA-6EC88CF8813B}'
        },
        name: ['AllPhones']
    },
    {
        '$': {
            uuid: '{4DCF3A89-ADA1-2770-4154-F6E0204D9A71}'
        },
        name: ['Unity_Connection']
    },
    {
        '$': {
            uuid: '{B653BC00-2D90-790C-AE0D-16C3DD2F8EDD}'
        },
        name: ['LAB-Tansform-Calling']
    },
    {
        '$': {
            uuid: '{148C8971-87E4-49D3-1536-69B6C95293B3}'
        },
        name: ['Blocked']
    },
    {
        '$': {
            uuid: '{25534E0F-F69A-FDDB-2FAD-34312BB6CEFC}'
        },
        name: ['LAB-PSTN-Sim-911']
    },
    {
        '$': {
            uuid: '{EC1E144B-2C8C-22CC-F1F5-423CF0343367}'
        },
        name: ['LAB-PSTN-Sim-Local']
    },
    {
        '$': {
            uuid: '{9C7F3223-AE2D-7605-C642-0CEAB81CD555}'
        },
        name: ['LAB-PSTN-Sim-LD']
    },
    {
        '$': {
            uuid: '{15AFADC3-859B-2806-B9D1-5678CE035E3D}'
        },
        name: ['LAB-PSTN-Sim-Intl']
    },
    {
        '$': {
            uuid: '{5DD43CF0-5FB0-A6A0-A71D-D284265F37C7}'
        },
        name: ['Agents']
    },
    {
        '$': {
            uuid: '{7FDE7E11-F821-2491-BB08-E6A41DAB205D}'
        },
        name: ['UCCX']
    },
    {
        '$': {
            uuid: '{17500618-9567-92B9-8C15-95D794094A3F}'
        },
        name: ['Intercom']
    },
    {
        '$': {
            uuid: '{77049844-AB06-F899-26D0-C0940E20D4D5}'
        },
        name: ['Netech_Managers']
    },
    {
        '$': {
            uuid: '{A9DD47E0-1C4A-AAB9-E859-E6EEDB26E6B0}'
        },
        name: ['Assistant_Route_Point']
    }
];

var transpatterns = [{
        '$': {
            uuid: '{3FF82ECB-7364-41DB-176B-65D28885339F}'
        },
        pattern: ['9.19005554444'],
        description: ['Sample Outbound Call Block'],
        routePartitionName: ['Blocked']
    },
    {
        '$': {
            uuid: '{18C2C829-AFAE-DB28-A003-5F1731907D85}'
        },
        pattern: ['555555XXXX'],
        description: ['Inbound DID Range'],
        routePartitionName: ['AllPhones']
    },
    {
        '$': {
            uuid: '{465EFEF8-C405-8D30-2C97-4BF9907C92C6}'
        },
        pattern: ['3100'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    },
    {
        '$': {
            uuid: '{C17E117C-41C7-D459-8CD1-B1D3C4EDC40D}'
        },
        pattern: ['3101'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    }
];

// TESTING NEW
// COMBINE OBJECTS - CREATE HASH
function classify(e) {
    if (hash[e.name] || hash[e.routePartitionName]) {
        Object.keys(e).forEach(function (c) {
            hash[e.name || e.routePartitionName][c] = e[c];
        });
    } else {
        hash[e.routePartitionName || e.name] = e;
    }
}

// COMBINE OBJECTS - ADD VARS to HASH
partitions.forEach(classify);
transpatterns.forEach(classify);

// COMBINE OBJECTS - ITERATE HASH + REMOVE ANY FIELDS
var combo = Object.keys(hash).map(function (e) {
    delete hash[e]['routePartitionName'];
    return hash[e];
});

console.log(combo);

A: I was able to solve my problem. I determined that I needed to collapse the object with multiple items associated with the same key before I merged the two objects. I was able to use the answer from this question to help me do this.
How to combine JSON object with same key and add their other corresponding values?
Here is the code I came up with that seems to work nicely.

// DEFINE VARIABLES
var partitions = [{
        '$': {
            uuid: '{0F314A21-B066-B597-BCFA-6EC88CF8813B}'
        },
        name: ['AllPhones']
    },
    {
        '$': {
            uuid: '{4DCF3A89-ADA1-2770-4154-F6E0204D9A71}'
        },
        name: ['Unity_Connection']
    },
    {
        '$': {
            uuid: '{B653BC00-2D90-790C-AE0D-16C3DD2F8EDD}'
        },
        name: ['LAB-Tansform-Calling']
    },
    {
        '$': {
            uuid: '{148C8971-87E4-49D3-1536-69B6C95293B3}'
        },
        name: ['Blocked']
    },
    {
        '$': {
            uuid: '{25534E0F-F69A-FDDB-2FAD-34312BB6CEFC}'
        },
        name: ['LAB-PSTN-Sim-911']
    },
    {
        '$': {
            uuid: '{EC1E144B-2C8C-22CC-F1F5-423CF0343367}'
        },
        name: ['LAB-PSTN-Sim-Local']
    },
    {
        '$': {
            uuid: '{9C7F3223-AE2D-7605-C642-0CEAB81CD555}'
        },
        name: ['LAB-PSTN-Sim-LD']
    },
    {
        '$': {
            uuid: '{15AFADC3-859B-2806-B9D1-5678CE035E3D}'
        },
        name: ['LAB-PSTN-Sim-Intl']
    },
    {
        '$': {
            uuid: '{5DD43CF0-5FB0-A6A0-A71D-D284265F37C7}'
        },
        name: ['Agents']
    },
    {
        '$': {
            uuid: '{7FDE7E11-F821-2491-BB08-E6A41DAB205D}'
        },
        name: ['UCCX']
    },
    {
        '$': {
            uuid: '{17500618-9567-92B9-8C15-95D794094A3F}'
        },
        name: ['Intercom']
    },
    {
        '$': {
            uuid: '{77049844-AB06-F899-26D0-C0940E20D4D5}'
        },
        name: ['Netech_Managers']
    },
    {
        '$': {
            uuid: '{A9DD47E0-1C4A-AAB9-E859-E6EEDB26E6B0}'
        },
        name: ['Assistant_Route_Point']
    }
];

var transpatterns = [{
        '$': {
            uuid: '{3FF82ECB-7364-41DB-176B-65D28885339F}'
        },
        pattern: ['9.19005554444'],
        description: ['Sample Outbound Call Block'],
        routePartitionName: ['Blocked']
    },
    {
        '$': {
            uuid: '{18C2C829-AFAE-DB28-A003-5F1731907D85}'
        },
        pattern: ['555555XXXX'],
        description: ['Inbound DID Range'],
        routePartitionName: ['AllPhones']
    },
    {
        '$': {
            uuid: '{465EFEF8-C405-8D30-2C97-4BF9907C92C6}'
        },
        pattern: ['3100'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    },
    {
        '$': {
            uuid: '{C17E117C-41C7-D459-8CD1-B1D3C4EDC40D}'
        },
        pattern: ['3101'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    }
];

var hash = {};

// FUNCTION - COMBINE ITEMS WITHIN OBJECT - WITH SAME KEY:routePartitionName
function combine(arr) {
    var combined = arr.reduce(function (result, item) {
        var current = result[item.routePartitionName];

        result[item.routePartitionName] = !current ? item : {
            pattern: current.pattern + ',' + item.pattern,
            description: item.description,
            routePartitionName: item.routePartitionName
        };

        return result;
    }, {});

    return Object.keys(combined).map(function (key) {
        return combined[key];
    });
}

// FUNCTION - COMBINE ITEMS WITHIN OBJECT - RUN
var result = combine(transpatterns);

// FUNCTION - COMBINE OBJECTS - CREATE HASH
function classify(e) {
    if (hash[e.name] || hash[e.routePartitionName]) {
        Object.keys(e).forEach(function (c) {
            hash[e.name || e.routePartitionName][c] = e[c];
        });
    } else {
        hash[e.routePartitionName || e.name] = e;
    }
}

// FUNCTION - COMBINE OBJECTS - ADD VARS to HASH
partitions.forEach(classify);
result.forEach(classify);

// FUNCTION - COMBINE OBJECTS - ITERATE HASH + REMOVE ANY FIELDS
var combo = Object.keys(hash).map(function (e) {
    delete hash[e]['routePartitionName'];
    delete hash[e]['$'];
    return hash[e];
});

console.log(combo);


text:
Q: Regex to switch words? I have long list of two string in every row, numerical string and alphanumerical string (that are of different length in every raw), that I want to change (switch) position:
010110,file_1.txt
0120100,file_11.txt

To have this:
file_1.txt,010110
file_11.txt,0120100

Second string also include dots and underscores, as in example above.
I tried regex that I used before for similar task but it doesn't work, I tried in Notepad++ and Powergrep.
([^_]*),(.*)

Replace with:
\2_\1

Tried that regex (with variations) but didn't have result.

A: I'd do:

*

*Find what: ^([^,]+),(.+)$

*Replace with: $2,$1

*Replace all

A: Use a reluctant quantifier *?:
Find: ^(.*?),(.*)
Repl: $2,$1

.*? matches as little as possible.


text:
Q: Git GUI (for Windows) displays duplicate repos I am using version 1.2.11 of GitHub for windows. As shown in the screenshot below, the same repository is listed multiple times, and I don't know how to clean it up (note: names are censored, but colour coded: the black items are all the same, and the maroon items are all the same).
The github release notes indicate that a problem involving "Duplicate entries Git error for some repositories" was fixed as of 1.0.30, but I still encounter the below situation.
The other posts that I have come across include how to duplicate repositories in the GUI, but I haven't found an answer regarding how to remove the entries from the GitHub GUI for Windows. Note: on github.com there is only one instance of each repo, but in the GUI multiple entries are shown (they all link to the same repo) in various quantities. Also note: one of the "dungeons" entries (the purple one) is a fork of the other.
Image:

A: If you're running the latest version and it's supposed to have fixed the bug, the best thing you could do is to contact them and provide as much information as you can. They'll for sure reply soon asking for further information, and clearly telling you how to get it.
There's probably an issue left, and you can help them solve it - and it's always a pleasure to talk with GitHub's support guys :)


text:
Q: How to get username of person who had hit the custom build Rest API in my Java code? I am trying to build a custom build plugin using Atlassian sdk framework and in that I have developed a Rest API to fetch data saved in Active Objects database tables and I am using basic authentication in postman where I need to provide my local Jira username and password.
In my plugin code, I am storing data using active objects and following code I am using to fetch the stored data in active objects table:
// To delete all the rules present in database table
@DELETE
@Path("/debug/delete/rules")
public Response deleteAllRules() {

    boolean result = rules.deleteAllStoredRules();
    if (result) {
        return Response.noContent().build();
    }
    return Response.status(205).build();
}

Can anyone please help me to find a way to fetch username provided in basic authentication in my java code?

A: The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

Please read more about this: https://www.baeldung.com/get-user-in-spring-security


text:
Q: How do you write to the file system of an aws lambda instance? I am unsuccessfully trying to write to the file system of an aws lambda instance.  The docs say that a standard lambda instance has 512mb of space available at /tmp/. However the following code that runs on my local machine isn't working at all on the lambda instance:
  var fs = require('fs');
  fs.writeFile("/tmp/test.txt", "testing", function(err) {
      if(err) {
          return console.log(err);
      }
      console.log("The file was saved!");
  });

The code in the anonymous callback function is never getting called on the lambda instance.  Anyone had any success doing this?  Thanks so much for your help.
It's possible that this is a related question. Is it possible that there is some kind of conflict going on between the s3 code and what I'm trying to do with the fs callback function?  The code below is what's currently being run.
console.log('Loading function');

var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });
var fs = require('fs');

exports.handler = function(event, context) {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    // Get the object from the event and show its content type
    var bucket = event.Records[0].s3.bucket.name;
    var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    var params = {
        Bucket: bucket,
        Key: key
    };
    s3.getObject(params, function(err, data) {
        if (err) {
            console.log(err);
            var message = "Error getting object " + key + " from bucket " + bucket +
            ". Make sure they exist and your bucket is in the same region as this function.";
            console.log(message);
            context.fail(message);
        } else {

            //console.log("DATA: " + data.Body.toString());
            fs.writeFile("/tmp/test.csv", "testing", function (err) {

                if(err) {
                    context.failed("writeToTmp Failed " + err);
                } else {
                    context.succeed("writeFile succeeded");
                }
            });
        }
    });
};

A: Modifying your code into the Lambda template worked for me.  I think you need to assign a function to exports.handler and call the appropriate context.succeed() or context.fail() method.  Otherwise, you just get generic errors.
var fs = require("fs");

exports.handler = function(event, context) {
    fs.writeFile("/tmp/test.txt", "testing", function (err) {
        if (err) {
            context.fail("writeFile failed: " + err);
        } else {
            context.succeed("writeFile succeeded");
        }
    });
};

A: So the answer lies in the context.fail() or context.succeed() functions.  Being completely new to the world of aws and lambda I was ignorant to the fact that calling any of these methods stops execution of the lambda instance.
According to the docs:

The context.succeed() method signals successful execution and returns
  a string.

By eliminating these and only calling them after I had run all the code that I wanted, everything worked well.

A: I ran into this, and it seems like AWS Lambda may be using an older (or modified) version of fs. I figured this out by logging the response from fs.writeFile and noticed it wasn't a promise.
To get around this, I wrapped the call in a promise:
var promise = new Promise(function(resolve, reject) {
    fs.writeFile('/tmp/test.txt', 'testing', function (err) {
        if (err) {
            reject(err);
        } else {
            resolve();
        }
    });
});

Hopefully this helps someone else :hug-emoji:


text:
Q: Mutithreading in django when interactiong with database, what i need to know and pay attention to? My site will need to parse large amounts of data from multiple web pages in regular intervals. I'm thinking about using celery or python threads to speed that up.
I'm afraid of hard to debug errors when interacting with database.
For example is it possible/ what will happen when 2 threads will call SampleModel.object.get_or_create(name="same string") at the same time?
Or what will happen if (simplified pseudocode to show the idea):
mymodel(models.Model)
      title = models.CharField()
      (...)
      owner = models.ManyToManyField(Creator)

def FindPageCreatorName(page):
    (...)
    return name

and in multiple threads i will call
def create_mymodel(url): #thats what will be run in each thread
    page = urllib.urlopen(url)
    mymodelInstance.title = FindPageTitle(page)
    (...)
    mymodelInstance.save()
    creator = Creator.get_or_create(name=FindPageCreatorName(page))
    mymodelInstance.creator.add(creator)

and it will find same creator name on multiple pages in roughly the same time?
(other thread will change database between another instructions)
Should i encapsulate each thread in transaction and it will be enough to prevent errors?
What are other scenarios that may not work as intended?
Or I shouldn't worry because nothing bad can happen, celery will take care of such things?
If you cant point me to any good tutorials or docs on this topic i will be grateful. Sorry for such vague question but i don't have a clue what specific problems may appear - thats the question.
Also it will be probably only thing in the code that needs to be multi threaded - should i use celery or python threads in that case? (isn't celery an overkill?)

A: Bad things can certainly happen if you have enough requests per second.
What will happen if two threads call SampleModel.object.get_or_create(name="same string") simultaneously? What about if there are two processes instead? What if it is called by two worker nodes?
In cases like this, you need to think of where the failure might occur.
If you have two worker nodes accepting jobs from Celery, and if the two call a database operation simultaneously, there is nothing in the django code base that can provide any guarantee of what will happen.
If two different threads in the same process call the database action, they cannot call it simultaneously, since they are restricted by CPU access.
But if you do have multiple nodes, who hit the database, the database itself will execute them one after the other (there are exceptions). So in that case, you want to make sure that the database rejects the second create command. Depending on the database, this can be done by adding a unique index on the relevant fields.
You need to think your design through, and make sure you have sequential data writes in the database, if that is what you need. Parallel data writes, in certain databases, will provide much better performance, but won't provide data integrity.


text:
Q: How to interface C++ and Excel (Output from C++ program to an Excel spreadsheet) I am making a small program for my job (it has nothing to do with programming) to help them with the many measurements and efficiency of their job.
I have made most of the program in a Console App in C++ with Code::Blocks.
Would it be possible to yank the output of variables from my C++ and put them in certain cells in an Excel spreadsheet? I have looked around the internet for some forums but some do not work or have me use Visual Basics. Any clues or hints would help dramatically. Thanks.
Source Code:
#include <iostream>
#include <cstdlib>
#include <cmath>

//Function Prototypes -- *
void DisplayMenu();
void Bahama();
int Colonial();
int StormPanel();

 void DisplayMenu()
{

    int a;

    std::cout << "*---Display Menu---*\n";
    std::cout << "1) Bahama/Colonial\n";
    std::cout << "2) Strom Panel\n\n";

    std::cout << "Type the corresponding number for\n";
    std::cout << "the type of shutter you need calculated: ";

        std::cin >> a;

        switch(a)
        {
        case 1:
            Bahama();
            break;
        case 2:
            StormPanel();
            break;

        }

}

void Bahama()
{

    int Token = 200;

    do{

    int SN; //Shutter Number
    int QSL; // Quantity of Shutter Louvers

    double W; //Width
    double H; //Hight
    double Sl; // Shutter Louvers (trail)
    double SL; // Size of Shutter Louvers

    float Sd = 3.7812; // Single Deduction
    float Dd = 5.6562; // Double Deduction
    float Td = 7.5312; // Triple Deduction
    float Qd = 9.4062; // Quadruple Deduction
    float QTd = 11.2812; // Quintuple Deduction
    float STd = 13.1562; // Sextuple Deduction

    float HL; // Hight multiplied by Length

    system("cls");

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Width of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> W;

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Hight of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> H;

    HL = W*H;

    system("cls");

    std::cout << "*---------------------------------------------------------
----
---------------------------------------*\n\n";
    std::cout << "Is this Shutter a . . ." << "\n" << "Single (1), Double
(2),"
<< "\n" << "Triple (3), Quadruple (4)," << "\n" << "Quintuple (5), or
Sextuple
(6): ";
        std::cin >> SN;

    switch (SN)
    {
        case 1: Sl = W - Sd;
        break;

        case 2: Sl = W - Dd;
        break;

        case 3: Sl = W - Td;
        break;

        case 4: Sl = W - Qd;
        break;

        case 5: Sl = W - QTd;
        break;

        case 6: Sl = W - STd;
        break;

        default: Sl = W - Sd;
    }

    SL = Sl / SN;

    std::cout << "\n\nWith a Width of [" << W <<"] and a Hight of [" << H <<
"]";
    std::cout << " the Bahama/Colonial Shutters'. . .";

    std::cout << "\n\nSide Slide: ";
        std::cout << W - 3.3125;

    std::cout << "\n\nSide Rails: ";
        std::cout << H - 3.7187;

    std::cout << "\n\nLouver Size: ";
        std::cout << SL;

    // std::cout << "\n\nNumber of Louvers: ";
       // std::cout << NP;

    std::cout << "\n\n*-----------------------------------------------------
----
-------------------------------------------*\n\n\n";

    std::cout << "Would you like to measure out another Bahama/Colonial
shutter?";
    std::cout << "(1 = Yes)(2 = Main Menu)(0 = Quit): ";
        std::cin >> Token;

    switch (Token)
    {
    case 2: DisplayMenu();

    case 0: Token = 200;
    }

    } while (Token == 1);

}

int StormPanel()
{
    std::cout << "Storm Panel!";

    return 0;

}

int main()
{
    DisplayMenu();

    return 0;
}

A: You can control Excel via OLE Automation.
https://support.microsoft.com/en-us/help/216686/how-to-automate-excel-from-c-without-using-mfc-or-import


text:
Q: A minimal eigenvalue inequality Suppose $A$ is an $n\times n$ real symmetric positive definite matrix. Let $A^{(-1)}_{i,j}$ be the $n\times n$ matrix the entries $(i,i),\,(i,j),\,(j,i),\,(j,j)$ of which equal to the corresponding entries of the inverse of the row $i$ column $j$ principal minor of $A$, and all other entries zero. Let me put the verbal defintion in the last sentence into more sepcific terms. Let $a_{ij}$ be the $(i,j)$ entry of $A$. Let $C_{i,j}$ be the $2\times2$ matrix $C_{i,j} :=\begin{bmatrix}a_{ii} & a_{ij} \\ a_{ij} & a_{jj}\end{bmatrix}$, which is the row $i$ column $j$ principal minor of $A$. Let $\big[C_{i,j}^{-1}\big]_{kl},\,k,l\in\{1,2\}$ be the $(k,l)$ entry of the inverse of $C_{i,j}$. Then the $(p,q), \,p,q\in\{1,2,\cdots,n\}$ entry of $A^{(-1)}_{i,j}$ is then $$\big[A_{i,j}^{(-1)}\big]_{pq} :=[C_{i,j}^{-1}]_{11}\delta_{ip}\delta_{iq}+[C_{i,j}^{-1}]_{12}(\delta_{ip}\delta_{jq}+\delta_{iq}\delta_{jp})+[C_{i,j}^{-1}]_{22}\delta_{jp}\delta_{jq}.$$
Now we are clear about what exactly $A_{i,j}^{(-1)}$ is, define
$$B:=\frac{1}{n-1}\sum_{i<j}A_{i,j}^{(-1)},\quad P:=\big(\text{diag}(A)\big)^{-1},$$
and $\lambda_{\min}(M)$ to be the minimal eigenvalue of matrix $M$ (with all real eigenvalues).
Random test suggests the following inequality. Is it true in general?
$$\lambda_{\min}(PA)\le \lambda_{\min}(BA)$$

It is true for $n=2$.

This is an equivalent and simplified reformulation of a problem in math.exchange.com.


text:
Q: Android - streaming sensor data continuously? I have the following code giving me some sensor data:
private void computeOrientation() {
        if (SensorManager.getRotationMatrix(m_rotationMatrix, null, m_lastAccels, m_lastMagFields)) {
            SensorManager.getOrientation(m_rotationMatrix, m_orientation);

            /* 1 radian = 57.2957795 degrees */
            /*
             * [0] : yaw, rotation around z axis [1] : pitch, rotation around x
             * axis [2] : roll, rotation around y axis
             */
            float yaw = m_orientation[0] * 57.2957795f;
            float pitch = m_orientation[1] * 57.2957795f;
            float roll = m_orientation[2] * 57.2957795f;

            /* append returns an average of the last 10 values */
            m_lastYaw = m_filters[0].append(yaw);
            m_lastPitch = m_filters[1].append(pitch);
            m_lastRoll = m_filters[2].append(roll);

            yawText.setText("azi z: " + m_lastYaw);
            pitchText.setText("pitch x: " + m_lastPitch);
            rollText.setText("roll y: " + m_lastRoll);

                    //Now I want to send those 3 values over the network
                    //whenever they're calculated
}

This function will be invoked every few milliseconds I reckon, from onSensorChanged(SensorEvent event).
I want to continually send/stream this data over internet network to a remote device, that will be using the data stream to calculate things in real time.
How should I do this? Through sockets? An AsyncTask? Example source code for getting started would be much appreciated =)

A: This is a job for a Service to calculate the data in background. Because no UI is necessary you can use a Thread insteed of an AsyncTask to get the sensor data.
There is more detail needed in general, but especially for the setup of the connection between your phone and the remote device. If you use a LAN, sockets in combination with a ByteArrayriter on the Phone and a ByteArrayReader on the device should do the job.


text:
Q: vscode - explorer file view filter section how to make always open
I see this photo then I think when I try to search in explorer it happens like that

when I search some files occasionally stay behind to filter section so I want to import always like the first photo like that.
how I can do that?


text:
Q: Multiply value of input and print I have multiple inputs. These are multiplied and the result is checked wether it is higher or lower than certain values. This result shall be printed with an alert. It is just the first step, therefore I have an alert for me, so I can assure myself, that the result is correct.
The Input

   <input class=".someClass" type="text" id="input-q1a" />
   Some text

Jquery
var $htA = parseFloat($("#input-q1a").val(), 10);
var $avisA = ($htA *2);
var $euA = 0;
var $gaA = ($htA *3);

function exposeumfang() {
    if ($gaA <= 8) {
        $euA = 20;
    }  if ($gaA > 8 && $gaA <= 12) {
        $euA = 24;
    }  if ($gaA > 12 && $gaA <= 16) {
        $euA = 28;
    }  if ($gaA > 16 && $gaA <= 20) {
        $euA = 32;
    }  if ( $gaA >20 && $gaA <= 24) {
        $euA = 36;
    }  if ($gaA > 24 && $gaA <= 28) {
        $euA = 40;
    }  if ($gaA >28) {
        $euA = 44;
    }
    }
someButton.on('click', function(){
        alert('Some text ' + exposeumfang() + ' more text ' + $avisA + ' last bit of text.');
        });

I only get undefined and NaN for the two variables in the alert. I can't get a hold of this problem... :/
What am I doing wrong?

A: You parse the value of an empty input and get NaN. You should parse the value on button click. I changed your code to display the alert on 'Some text' click:

   <input class=".someClass" type="text" id="input-q1a" />
   Some text

Javascript:
var $htA = parseFloat($("#input-q1a").val() != '' ? $("#input-q1a").val() : 0, 10);
var $avisA = ($htA * 2);
var $euA = 0;
var $gaA = ($htA * 3);

function exposeumfang() {
  $htA = parseFloat($("#input-q1a").val() != '' ? $("#input-q1a").val() : 0, 10);
  $avisA = ($htA * 2);
  $gaA = ($htA * 3);
  if ($gaA <= 8) {
    $euA = 20;
  }
  if ($gaA > 8 && $gaA <= 12) {
    $euA = 24;
  }
  if ($gaA > 12 && $gaA <= 16) {
    $euA = 28;
  }
  if ($gaA > 16 && $gaA <= 20) {
    $euA = 32;
  }
  if ($gaA > 20 && $gaA <= 24) {
    $euA = 36;
  }
  if ($gaA > 24 && $gaA <= 28) {
    $euA = 40;
  }
  if ($gaA > 28) {
    $euA = 44;
  }
}

$("label>span").on('click', function() {
  exposeumfang()
  alert('Some text ' + $euA + ' more text ' + $avisA + ' last bit of text.');
});

WORKING FIDDLE

EDIT
I also modified the $htA variable to check if the input value is not empty. If it was empty, parseFloat(...) returned NaN.
This check is a one line 'if-else' (or more specifically a ternary operation) statement:
$("#input-q1a").val() != '' ? $("#input-q1a").val() : 0

If the input value is not empty, it passes the value to parseFloat function, and when it's empty it passes 0.
It could be modified to not call parseFloat function if it's empty:
var $htA = $("#input-q1a").val() != '' ? parseFloat($("#input-q1a").val(), 10) : 0;

A: Try this:

   <input class=".someClass" type="text" id="input-q1a" />
   Some text
   <button id = "someButton" >Submit</button>

A: Add a return in every if statement.
var $htA = parseFloat($(".input-q1a").val(), 10);
var $avisA = ($htA * 2);
var $euA = 0;
var $gaA = ($htA * 3);

function exposeumfang() {
  if ($gaA <= 8) {
    return $euA = 20;
  }
  if ($gaA > 8 && $gaA <= 12) {
    return $euA = 24;
  }
  if ($gaA > 12 && $gaA <= 16) {
    return $euA = 28;
  }
  if ($gaA > 16 && $gaA <= 20) {
    return $euA = 32;
  }
  if ($gaA > 20 && $gaA <= 24) {
    return $euA = 36;
  }
  if ($gaA > 24 && $gaA <= 28) {
    return $euA = 40;
  }
  if ($gaA > 28) {
    return $euA = 44;
  }
}
$("button").on('click', function() {
  alert('Some text ' + exposeumfang() + ' more text ' + $avisA + ' last bit of text.');
});


text:
Q: Create direct file object in python I have images in 100 folders and the search results are slow, so I want to access those images, so maybe I wanna do it with python(if it is faster), in the way that when we select all the files, and drag and drop them in windows. then I realized that drag and drop in windows uses Component Object Model this source.
So I want to know is there any way in python to have COMs of the image files in those 100 folders in the same place (a specific folder)? or in other words can we create COMs of other files, (equivalent of shortcuts), cause I know shortcuts for my purpose won't work.
The question in general is about how to access direct handles or COMs of files of different folders in one folder? if it's possible, please tell me how? to be simpler I want to have similar function of file shortcuts but not 'shortcuts' existing in windows, because for my purpose 'shortcuts' won't work, so I think it can be done with COMs.
tkinter equivalent question:
let me ask my question in other way, lets think I want to make a windows file search application in python with some library like tkinter, so one background part of my code finds the file paths of desired search results, and other part in gui('gui part'): wants to show the result files with ability of opening files from that gui or drag files from gui to other folder or applications, so how should I do the 'gui part'?
this tutorial suggested by @Thingamabobs is about getting external files into window(gui) of app, but I want the opposite, I mean having file handles to open, something like windows explorer
My question maybe wrong in case of misunderstanding the concept of COMs, so please provide me more relevant sources of use case of mine. finally if the title seems to be unsuitable, feel free to change it.

A: Based on an interpretation of the question, the following is an initial summary approach to a solution.
"""
This module will enable easy access to files spread across 100 plus
directories. A file should be as easy to open as clicking on a link.

Analysis:
Will any files be duplicated in any other directory? Do not know.
Will any file name be the same as another file in a different directory? Do
not know.

Initial design in pseudocode:
> Capture absolute path to each file in each directory.
> Store files information in python data structure
    > for instance a list of tuples <path>,<filename>
> Once a data structure is determined use Tkinter, ttk.treeview to open a
file as easy as clicking on a link in the tree.
"""


text:
Q: (py)spark weighted average taking account of missing values Is there a canonical way to compute the weighted average in pyspark ignoring missing values in the denominator sum?
Take the following example:
# create data
data2 = [(1,1,1,1),
         (1,None,1,2),
         (2,1,1,1),
         (2,3,1,2),
  ]

schema = (StructType([
    StructField("group",IntegerType(),True),
    StructField("var1",IntegerType(),True),
    StructField("var2",IntegerType(),True),
    StructField("wght", IntegerType(), True),
  ]))

df = spark.createDataFrame(data=data2,schema=schema)
df.printSchema()
df.show(truncate=False)

+-----+----+----+----+
|group|var1|var2|wght|
+-----+----+----+----+
|1    |1   |1   |1   |
|1    |null|1   |2   |
|2    |1   |1   |1   |
|2    |3   |1   |2   |
+-----+----+----+----+

I can compute the weighted average as documented elsewhere:
(df.groupBy("group").agg(
     (F.sum(col("var1")*col("wght"))/F.sum("wght")).alias("wgtd_var1"),
     (F.sum(col("var2")*col("wght"))/F.sum("wght")).alias("wgtd_var2")).show(truncate=False))

+-----+------------------+---------+
|group|wgtd_var1         |wgtd_var2|
+-----+------------------+---------+
|1    |0.3333333333333333|1.0      |
|2    |2.3333333333333335|1.0      |
+-----+------------------+---------+

But the problem is that for group 1 the weigthed average should be one as the second observation sohuld not be used. I can
# get new weights
df = (df.withColumn("wghtvar1", F.when(col("var1").isNull(), None)
                                 .otherwise(col("wght")))
        .withColumn("wghtvar2", F.when(col("var2").isNull(), None)
                                 .otherwise(col("wght"))))

# compute correct weighted average
(df.groupBy("group").agg(
     (F.sum(col("var1")*col("wghtvar1"))/F.sum("wghtvar1")).alias("wgtd_var1"),
     (F.sum(col("var2")*col("wghtvar2"))/F.sum("wghtvar2")).alias("wgtd_var2")).show(truncate=False))

+-----+------------------+---------+
|group|wgtd_var1         |wgtd_var2|
+-----+------------------+---------+
|1    |1.0               |1.0      |
|2    |2.3333333333333335|1.0      |
+-----+------------------+---------+

Is there a canonical way to do this?

A: Not much difference but at least this can save you from creating new wght column per variable.
Conditional aggregation.
df = (df.groupby('group')
      .agg(
          (F.sum(F.when(F.col('var1').isNotNull(), F.col('var1') * F.col('wght')))
           /
          (F.sum(F.when(F.col('var1').isNotNull(), F.col('wght'))))
          ).alias('wgtd_var1')
      ))

For applying this to multiple var, I can use list comprehension.
df = (df.groupby('group')
      .agg(*[
          (F.sum(F.when(F.col(x).isNotNull(), F.col(x) * F.col('wght')))
           /
          (F.sum(F.when(F.col(x).isNotNull(), F.col('wght'))))
          ).alias(f'wgtd_{x}')
          for x in ['var1', 'var2']
      ]))


text:
Q: Implementing Minecraft Banner Text Parsing This is a complex question, so I apologize in advance. Believe it or not, this is for an assignment in a college-level class.
I am trying to implement a lexer in Minecraft that interprets different types of number-looking banners. The functionality I am looking to achieve is very similar to SethBling's Scrabble Spell Checker. Essentially, when a number of various banners are placed, some series of command blocks are triggered.
So let's say I want to interpret these banners and set a scoreboard objective to be 149:

Here's my understanding of how this functionality works:

*

*There is a dummy scoreboard object configured to act a counter

*A command block would spawn in an armour stand to the far right of the banners and it could step the armour stand to the left 1 block after every iteration using relative coordinates

*At each "step", the armour stand would have to issue a testfor command and then, depending on the result, would have to add that respective value to the scoreboard

Step 3. is the heart of my question. In SethBling's example he uses this command:
/execute @e[type=ArmorStand,name=Lexer] ~ ~ ~ /testforblock ~ ~ ~ wall_banner -1 {Patterns:[{Pattern:"ls",Color:0},{Pattern:"bs",Color:0},{Pattern:"bo",Color:15}]}

Where it's clear the banner type is being identified. But I'm not sure how it is possible to do anything with this result.
Am I on the right track with this logic? How can I use the result from the testfor command issued by the armour stand?
Once I figure out the value of the banner, how can I add this result to the relative total (ie. 9 + 40 + 100), since I can't perform mathematical operations inside the command block?
I know this question involves a lot of complex command block logic. Thanks so much for your help!

A: You can use the /stats or check the CommandStats datatag of the ArmorStand. I highly recommend use of the /stats command.
Extract the result:
Run these commands once
Note: Anything suffixed with a "_v" can be whatever you want, as long as they're consistent.
/scoreboard objectives add SuccessCount_v dummy
/stats entity @e[type=ArmorStand,name=Lexer] set SuccessCount @e[type=ArmorStand,name=Lexer] SuccessCount_v

This will store the SuccessCount (in case of this command, 0 or 1) in the scoreboard as @e[type=ArmorStand,name=Lexer] SuccessCount_v, which you can then test and use as you would any other scoreboard value.
Add results together:
I'm not going to go into detail here, since I am unsure exactly you want to add together. I will, however link you to a wiki page where you can find the format of /scoreboard players operation <selector> <objective> <operator> <selector2> <objective2>, the only method for doing math in command blocks. (Yes, there is a command dedicated to it. It is not impossible.)
Hope this helps and wish you luck!

A: The new syntax for /execute in 1.13 makes chaining commands like this very easy:
/execute positioned as @e[type=armor_stand,name=Lexer] if block ~ ~ ~ minecraft:wall_banner{Patterns:[{Pattern:"ls",Color:0},{Pattern:"bs",Color:0},{Pattern:"bo",Color:15}]} run <command>

Where <command> can be replaced with any command, without the leading slash that is usually present.


text:
Q: Javascript lodash - data massaging based on attribute value I have an array of objects, such as this:
var elements = [
{
    LabCode: 'VA',
    Zscore: 0.5,
    Standard: 'std1'
},

{
    LabCode: 'RE',
    Zscore: 0.53,
    Standard: 'std1'
},
{
    LabCode: 'VO',
    Zscore: 1.5,
    Standard: 'std1'
},
{
    LabCode: 'VA',
    Zscore: 3.4,
    Standard: 'std2'
},
{
    LabCode: 'RE',
    Zscore: 2.45,
    Standard: 'std2'
},
{
    LabCode: 'VO',
    Zscore: 1.67,
    Standard: 'std2'
}
]

What I need is this:
var result = [
{
Standard: 'std1',
VA: 0.5,
RE: 0.53,
VO: 1.5
},

{
Standard: 'std2',
VA: 3.4,
RE: 2.45,
VO: 1.67
}
]

Labcodes are dynamic so I need to be able  to dynamically creates the resulted object. I can have many standards and they are also dynamic.
I am using lodash.
Please note that the property name needs to reflect the fact that labcodes are dynamic as well. This was not addressed in the answer you notes as duplicate.

A: You can do it simply with reduce() like this

var elements = [
                {LabCode: 'VA',Zscore: 0.5, Standard: 'std1' },
                {LabCode: 'RE',Zscore: 0.53,Standard: 'std1' },
                {LabCode: 'VO',Zscore: 1.5, Standard: 'std1' },
                {LabCode: 'VA',Zscore: 3.4, Standard: 'std2' },
                {LabCode: 'RE',Zscore: 2.45,Standard: 'std2' },
                {LabCode: 'VO',Zscore: 1.67,Standard: 'std2' }
               ]

let final = Object.values(elements.reduce((op,cur)=>{
  if( op[cur['Standard']] ) {
    op[cur['Standard']][cur['LabCode']] = cur['Zscore']
  } else {
    op[cur['Standard']] = {
     'Standard' : cur['Standard'],
     [cur['LabCode']]: cur['Zscore']
    }
  }
  return op;
}, {} ))

console.log(final);

Well in case of IE you can use this.

var elements = [
                    {LabCode: 'VA',Zscore: 0.5, Standard: 'std1' },
                    {LabCode: 'RE',Zscore: 0.53,Standard: 'std1' },
                    {LabCode: 'VO',Zscore: 1.5, Standard: 'std1' },
                    {LabCode: 'VA',Zscore: 3.4, Standard: 'std2' },
                    {LabCode: 'RE',Zscore: 2.45,Standard: 'std2' },
                    {LabCode: 'VO',Zscore: 1.67,Standard: 'std2' }
                   ]

    let final = elements.reduce((op,cur)=>{
      if( op[cur['Standard']] ) {
        op[cur['Standard']][cur['LabCode']] = cur['Zscore']
      } else {
        op[cur['Standard']] = {
         'Standard' : cur['Standard'],
         [cur['LabCode']]: cur['Zscore']
        }
      }
      return op;
    }, {} )
let finalop = [];
for(let key in final){
  finalop.push(final[key])
}
    console.log(finalop);

A: You can get this done via one Array.reduce and some ES6 (without lodash):

var data = [{ LabCode: 'VA', Zscore: 0.5, Standard: 'std1' }, { LabCode: 'RE', Zscore: 0.53, Standard: 'std1' }, { LabCode: 'VO', Zscore: 1.5, Standard: 'std1' }, { LabCode: 'VA', Zscore: 3.4, Standard: 'std2' }, { LabCode: 'RE', Zscore: 2.45, Standard: 'std2' }, { LabCode: 'VO', Zscore: 1.67, Standard: 'std2' } ]

const result = data.reduce((r, {LabCode, Zscore, Standard}, i, a) => {
  r[Standard] = r[Standard] || {}
  r[Standard][LabCode] = Zscore
  return i == a.length-1 ? Object.keys(r).map(k => ({Standard: k, ...r[k]})) : r
}, {})

console.log(result)


text:
Q: USING DAX: How can I get output that are not blank from COMBINEVALUES()? I have several nested IF statements in a COMBINEVALUES(), everything works but I am trying to remove ",,,VALUE,VALUE" the occurrences of blank comma separations so it displays as "VALUE,VALUE".
Any suggestions?
COMBINEVALUES(",",IF(,"","VALUE"),IF(,"VALUE",""))

is the general example of the code, but is there a way in DAX/M code to do this?


text: Q: Book recommendations to understand General Relativity I just finished Multivariate calculus and I am wondering what sequence of books would allow me to work up to the mathematical knowledge needed to understand General Relativity and the corresponding field equations?


text:
Q: How to get library of devise so that it can be modified like php libraries Getting the generated devise controller like.
class Users::SessionsController < Devise::SessionsController
   before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
   def new
    # super
        #       byebug
        redirect_to  root_url
   end

  # POST /resource/sign_in
   def create
        puts 'Login user............'
        super
        puts '..............'

   end

  # DELETE /resource/sign_out
   def destroy
     super
   end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
   def configure_sign_in_params
     devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
   end
end

where can I get the library of devise so that I can modify it new function and do not get error of double redirect.
suppose in terminal logs out put is as Processing by
Users::SessionsController#new as HTML

where is the code written for method new in its devise library.

A: If I get what you mean
In the devise model you have to make something like this
   before_create :welcome_alert
   before_create :confirm_email
   after_save :subscribe_user_to_mailing_list

def welcome_alert
    alert = ("signed_up_but_unconfirmed")
  end

  def confirm_email
    UserMailer.registration_confirmation(self).deliver
  end

Is this what you want!


text:
Q: The most elementary proof of divisibility of sum of powers I am wondering how one can prove that for an arbitrary odd natural number $n$ and an arbitrary natural number $a$ the power-sum $S_{(a,n)}=1^n+2^n+\ldots +a^n $ is divisible by $S_{(a,1)}=1+2+\ldots + a$ in the most elementary way (possible) which comes to your mind. By an elementary way I mean the way which even middle school student could follow.
I traditionally tried to compute $S_{(a,n)}$ using the expansion of $(x-1)^{n+1}=\sum_{k=0}^{n+1}(-1)^k\binom{n+1}{k}x^{n+1-k}$.
I substituted $x=1,2,3,\ldots , a$ and then summed up results. After telescoping and cancelations I received $a^{n+1}=\sum_{k=1}^{n+1}(-1)^{k+1}\binom{n+1}{k}S_{(a,n+1-k)}$, from which we can express $S_{(a,n)}$.
Nevertheless this approach seems to me tough and not so easy to follow for a middle school student; A loads of technical re-writing and quite long symbolic computations needed to go through.
My question: I am missing something very evident and elegant which gives the desired divisibility without tears?

A: Note that $r^n+(P-r)^n$ is divisible by $P$ by Binomial expansion and cancelling of the only terms without factors of $P$ (as $n$ is odd). If $a$ is odd, then all the terms in $S_{(a,n)}$ pair up in this way, with $P=a$, except for $a^n$, which is certainly a multiple of $a$, so $S_{(a,n)}$ is a multiple of $a$. If $a$ is even, then all the terms in $S_{(a,n)}$ pair up in this way, except for $a^n$ and $\Big(\dfrac{a}{2}\Big)^n$, so so $S_{(a,n)}$ is a multiple of $\dfrac{a}{2}$. We can make exactly the same argument with $P=a+1$, except that, if $a$ is odd, we find $S_{(a,n)}$ is a multiple of $\dfrac{a+1}{2}$ and if $a$ is even, $S_{(a,n)}$ is a multiple of $a+1$. Hence $S_{(a,n)}$ is always a multiple of $\dfrac{a(a+1)}{2}=S_{(a,1)}$.
Illustrative examples.
$1^n+2^n+3^n+4^n+5^n=(1^n+4^n)+(2^n+3^n) + 5^n$, so divisible by 5; also $1^n+2^n+3^n+4^n+5^n=(1^n+5^n)+(2^n+4^n) + 3^n$, so divisible by 3.
$1^n+2^n+3^n+4^n+5^n+6^n=(1^n+5^n)+(2^n+4^n) + 3^n +6^n$, so divisible by 3; also $1^n+2^n+3^n+4^n+5^n+6^n=(1^n+6^n)+(2^n+5^n) + (3^n+4^n)$, so divisible by 7.

A: I liked your approach by using binomial expansion.
Here is my approach using induction...
The base cases are obviously true.
Suppose $k$ is an odd natural number such that $S_{(a, 1)} \mid S_{(a, n)}$ for all odd $n\leq k-2$.
Observe that
$$(p+1)^k+(p-1)^k=2 \sum_{m=0}^{\frac{k-1}{2}}\binom{k}{2m}p^{k-2m}$$
$$\therefore \sum_{p=1}^{a}[(p+1)^k+(p-1)^k]$$
$$=2\sum_{m=0}^{\frac{k-1}{2}}\binom{k}{2m}(1^{k-2m}+2^{k-2m}+...+a^{k-2m})$$
$$=2\sum_{m=0}^{\frac{k-1}{2}}\binom{k}{2m} S_{(a, k-2m) }$$
Now notice that,
$(p+1)^k+(p-1)^k$ is divisible by $(p+1)+(p-1)=2p$ as $k$ is odd.
$$\therefore \sum_{p=1}^{a}2p\, {\huge \mid} 2\sum_{m=0}^{\frac{k-1}{2}}\binom{k}{2m} S_{(a, k-2m)}=2S_{(a, k) }+2\sum_{m=1}^{\frac{k-1}{2}}\binom{k}{2m}S_{(a,\,k-2m)}$$
$$\implies\sum_{p=1}^{a}p\, {\huge \mid}\,  S_{(a,\, k) }+\sum_{m=1}^{\frac{k-1}{2}}\binom{k}{2m}S_{(a,\,k-2m)}$$
$$\implies S_{(a, \,1)}\,{\huge \mid}\,S_{(a,\, k) }+\sum_{m=1}^{\frac{k-1}{2}}\binom{k}{2m}S_{(a,\,k-2m)} $$
$$\implies S_{(a, \,1)}\,{\huge \mid}\,S_{(a,\, k) }$$
$$[\because S_{(a, \,1)} \,\text{divides}\,S_{(a,\,k-2m)}\,\text{for all}\, 1\leq m\leq \frac{k-1}{2}]$$
Hence, by the principle of mathematical induction, we can conclude that $S_{(a, \, k) }$ is divisible by $S_{(a, \, 1) }$ for all odd $k$.


text:
Q: Design page with static HTML or static DOM Javascript? today I've a question. Is faster to load a web page designed from static html example:

      <title>Web page</title>

Hi community

Or by static Javascript with DOM? Example with document.createElement("...")

A: Serving the HTML directly would be the faster approach, as your browser only have to render the elements, and not manipulate the dom :)

A: Populating HTML statistically is much faster than populating through javascript.

*

*The HTML document gets downloaded

*The parsing of the HTML document starts

*HTML Parsing reaches

*Internal Javascript is parsed and run

*HTML Parsing reaches <img src="abc.jpg" ...

*xyz.jpg is downloaded and displayed

*Parsing of HTML document ends
So, if you have static html loading with javascript will be overhead for page rendering.

A: It's faster to send a static html, because the client doesn't have to execute js. Sending complete HTML is also better for search engines, even if google can now execute js.
You can still use js to add elements in your DOM once the page is loaded

A: Like others said, it is always faster to output static HTML rather than generating it dynamically using Javascript/JQuery. However, sometimes the content cannot be served directly and generating the HTML dynamically is the only choice. I have worked on a few applications where this was the case. In general, generate static HTML whenever you can.


text:
Q: Android SQLite Join Query I'm creating an app as a learning tool and am having difficulty with join queries.
I have a database with two tables- horses and covers- declared as follows;
    private static final String HORSES_CREATE = "create table horses (_id integer primary key autoincrement, "
        + "name text not null, type integer not null, birthDate text not null, vaccineDate text not null, "
        + "inFoal integer not null, notes text not null);";

The 'type' field refers to stallion, mare, gelding etc and is selected from a spinner (populated from an XML String array).
private static final String COVERS_CREATE = "create table covers (_id integer primary key autoincrement, "
        + "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
        + "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null);";

stallionName is actually stored as the _id field of the horse from the horse table. It is selected from a spinner that only displays horses whose type defined as 'Stallion' in the horses table. (The same applies for Mare).
I have a class 'DatabaseHelper' to create and upgrade the tables, and each table has its own adapter class 'horsesDbAdapter' and 'coversDbAdapter' that contains the methods to add, edit and delete entries, and relevant queries. (fetchAllHorses(), fetchHorse(long rowId) )
eg:
    public Cursor fetchAllHorses() {

    return mDb.query(DATABASE_TABLE,
            new String[] { KEY_ROWID, KEY_NAME, KEY_TYPE, KEY_BIRTHDATE,
                    KEY_VACCINEDATE, KEY_INFOAL, KEY_NOTES }, null, null,
            null, null, null);
}

(It's all adapted from the Android notepad example)
I have the contents of the covers table displayed in a listview (just showing the stallionName and mareName). But as those fields just contain the unique reference to the horses table all that is displayed is the fairly uninformative _id field.
My question is; how can I get the relevant name for the horses to display in the listView? I've read up on join queries etc but get lost when I try implement them. I assume I have to join on horses._id and covers.stallionName (then make an almost-identical one for MareName) but I can't find a concrete example of how to do this.
Please let me know if any additional information/ code is needed.
Any help would be greatly appreciated, thankyou in advance.
EDIT:
I have made stallionName and mareName foreign keys referencing (_id) in the horses table, but am still unsure how and where to implement the join query; should it be in the horsesDbAdapter, coversDbAdapter or the coversList class? (coversList is the class that creates and populates the listView)
The covers table declaration now reads;
    private static final String COVERS_CREATE = "create table covers (_id integer primary key autoincrement, "
        + "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
        + "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null," +
        "FOREIGN KEY (stallionName) REFERENCES horses (_id), FOREIGN KEY (mareName) REFERENCES horses (_id));";

A: I'm a newbie to Android and SQLLiteHelper and was wondering about the same thing.
After reading this post, I found that the method to define joins between tables is done with the SQLLiteQueryBuilder.setTables method. See the reference here
I got this from this blog
Hope this helps pointing readers in the right direction.

A: I've managed to get it working. For anyone else who may have a similar problem I'll try detail what I did.
As @deceiver stated I should have made stallionName and mareName foreign keys referencing horses (see Edit).
In the coversList class (the class that implements the listView) I just needed to get an instance of the database and use a rawQuery to implement the SQL code directly (It may be possible to do it with Query but I'm not sure how)
The added code is as follows;
private Cursor coversCursor;
private void fillData() {

    db = (new DatabaseHelper(this).getReadableDatabase());
    coversCursor = db.rawQuery("SELECT horses1.name AS stallionNameText, covers.*, horses2.name AS mareNameText FROM horses horses1 JOIN covers ON horses1._id = covers.stallionName JOIN horses horses2 ON horses2._id = covers.MareName",
                    null);
    startManagingCursor(coversCursor);
    // Create an array to specify the fields we want to display in the list
    // (the renamed fields from the above query)
    String[] from = new String[] { "stallionNameText", "mareNameText" };

    // and an array of the fields we want to bind those fields to (in this
    // case just text1)
    int[] to = new int[] { R.id.rowStallionName, R.id.rowMareName };

    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter covers = new SimpleCursorAdapter(this,
            R.layout.covers_list_row, coversCursor, from, to);
    setListAdapter(covers);
}

FillData() is then called in the onCreate() method. Then just close the db in the onDestroy method.
(Selecting all columns from the covers table seems wasteful here but I will eventually show these columns in the listView aswell. I just wanted to answer this before continuing coding).
A tutorial I found helpful was http://coenraets.org/blog/android-samples/androidtutorial/
I had issues with the SQL query as there are 2 foreign keys referencing the same table and I wanted the listView to display both the stallion name and mare name, so had to join two horses table to a covers table. I just needed to rename the tables in the FROM section of the SQL query. Hopefully the above code is clear. If not, I found the following useful; http://www.bryantwebconsulting.com/blog/index.cfm/2005/3/11/join_a_table_to_itself_in_sql
Sorry if this explanation is too specific to my (unusual) example.
Thanks for reading.


text:
Q: Preloading images with javascript does not work I'm trying to preload images with javascript:
$(document).ready(function () {
    preloadImages(
        ['../../Content/Resources/close_mouse_over.png',
        '../../Content/Resources/close.png']);
});

function preloadImages(sources) {
        var image = new Array();
        for (var i = 0; i < sources.length; i++) {
            image[i] = new Image();
            image[i].src = sources[i];
        }
    }

function mouseOverForImage(imgId, imgSrcs) {
        document.getElementById(imgId).src = imgSrcs;
    }

In Html:
<input type="image" src="../../Content/Resources/close.png" name="Action" value="Save" onmouseover="mouseOverForImage('close', '../../Content/Resources/close_mouse_over.png')"
               onmouseout = "mouseOverForImage('close', '../../Content/Resources/close.png')" id="close" title = "Close" />

But request is still sending to server after mouseover. Is not working only in chrome

A: As noted within my comment, you are passing an array of arrays to the preLoadImages method.
As a result, you are passing an array to image[i].src which means it won't get loaded.
Try
$(document).ready(function () {
    preloadImages(
        ['../../Content/Resources/close_mouse_over.png', '../../Content/Resources/close.png']);
});

function preloadImages(sources) {
        var image = new Array();
        for (var i = 0; i < sources.length; i++) {
            image[i] = new Image();
            image[i].src = sources[i];
        }
    }

function mouseOverForImage(imgId, imgSrcs) {
        document.getElementById(imgId).src = imgSrcs;
    }

or, if you want to keep the array of array's, then use
function preloadImages(sources) {
        var image = new Array();
        for (var i = 0; i < sources.length; i++) {
            image[i] = new Image();
            image[i].src = sources[i][0];
        }
    }

Edit, on further investigation, a possible cause is preloadImages destroys the image array after preloading the images.
try this instead:
function preloadImages(sources) {
    window.preloadedImages = new Array();
    for (var i = 0; i < sources.length; i++) {
        window.preloadedImages[i] = new Image();
        window.preloadedImages[i].src = sources[i];
    }
}

This stores the preloaded images within the window object, allowing them to preload properly.
Hope that helps?


text:
Q: AngularJS Cannot show authentication status I am very new to AngularJS so apologies first!
I have an Angular app uses a REST API on the back-end to log users in/out
However I am trying to show the user's logged in status on the Angular front-end but not having much success.
My users are logged in and out using "authService.js":
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {

    // dec the home of the API
    var serviceBase = '<domain>' // remember to change this to the current domain that the API is being hosted!
    var authServiceFactory = {};

    // Local Authentication Data
    var _authentication = {
        isAuth: false,
        userName: ""
    };

    // Attempt to log in the user here
    var _login = function (loginData) {
        // This will be the body data of the login requesst
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
        var deferred = $q.defer(); // This gets the async data (AngularJS Call)

        // Send a post request to the /token endpoint to request a login
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(
            function (response) {
                // If the response was a 200 Success, then the user can be logged in locally
                // Store the auth token
                localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });
                // set local client data
                _authentication.isAuth = true;
                _authentication.userName = loginData.userName;
                // Return the promise
                deferred.resolve(response);
            }).error(function (err, status) {
                // Response from the HTTP was bad, i.e. not 200
                // flush the user and reject thee promise
                _logOut();
                deferred.reject(err);
            });
        return deferred.promise; // return the promise
    };

    // Remove the token from local storage
    var _logOut = function () {
        localStorageService.remove('authorizationData');
        _authentication.isAuth = false;
        _authentication.userName = "";
    };

    // This is run at start. Tries to get the autherizationData and if it is there then
    // the user is considered logged in
    var _fillAuthData = function () {
        var authData = localStorageService.get('authorizationData');
        if (authData) {
            _authentication.isAuth = true;
            _authentication.userName = authData.userName;
        }
    }

    // Assign all the attributs of the service facotry
    authServiceFactory.saveRegistration = _saveRegistration;
    authServiceFactory.login = _login;
    authServiceFactory.logOut = _logOut;
    authServiceFactory.fillAuthData = _fillAuthData;
    authServiceFactory.authentication = _authentication;

    console.log("Auth at end of factory:");
    console.log(_authentication.isAuth);

    // Return this object
    return authServiceFactory;
}]);

So, this factory should produce an object authServiceFactory. The authServiceFactory.authentication object is the data I require to present to the user, specifically .isAuth. From here I would be able to hide links, show the username to the user etc...
In my main App.js file I have:
var app = angular.module('AngularAuthApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar']);

app.config(function ($routeProvider) {

    // Declaire routes...
    $routeProvider.when("/home", {
        controller: "homeController",
        templateUrl: "/app/views/home.html"
    });

    $routeProvider.when("/login", {
        controller: "loginController",
        templateUrl: "/app/views/login.html"
    });

    $routeProvider.when("/signup", {
        controller: "signupController",
        templateUrl: "/app/views/signup.html"
    });

    // redirect the user if they try to access anything else
    $routeProvider.otherwise({ redirectTo: "/home" });
});

// On the app running run the authService to get auth data
app.run(['authService', function (authService) {
    authService.fillAuthData();
}]);

// Set the application config
// Any http request push it though the authInterceptorService
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
});

Notice app.run will collect the current authentication data from the factory.
And in my main single-paged HTML document I have:
<!DOCTYPE html>

    <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" />
    <link href="content/css/bootstrap.min.css" rel="stylesheet" />
    <link href="content/css/loading-bar.min.css" rel="stylesheet" />
    <link href="content/css/site.css" rel="stylesheet" />

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

Welcome {{authentication.userName}}

Logout

 Login

 Sign Up

 ...

My users can log in with no problem! and the status is changing which I found using the chrome debugger. However the I cannot reflect the results through the HTML. The list items are NOT being shown when a user loggs in. Adding {{authentication.isAuth}} to my html page shows nothing.
How can I hide/show the links, and represent visually that the user is currently logged in?

A: Have a $rootScope variable flag in your AuthFactory and update it after the successful login.
$rootScope.isAuthenticated = false; // Not authenticated
function login(){
    $http.post('RESTcalls').then(function(data){
        $rootScope.isAuthenticated = true; // Authenticated
    })
}


text:
Q: Is GLEW mandatory for an up-to-date OpenGL application? I've been reading on the gl.h header file included with my version of Visual Studio and it seems heavily outdated.
I do not want GLUT or any other middleware/utility library in between to do the dirty work for me, that includes GLEW. Could someone elaborate on why and how does one acquire/query for the modern feature set of the 4.0 specification and what's the idea behind GLEW in general?

A: Don't be afraid of GLEW. First, I've actually seen GLEW used in Nvidia OpenGL SDK examples. It's obviously a reliable tool with a friendly license. Second, you can statically link the library and vaporize it as a dependency. (Personally, I just add the source code to my project and #define GLEW_STATIC to make it work.)

A: The gl.h shipping with MSVC++ covers only the functions exported by the opengl32.dll shipping with Windows. This DLL is mostly only a so called "trampoline" into the actual driver. But it only exports a very old version of OpenGL, namely OpenGL-1.1.
Any functionality beyond that must be accessed through the extension mechanism.

I do not want GLUT or any other middleware/utility library in between to do the dirty work for me, that includes GLEW.

GLUT is completely unrelated to GLEW

Could someone elaborate on why and how does one acquire/query for the modern feature set of the 4.0 specification and what's the idea behind GLEW in general?

You aquire the modern feature set through the already mentioned extension system.
There is a function ?glGetProcAddress (exact name depending on the OS environment, in Windows wglGetProcAddress). Using this function you retrieve function pointers to the procedures of extensions for the current OpenGL context (in GLX the function pointers are the same for all contexts, but in Windows they may differ).
Loading a extension goes about this:
typedef (*OGLEXTP_SOMEEXTENSIONFUNCTION)(...)
OGLEXTP_SOMEEXTENSIONFUNCTION oglextp_glSomeExtensionFunction = NULL;
#define glSomeExtensionFunction oglextp_glSomeExtensionFunction;

struct Extensions
{
    bool SomeExtensionFunction;
}

errorcode initGLExtensions(){
    Extensions available;

    GLubyte extensions = glGetStrings(GL_EXTENSIONS);
    parse_extension_string(extensions, available);

    if( available.SomeExtensionFunction ) {
        oglextp_glSomeExtensionFunction = wglGwtProcAddress("glSomeExtensionFunction");
        if( !oglextp_glSomeExtensionFunction )
             return errorcode;
    }
}

And you have to write the bulk code of this for each and every function. Nobody wants to write this. So the developers of GLEW came up with a set of scripts, that fetch the extension specifications from opengl.org and automatically create the whole extension loading and wrap this into a small library, that creates no additional dependencies.
If you want to use higher OpenGL functionality: Use GLEW. Not because it's mandatory, but because it's the most straightforward way to go about this.

A: You want to access OpenGL 4.0 extensions right? You may need to create a OpenGL 4.0 context and ask GLEW to bind corresponding functions.
Here is a sample with GLEW and GLFW copied from my project.
  ...

  if (!glfwInit()) {
    exit(EXIT_FAILURE);
  }

  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2);   // I requested OpenGL 2.1 context
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);

  if(!glfwOpenWindow(640, 480, 8, 8, 8, 0, 24, 0, GLFW_WINDOW)) {  // get OpenGL context
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  if (glewInit() != GLEW_OK) {   // init glew, and bind gl* Extension functions
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  // now gl* extensions is available here

  ....

A: GLee is another library for loading OpenGL extensions, and it's pretty straightforward and easy to understand the source code (the code generator is a different story).  So you can see how loading extension functions works.

*

*Homepage: http://elf-stone.com/glee.php

*Description on OpenGL.org: http://www.opengl.org/sdk/libs/GLee/

*Description on Wikipedia: http://en.wikipedia.org/wiki/OpenGL_Easy_Extension_library
Do use the SVN trunk, not the "released" version, since I worked with the author to add support for the OpenGL 4.x extensions.
What I like about GLee is that it only loads the extensions you use, in contrast to GLEW which loads 200+ different extensions, which slows down program startup and especially slows down OpenGL profiling.


text:
Q: "Undefined type 'App'" in api.php Laravel I'm using Laravel 8.53 and Vuejs.
I want to set language for specific controller based on api parameter. (to send password reset email in desired language)
I have this route in api.php which works:
Route::post('forgot-password', [NewPasswordController::class, 'forgotPassword'])->name('password.reset');

Now I wanted to create something like this:
Route::post('forgot-password/{locale}', function ($locale) {App::setLocale($locale);}, [NewPasswordController::class, 'forgotPassword'])->name('password.reset');

Now when I send to /api/forgot-password/en I get 200 OK but no response.
My VS Code is showing me this error: Undefined type 'App'.
Do I need to define "App" in api.php? How?

A: I am not sure if it's correlated  but maybe the problem is in different place. You passing three parameters to post method. According to laravel docs you should pass only two. In this case you pass callback, or you pass controller path with method. Try to move App::setLocale() to your controller method and use your first syntax. Remember to import App facade before using it.
// api.php
Route::post('forgot-password', [NewPasswordController::class, 'forgotPassword'])->name('password.reset');

// NewPasswordController.php
use \App;

class NewPasswordController {
    public function forgotPassword( $locale ) {
         App::setLocale( $locale );

         /* rest of code */
    }
}


text:
Q: Expected value of 2nd-bigger number out of n independent random variables in uniform distribution [r,1], r>0 I am having a problem on which I have 4 players bidding in second price auction with reserved price (r). I need to find the expected value of 2nd bigger number when there are 3 players or 4 bidding over r, bid>r. For example, if 3 players bids over r, I need to find the expected value of the second bigger bid. So far I've found that when 2 players bids over r the expected value is equal to $a + (b-a)/3$  when we have uniform distribution in [a,b]. So in my example in [r,1] will be equal to $ r + (1-r)/3 $ I need the expected value of 2nd bigger value of n values. Haven't thought a way to do so. Found this but didn't help me Expected value of 2nd-smallest out of 3 random variables. Thanks in advance and sorry if my question is amateur.

A: I think the expected value of the second highest value in $n$ uniform random variables on $[a,b]$ is $a + (b-a)\frac{n-1}{n+1}$.
You can first consider $n$ uniform random variables on $[0,b-a]$, then the pdf of the second highest value is
$$f(x) = \frac{n!}{(n-2)!}(\frac{x}{b-a})^{n-2}(1-\frac{x}{b-a}),$$
which has mean value $(b-a)(\frac{n-1}{n+1})$.
Maybe you can see https://imgur.com/a/UFm12aK and Expected value of $2$nd highest draw from uniform dist out of n draws for detailed discussion.


text:
Q: Writing an array to a text file So I have this array, say it's
import numpy as np
m = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

and I want to write its dimension to a text file, and then I want to write the array itself below that.
I've already accomplished this somewhat with
with open(filepath, 'w') as f:
    n = len(m)
    f.write(str(n) + ' \n')
    np.savetxt(f, m)

The problem is that in the file the numbers are written as floats and I want them as they were given--as ints!  As far as I can tell savetxt() has no setting for this.
And I've tried switching from using savetxt() to using tofile() but this won't even write the array to a file, I assume because I've written something else to the file first and that's somehow messing with its operation.
I guess I could just write it by making a for loop, but that seems less ideal than just having a function out there waiting for me to use it, if that exists.

A: I don't know if this is what you are looking for, but it saves the array as it is, in this case the elements are all floats:
import numpy as np
m= np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

filepath = '/Path/to/file/'
fout = open(filepath + 'fout.dat', 'w')

# I'd use this if you want the full shape of the array
dimensions = np.shape(m)
print >>fout, str(dimensions) + ' \dimensions'
print >>fout, m

fout.close()

Hope this helps..


text:
Q: spring: return JSON from controller as ModelAndVIew How can I return JSON from spring controller as a view or ModelAndView? I am not interested in using @ResponseBody annotation. Is there any other way of doing this?

A: Yes, you can return a MappingJacksonJsonView or assign it to a ModelAndView object using mav.setView(new MappingJacksonJsonView()).
Update: In Spring 4 MappingJacksonJsonView is deprecated. You might want to upgrade to MappingJackson2JsonView

A: You can use org.codehaus.jackson.map.ObjectMapper class for writing json strings to output stream. Use the following code snippet in method of your controller:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(outputStream, model);
outputStream.flush();


text:
Q: Unable to fork: Cannot allocate memory frequently getting 'fork: Cannot allocate memory' when running commands over ssh. I have 64Gb of RAM and usually 1~2Gb free.
swap is more than 8gb free
Ubuntu version:"Ubuntu 12.04.2 LTS" Desktop 64 bit
free -m output:
   total       used       free     shared    buffers     cached

Mem:         64386      64079        307          0       9840      41196
-/+ buffers/cache:      13042      51343
Swap:         7720        347       7373
ulimit -a output :
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 514954
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 514954
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
Thanks


text:
Q: How can post and populate todos (no relational array) inside service? todos: no relational nested array. service: model's object I'm trying to insert one document called "service" from Collection "services". I want see todos inside service object, but I only see todo id. May you help me, please?
this is my code:
the schema:
const mongoose = require("mongoose");
const { Schema } = mongoose;

const serviceSchema = new Schema({
  name: String,
  description: String,
  pricePerHour: Number,
  todos: [
    {
      name: String,
      description: String,
      isDone: Boolean
    }
  ],
  createdAt: Date,
  updatedAt: Date
});

mongoose.model("services", serviceSchema);

that's my post services
app.post("/api/services", async (req, res) => {
  const { name, description, pricePerHour, todos } = req.body;

  const service = new Service({
    name,
    description,
    pricePerHour,
    todos: [
      {
        name: todos.name,
        description: todos.description,
        isDone: todos.isDone
      }
    ]
  });

  try {
    let newService = await service.save();

    res.status(201).send(newService);
  } catch (err) {
    if (err.name === "MongoError") {
      res.status(409).send(err.message);
    }

    res.status(500).send(err);
  }
});

As you see, I only see the todos id inside each service.
So, how can I post a service with no relational nested array and see every content from todos array inside each service object?

A: If your req.body structure is the same as Service model schema, you construct your service object in the post route like this:
  const service = new Service({
    name,
    description,
    pricePerHour,
    todos
  });

And your req.body must be like this to work:
{
  "name": "service 3",
  "description": "maintenance",
  "pricePerHour": 855,
  "todos": [{ "name": "todo 1", "description": "description 1", "isDone": true },
            { "name": "todo 2", "description": "description 2", "isDone": false}
  ]
}


text:
Q: Repeat HTML code with plain Javascript Is there a way to have html/javascript code to repeat html-code?
Basically, I need to use plain javascript and at the same time I need to build html elements in a for loop.
So in html I can have:

col1

col2>

col3

The problem is that there can be several sets of the above html code.
What I'm doing now is to write html inside the javascript code.
I would like to make it cleaner and have the html structure where it belongs, which is in the html-page.

A: You can try something along these lines:
for(i = 0;i<howeverManyYouNeed;i++)
{
    document.getElementById("parentId").innerHTML += "
col"+i+"
";
}

A: I would suggest you write your own minimal templating library if you're using ES-6 templates. See this blogpost on how to do that: http://www.2ality.com/2015/01/template-strings-html.html


text:
Q: Algorithm to determine how much and in what direction two rectangles are overlapping? Does anyone know of an algorithm that can be used to determine how much and in what direction two rectangles are overlapping? I have spent hours trying to figure this out so I can implement it into a basic tile game written in slick2d + java.

A: Poll the coordinates for the corners, and if Square1 has any corner between Square2's nearest and farthest vertices, they are in collision by the difference in coordinates?
Example:
square1.setVertex1(0,0);
square1.setVertex2(2,0);
square1.setVertex3(2,2);
square1.setVertex4(0,2);

square2.setVertex1(1,1);
square2.setVertex2(4,1);
square2.setVertex3(4,4);
square2.setVertex4(1,4);

Vertex[] verticesSq1=Square1.getVertices();
for (Vertex vert: verticesSq1) {
    if(vert.getXVal>square2.getLowestXVal() &&
       vert.getXVal<square2.getHighestXVal()

       &&
       vert.getYval>square2.getLowestYval() &&
       vert.getYVal<square2.getHighestYVal() {

            System.out.write("Vertex "+vert.ID+" is overlapping Square 2 by " +
            vert.getXval()-square2.getLowestXVal +","+
            vert.getYval()-square2.getLowestYVal);
    }
}

A: Let us represent each rectangle as R=(x1,x2,y1,y2) (i.e. (x1,y1), (x1,y2), (x2,y1), (x2,y2) are vertices of that rectangle, and x1

Now, we have two rectangles R1 and R2 and we want to know if they overlap and if yes, what direction.
For each vertex of R1 check if it is inside rectangle R2 which you can represent as 4 bits. The mapping is very direct:
0000 -> None (or R2 is inside R1)
0001 -> R2 is bottom right of R1
0010 -> R2 is top right of R1
0100 -> R2 is bottom left of R1
1000 -> R2 is top left of R1
0011 -> R2 is right of R1
0101 -> R2 is bottom of R1
1100 -> R2 is left of R1
1010 -> R2 is left of R1
1111 -> R1 is inside R2

Other combinations are impossible.

A: First make a center point between rectangles ( center of second rectangle - center of first one).
Check distance form every point of each rectangle to center point.
Pick 2 closest points, check if one of them is inside other rectangle, if yes, the  rectangle created by these two point gives us the overlapping area.


text:
Q: Japanese and european languages font list Where can I find a complete list of the fonts available for Ubuntu? I need in particular those for all European languages and Japanese.

A: I do not think such a list even exist! Fonts are invented or modifyed every second.
But don't let that stop you, just download the fonts you like and install, for that end use font-manager.
AFAIK. Ubuntu supports all kinds of fonts, I even have Futhark installed (Old Norce Runes).

A: There are fonts without end. A good place to look is Google Fonts or Free Japanese Fonts.
How to install fonts on Ubuntu, you can read here.
To simply load and install Google Fonts, you can use typecatcher.
sudo apt-get install typecatcher


text:
Q: User who voted a Q as dupe is missing from list of users in the review. & Weird Community edits Both my questions here are about the same Question in question, so kept them in this one Question (err..if that makes sense)
The relevant question:
How to refer to your blog when answering?
Question 1)
Just voted for the question to be marked as dupe.
On the question itself it's shown as marked dupe by:
Al E., cVplZ, doppelgreener, gnat, James
In the review area it shows the users as per above (plus one who voted Leave Open), except gnat who is not listed in the review area as having reviewed/voted on it.
What's the reason for this?
(Apart from gnat being a review ninja)
Question 2)
The revision history for that question shows it's changed a fair bit over time, however why has Community♦ seemingly fixed it's own fixes?
I get the first change, where it "migrated MSO links to MSE links" following the change over, but then twice it "Fixed bad MSO links to MSE links migration".
I can only surmise that it being done by a script, the changes from the first fix caused a change in condition so something else was done on the next pass over by the scripts..?
If so, shouldn't the title be different for each fix, or the scripts improved so it catches both issues in one pass over?
Maybe neither above options are possible, or necessary, I just wondered why and if there was perhaps some bug or oversight.

A: *

*Gnat voted on the post directly, not in the queue. As such he didn't review the votes, he just cast one.

*Shortly after the MSO-MSE split, the devs ran a script to migrate links from http://meta.stackoverflow.com to http://meta.stackexchange.com where appropriate, all over the Stack Exchange network. The first revisions of that script had problems so subsequent patchings-up were needed.
All changes made by the script are attributed to Community User.
See Should we unbugger the changes Community has just made, or will they be automatically fixed?


text:
Q: Custom script file enqueue has "?ver=4.5.1" when loading and doesn't update I'm loading a custom script file using an enqueue and here's the output:
<script type='text/javascript' src='.../wp-content/themes/enfold-child/js/custom_script.js?ver=4.5.1'></script>
curious why it's appending that "?ver=4.5.1" at end. When I remove in console file loads fine, but when it's there blank file. Not sure if that's a caching thing or I should be loading some other way. Here's my enqueue code:
add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets');

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/js/custom_script.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

A: I agree with @Mark Kaplun - what you're describing is an odd behavior though. Try this markup to override the $ver param.
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), null, true);
https://developer.wordpress.org/themes/basics/including-css-javascript/
Alternatively, to work around the version cache try this markup which will generate a unique version with each page load.
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), rand(1, 100), true);

A: You should always specify a version number for you scripts/css when you enqueue them, otherwise when you change them on the server they might not be changed for the user because some caching proxy in the middle cached it and keep serving it.
If you don't specify one, wordpress will attach its own version number to the url as the ver parameter, but frankly IMO this behavior is more of a bug then a feature, since obviously wordpress upgrade almost never align with changes you are doing in your JS/CSS.


text:
Q: opengl from window point to 3d coordinate For a big project of mine i need at some point to draw a cube on the screen and i need to know if i clicked on a face of the cube. For that i know that i have to use the depth buffer. But the conversion i try to do doesnt work. Here is my code:
#include "Includes.h"
#include "Shader.h"

#define WIDTH 800
#define HEIGHT 600

using namespace std;

sf::Event event;

GLfloat get_gl_depth(int x, int y);
glm::vec4 get3dPoint(glm::vec2 point2D, int width,int height, glm::mat4 modelMatrix);

int main()
{
    sf::ContextSettings settings;
    settings.depthBits = 32;
    settings.stencilBits = 8;
    settings.antialiasingLevel = 4;
    settings.majorVersion = 3;
    settings.minorVersion = 0;

    sf::Window window(sf::VideoMode(WIDTH, HEIGHT), "OpenGL", sf::Style::Default, settings);

    GLfloat vertices[] = {
        -2.0, -2.0, -2.0,  0.0f, 0.0f,
         2.0, -2.0, -2.0,  1.0f, 0.0f,
         2.0,  2.0, -2.0,  1.0f, 1.0f,
         2.0,  2.0, -2.0,  1.0f, 1.0f,
        -2.0,  2.0, -2.0,  0.0f, 1.0f,
        -2.0, -2.0, -2.0,  0.0f, 0.0f,

        -2.0, -2.0,  2.0,  0.0f, 0.0f,
         2.0, -2.0,  2.0,  1.0f, 0.0f,
         2.0,  2.0,  2.0,  1.0f, 1.0f,
         2.0,  2.0,  2.0,  1.0f, 1.0f,
        -2.0,  2.0,  2.0,  0.0f, 1.0f,
        -2.0, -2.0,  2.0,  0.0f, 0.0f,

        -2.0,  2.0,  2.0,  1.0f, 0.0f,
        -2.0,  2.0, -2.0,  1.0f, 1.0f,
        -2.0, -2.0, -2.0,  0.0f, 1.0f,
        -2.0, -2.0, -2.0,  0.0f, 1.0f,
        -2.0, -2.0,  2.0,  0.0f, 0.0f,
        -2.0,  2.0,  2.0,  1.0f, 0.0f,

         2.0,  2.0,  2.0,  1.0f, 0.0f,
         2.0,  2.0, -2.0,  1.0f, 1.0f,
         2.0, -2.0, -2.0,  0.0f, 1.0f,
         2.0, -2.0, -2.0,  0.0f, 1.0f,
         2.0, -2.0,  2.0,  0.0f, 0.0f,
         2.0,  2.0,  2.0,  1.0f, 0.0f,

        -2.0, -2.0, -2.0,  0.0f, 1.0f,
         2.0, -2.0, -2.0,  1.0f, 1.0f,
         2.0, -2.0,  2.0,  1.0f, 0.0f,
         2.0, -2.0,  2.0,  1.0f, 0.0f,
        -2.0, -2.0,  2.0,  0.0f, 0.0f,
        -2.0, -2.0, -2.0,  0.0f, 1.0f,

        -2.0,  2.0, -2.0,  0.0f, 1.0f,
         2.0,  2.0, -2.0,  1.0f, 1.0f,
         2.0,  2.0,  2.0,  1.0f, 0.0f,
         2.0,  2.0,  2.0,  1.0f, 0.0f,
        -2.0,  2.0,  2.0,  0.0f, 0.0f,
        -2.0,  2.0, -2.0,  0.0f, 1.0f
    };

    glewInit();
    glViewport(0, 0, WIDTH, HEIGHT);
    glEnable(GL_DEPTH_TEST);
    Shader ourShader("shaders/default.vs", "shaders/default.frag");

    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

    glBindVertexArray(0); // Unbind VAO

    bool running = true;

    glm::vec3 cubePosition;
    cubePosition.z=-3;
    window.setFramerateLimit(30);

    glm::mat4 model;
    glm::mat4 view;
    glm::mat4 projection;

    while (running)
    {
        model=glm::mat4();
        model=glm::translate(model,cubePosition);
        view=glm::mat4();
        projection=glm::mat4();
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
        projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        ourShader.Use();

        GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
        GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
        GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");

        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        while (window.pollEvent(event))
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
                cubePosition.y-=0.2;
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
                cubePosition.y+=0.2;
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
                cubePosition.x+=0.2;
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
                cubePosition.x-=0.2;

            if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                float x=sf::Mouse::getPosition(window).x;
                float y=sf::Mouse::getPosition(window).y;
                float z=1.0;

                glReadPixels(x,HEIGHT-y-1,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&z);

                x=2.0*(x/WIDTH)-1;
                y=-2.0*(y/HEIGHT)+1;

                glm::vec4 v=glm::vec4(x,y,z,1.0);
                v=v*glm::inverse(projection*view*model);

                v.x/=v.w;
                v.y/=v.w;
                v.z/=v.w;

                cout<<v.x<<' '<<v.y<<' '<<v.z<<' '<<v.w<<'\n';
            }

            if (event.type == sf::Event::Closed)
            {
                // end the program
                running = false;
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
                glViewport(0, 0, event.size.width, event.size.height);
            }
        }

        window.display();
    }
    return 0;
}

So initialy the cube is drawn in the center of the screen and when i try to click on the left-top corner(first red pixel) i should get the numbers x=-2 ,y=2 but i get x=0.0150043,y=0.0150043 which is not even close. Where is my mistake? i followed this tutorial and read online about this topic:
http://webglfactory.blogspot.ro/2011/05/how-to-convert-world-to-screen.html

A: Projecting means translating world coordinates to normalized cannonical coordinates. NCC is a 2x2x2 cube space. The translation from this NCC space to window screen coordinates is done "automagically" by the GPU, using the parameters you passed in glViewport.
So first of all you must undo screen-NCC translation. Use https://www.opengl.org/sdk/docs/man2/xhtml/glViewport.xml formula.
Because window coordinates are 2D you can not get back the depth coordinate. There is an infine straight from your eye to the 2D window point and beyond.


text:
Q: How to call one method from another inside function I have tried to create javascript object like
function Caller() {

this.init = function() {
    makeCall();
};
this.makeCall = function(){/*come code here*/}

}

var a = new Caller();
a.init();

I got error function is not defined, same thing happens when I try to call this.makeCall();
When I remove this from makeCall definition it works, but when I remove also from init it doesn't work. How to solve this ?

A: Use this.makeCall(). Additionally define makeCall() before its use.
function Caller() {
    this.makeCall = function () { /*come code here*/ }
    this.init = function () {
        this.makeCall();
    };
}
var a = new Caller();
a.init();

DEMO

A: Use this.makeCall() it is a method so you can use it.

A: Try this this.makeCall() function is executed successfully here.
<html>
<head>
</head>

<body>
 <script>
    function Caller() {

        this.init = function() {
            this.makeCall();
        };
        this.makeCall = function(){
            alert('hello');
        }

    }

    var a = new Caller();
    a.init();
 </script>
</body>
</html>

A: You need to call the function properly using this
makeCall(); => this.makeCall();

A: You can use IIFE to declare Caller:
var Caller=(function () {
    function constructor() {
    }

    function makeCall() {
        /*come code here*/
    }

    constructor.prototype.init=function () {
        makeCall.apply(this, arguments);
    };

    return constructor;
})();

var a=new Caller();
a.init();

and be sure that Caller is loaded before it is invoked.

A: To answer your question and to enhance your code you should have a look at this:
function Caller(){};

This is your constructor.
You can then add methods to your constructor like this:
Caller.prototype.init = function () {
    // do something
}

When you create instances of your "class" Caller
var a = new Caller();

every instance will have the methods you described in the Caller.prototype object.
And to solve your problem:
If one prototype method wants to call another prototype method, you need to do this:
// do some setup in your constructor
function Caller(phoneNumber) {
    this.phoneNumber = phoneNumber;
};

Caller.prototype.init = function () {
    // the code word "this" will be the instance itself
    this.makeCall();
};

Caller.prototype.makeCall = function () {
    // do whatever this method needs to do
    alert('calling ' + this.phoneNumber);
};

var a = new Caller(0123456789);
a.init();

The main thing to understand is, that in every prototype method, the keyword this references the current instance of the constructor (in this case Caller).


text:
Q: angular 5 programatic access to observable from service getter Service
...
cart: any = {...}; //observable set in a subscription to and api response
get Cart() {
    return this.cart;
}
...

Component
get Cart() { return this.bcCartService.Cart; }

constructor(
    private bcCartService: BcCartService
) {}

ngOnInit() {
    console.log("Cart: ",this.Cart); // see screenshot
    console.log("Cart: ",this.Cart.data); // "Cart:  undefined"
}

Console Screenshots

The Problem
I need to programmatically access this.Cart but i keep getting undefined or ts compile errors when i try to go any deeper for example  this.Cart.data returns undefined

A: service
_cart:any;

fetchCartData(){
    this.http.get('/api/cart').subscribe (res => {this._cart = res});
}

get Cart() {
     return this._cart;
}

component
get Cart() {
    return this.service.Cart;
}

HTML
<p>{{Cart | json }}</p>

Solution2
service
getCartData() {
    return this.http.get('/api/cart');
}

component
ngOnInit(){
    this.service.getCartData().subscribe(res => {
        console.log(res); // here you will get desired data.
    });
}


text:
Q: How to immediately redraw a Label (NSTextField) in Swift? I'm dealing with a synchronous task which takes a little time to complete (about 1-2 sec).
Before that task begins, I'd like to update a Label's text:
label.stringValue = "Loading"
doMyTask() // This freezes everything for a moment

However, the text only appears when my task is done, making the Loading message totally useless.
So, is there a reason to force my Label to update its text before the task will begin?
This, for example, is the way of achieving this in C# while working with Windows Forms:
label.Text = "Loading";
label.Refresh();

I tried label.setNeedsDisplay() as well as label.updateLayer() and that didn't work out
Thank you.


text:
Q: Hashtag detection from a chunk of text, in PHP I am looking to create a php script that detects twitter style hashtags from a chunk  of text. So it would search for #then_a_word.

A: Using a regex and preg_match_all(), you could have something like this :
$str = <<<STR
this is a string
with a #tag and
another #hello one
STR;

$matches = array();
if (preg_match_all('/#([^\s]+)/', $str, $matches)) {
  var_dump($matches[1]);
}

Which gives the following output :
array
  0 => string 'tag' (length=3)
  1 => string 'hello' (length=5)

And, if you need to do a bit more manipulations on those, you should take a look at the PCRE Functions section of the manual : there are some others that might help you.

A: <?php

$str = "I LIKE BURGERS"; // for example
$pattern = "\burgers\i";
echo "$pattern, "BURGERS", $str";

?>


text:
Q: Download URL content with timeout I want to download the URL content in java with a specified download time. For ex: i want to have a maximum download timeout of 10 seconds for www.yahoo.com. If download takes more than 10s, then an error should be thrown. I have written the code for opening a connection and downloading the entire contents. But how do i set the download timeout? Here is the code snippet:
        StringBuilder text = new StringBuilder();

        urlconn = (HttpURLConnection)url.openConnection();
        urlconn.setConnectTimeout(100000);
      //urlconn.setInstanceFollowRedirects(false);
        urlconn.setRequestMethod("GET");
        urlconn.connect();
        buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
        while((line = buf.readLine()) != null)
            text.append(line);
        System.out.println(url + "=> "+ urlconn.getResponseCode());

A: You can set it by URLConnection#setReadTimeout().
urlconn.setReadTimeout(10000); // 10 sec
// ...

A: Use URLConnection.setReadTimeOut().