text:
Q: Does "I don't have either late-night nor between-meal snacks" sound natural? Does the sentence sound natural?

I don't have either late-night nor between-meal snacks.

A: No, it doesn't sound natural.  You've mixed your correlative conjunctions.
Either is used with or and neither should be paired with nor, so you should choose from the following options:

I don't have either late night or between-meal snacks.
I have neither late night nor between-meal snacks.

A: Regarding specifically Does the sentence sound natural?, and assuming you mean in spoken English today.
It does not. You almost never say "nor" in every day spoken English.  For that matter, you rarely say "either" in every day spoken English, and if you do you place it badly at the end.
A copywriter on a radio ad would probably write to be read:
"I don't eat late-night snacks, and I don't
eat between-meal snacks, either!!"

Furthermore! Hyphenated "slightly technical" phrases like "between-meals" do not sound natural in spoken English.
In real life (funnily enough, I don't eat snacks late at night and I don't eat snacks between meals) I'd probably say something like: I never eat snacks late at night and I never eat snacks between meals.


text:
Q: IE7 does it well but IE8 does not load the javascript gallery script - whats wrong? I have a javascript galleria which does work in every modern browser, even in IE7. But in IE8 if its load.. it does not show the gallery.. BUT if I press Ctrl + F5 it does a hard reload, it erase the cache and finally the galleria appears.. If I just reload the page.. or if I go to another page with the same galleria script, the problem comes again.. so I need a hard reload script for IE8.
Pseudo Code:
On Document Load

If user agent IE8 {
erase website cache
}

do normally continue webpage loading..

A: The problem isn't on the client side. The problem is your server. IE will aggressively cache responses to AJAX requests unless the server sets a Cache-Control: no-cache in the response. Clearing the cache in the browser is the wrong fix, because the server should decide what is current and what is not.
So change the server response to your request to include the correct headers.

A: see that link about clearing the cache!
Clear all website cache?

A: One possible way to fake a clear cache would be to attach a cache buster to all resources from a page your resources like
"test.js?cacheBuster=" + new Date())

This should be a last resort.

A: Using javascript you won't be able to do this. What you can do is to write code in your server side language so that the entire page won't be cached.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof that $\sum_{i=0}^n {n\choose i}2^{i}=3^{n}$ The following sum came up in a combinatorial argument. I know what it equals thanks to Wolfram Alpha, but I'm not sure how to show it
$$\sum_{i=0}^n {n\choose i}2^{i}=3^{n}$$

A: For the record, the proof 5xum alludes to goes as follows:
The Binomial Theorem states that $$(a+b)^n=\sum_{I=0}^n{n \choose i} a^ib^{n-i}$$ For $a=2,b=1$, we notice that our sum is of the above form.

A: As a combinatorial proof, both sides of the equality count the number of partitions of $\{1,2,\ldots,n\}$ into three ordered parts $(A,B,C)$.

*

*Method 1: For each element, we add it to $A$, $B$, or $C$, giving $3^n$ possibilities.

*Method 2: We choose $i \in \{0,1,\ldots,n\}$ elements to be added to $B \cup C$, and the rest go into $A$.  Of those $i$ elements, we add them to $B$ or $C$ one by one, giving $2^i$ possibilities.  This totals $\sum_{i=0}^n \binom{n}{i} 2^i$.

A: Hint:$ $ $ $ $ $
$$3^n = (2+1)^n$$


text:
Q: Your raw query had an incorrect number of parameters. Expected: `0`, actual: `2`. Prisma Prepared Statements Please go soft on me this is my first time asking here questions.
I am having a scenario that is causing my query to fail when I try to template it with variables. But when I pass in the static values it works.
The first image shows a query with static values
Code Block logic with static values
the second image is the response of the above logic.
Response while using static values
Now observe what happens when I change the query to use the templated prepared statements.
Templated code block with variables
The response I get
Templated code response


text:
Q: How to estimate reindexing time? How do you estimate the total time reindexing an entire table will take in PostgreSQL?
I have a large PostgreSQL database, the primary table of which has 15 million rows with 100 columns and 200 indexes.
I'm seeing a problem where, after a night of processes loading data into the table, queries to the table are terribly slow for about 3-6 hours after the loading ends. However, these queries miraculously become fast again after 6 hours post-load.
Is this temporary slowness caused by Postgres updating indexes in the background? How do I speed up this processing? I can't find any parameters for controlling this.
I was thinking about running a REINDEX on the table immediately after loading ends, but I'm not sure how long this will take, and I'm worried it might take longer than the original load and will only worsen performance.
My table stores dozens of descriptors about a customer, and the indexes (many of them partial indexes) are for speeding up very routine queries run by users.
The database is nearly a terabyte, so I rarely load the entire thing to a dev environment. Instead, I have a script that copies a few thousand records.

A: As you have 200 index, it would take longer than a vacuum. A reindex always depends on your OI. It seemed that it would take more than an hour.
What I would suggest is:

*

*get rid of some indexes. 200 for 100 columns makes no sense. See how many of the l those you use 90% of the time.
1.1. The other queries would find their path along other indexes
1.2. Your record takes more time recording indexes than rows, I that should be slowing down your night update

*You could reindex the indexes the you use the most
2.1. Use REINDEX INDEX index_name;
2.2. If you can run some reindex in parallel, it would make better use of your server cores


text:
Q: Is this a compiler bug or it's my code? Here is a sample code:
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <ctime>
#include <sstream>

using std::cout;
using std::endl;

std::size_t const BUF_SIZE(1000);

std::ostream& operator<<(std::ostream& os, std::tm const& rhs)
{
    os << asctime(&rhs);
    return os;
}

std::istream& operator>>(std::istream& is, std::tm& rhs)
{
    while (is.peek() == ' ' || is.peek() == '\t')
    {
        is.get();
    }
    std::streampos curPos = is.tellg();
    char buf[BUF_SIZE];
    is.getline(buf, BUF_SIZE);
    char* ptr = strptime(buf, "%D %T", &rhs);
    if (ptr == 0)
    {
        throw std::runtime_error("strptime() failed!");
    }
    std::size_t processed = ptr - buf;
    is.seekg(curPos + static_cast<std::streampos>(processed));
    return is;
}

int main()
{
    std::istringstream is("10101 07/09/12 07:30:00 123.24");
    int uuid(0);
    double price(0);
    std::tm ptime; std::memset(&ptime, 0, sizeof(tm));

    is >> uuid >> ptime >> price;
    cout << "UUID: " << uuid << endl;
    cout << "Time: " << ptime;
    cout << "Price: " << price << endl;
}

where I'm trying to overload the << and >> operators for struct tm!
If I compile my code with g++ and run it, I get:
UUID: 10101
Time: Sun Jul  9 07:30:00 2012
Price: 123.24

Perfect!
But, if I compile it using clang++, I get:
UUID: 10101
Time: Sun Jul  9 07:30:00 2012
Price: 0

OOPS!
What is going on? it this an issue with clang or it's the way i'm processing the istream?

A: I was able to reproduce this (g++ 4.7.0 and clang++ 3.1 with libc++-svn) and a brief debugging session showed that clang++ sets the eofbit after getline (which is normal), which then somehow causes seekg to set failbit. This sounds like a bug, given that seekg first clears eofbit (§27.7.2.3/41)
To work around, insert is.clear() anywhere between the getline and the seekg.


text:
Q: How can I describe a person who does not get to the point? When a person talks about something, s/he doesn't get to the point but starts with a pun, intending to let us figure out its purpose.
Someone told me I could use reserved to describe that person, but I checked ODO which says this means slow to reveal emotion or opinions. I guess it's not quite correct here.
Is there any better word for such a person?

A: If he speaks in a way that hides the meaning of his intentions, he is being cryptic. You are right that reserved is not the right word as that would mean he is shy.

A: I think that's referred to as being obtuse.

A: He sounds to me to be vague and inarticulate.

A: Speakers who take a long time to get to the point are longwinded. Those who may be briefer, but who are nevertheless dull or insensitive in their expression are, as Hy Libby has suggested, obtuse.

A: If he's hesitant to state his point out of concern for social repercussions, he may be said to be pussyfooting or beating around the bush.

A: Circumlocutor: literally, one who speaks around. The sense I get from your description is that of someone who is too enamored with his own voice. The deliberate concealing of meaning is esoteric, which one may use as either a verb or a noun. "Obtuse" suggests dense, slightly stupid. I would call this person annoying.


text:
Q: how to get json's filtered data in vue js form's v-model property? for update       async getData() {
        let result = await axios.get('/restaurant/')
        console.warn(result.data.data)
        //  this.list = result.data.data;
        this.list = JSON.stringify(result.data.data);
        var data = JSON.parse(this.list);
        this.restaurant = data.filter(d => d.restaurantId === 2);
        console.warn(this.restaurant)
    }

i'm trying to use this.restaurant's data in my v-model

<div class="form-group">
   <input type="text" class="form-control" v-model="this.restaurant.restaurantName" id="recipient-name">
 </div


text:
Q: Calculate convolution $x_n * y_n$ Having these two sequences:
$x_n = u_n u_{-n}$
$y_n = (n+1) u_n u_{3-n}$
Then the convolution of $ x_n * y_n $ equals...
The options are:
A. $x_n $
B. $y_n $
C. $(n+1) u_{n-4} u_{7-n}$
D.  $(n-3) u_{n-4} u_{7-n}$
Note: $u_n = 1$ if  $n \geq 0$ and $u_n = 0$ if  $n < 0$
Since $x_n$ seems to be always 0, then I'd say option would be A but apparently the correct option is B??
Update: $x_n$ is always 0 except when n = 0.
Ok so by definition Convolution would be something like:
$\int_{-\infty}^\infty x_t * y_{n-t} dn $
$\int_{-\infty}^\infty x_n y_{n-t} = \int_{-\infty}^\infty u_n u_{-n} (n-t+1) u_{n-t} u_{3-(n-t)} dt $
But since $x_t$ is only 1 when n = 0.
Then I would only evaluate
$\int_{0}^0 (n-t+1) dt = 0 $
What am I doing wrong??

A: Convolution of sequences is computed using a sum, not an integral. Specifically, if $x_n$ and $y_n$ are sequences, then their convolution is
$$\sum_{k=-\infty}^\infty x_k y_{n-k}$$
In your case, $x_k = u_k u_{-k}$, which as you pointed out, is zero for $k \neq 0$, and $x_0 = u_0^2 = 1$. In other words,
$$x_n = \begin{cases}1 & \text{ if $n = 0$ } \\ 0 & \text{ otherwise } \end{cases}$$
which is often written as $x_n = \delta_n$.
This means that only the $k=0$ term in the convolution sum is nonzero:
$$\sum_{k=-\infty}^\infty x_k y_{n-k} = x_0 y_{n-0} = y_n$$
So (b) is the correct answer. Note that this choice of $x_n$ satisfies $x_n * y_n = y_n$ for any sequence $y_n$. We say that $x_n = \delta_n$ is an identity with respect to the convolution operation.


text:
Q: NIS: which mechanism hides shadow.byname for unpriviledged users? On some Linux box (SLES 11.1) which is a NIS client I can do as root:
ypcat shadow.byname
and get output, i.e. some lines with the encrypted passwords, amongst other information.
On the same Linux box, if I run the same command as unpriviledged user, I get
No such map shadow.byname. Reason: No such map in server's domain
Now I am surprised. My good old knowlege says that shadow passwords in NIS are absurd because there is no access control or authentication in the protocol and thus every (unpriviledged) user can access the shadow map and thereby obtain the encrypted passwords.
Obviously we have a different picture here. Unfortunately I don't have access to the NIS server to figure out what is happening. My only guess is that the NIS master gives the map only to clients conection from a priviledged port (>1024), but this is only an uneducated guess.
What mechanisms are there in current NIS implementations to lead to a behavior like the above? How "secure" are they? Can the be circumvented easily? Or are shadow passwords in NIS as secure as the good old shadow files?

A: Access to maps that are not world-readable under /var/yp/{domainname}/ on the NIS master is restricted to clients making request from privileged port (<1024). It's not as secure as local /etc/shadow but still slightly better than nothing.
For a better security Sun designed NIS+ but it never really got widely adopted.
Much better is LDAP where the password hash doesn't have to be fetched from the server to the client but instead the client sends the proposed password to the server for verification (LDAP auth-bind).


text:
Q: LINQ with Entity Framework, getting calculated sum I have the following data:

Number can be NULL
I am writing a LINQ statement to get the following number as a result:

*

*100 with factor 110 is 110

*200 with factor 90 is 180

Needed result: 290
My LINQ statement currently looks like this:
(from b in data
where b.Number.HasValue
select new
{
    Number = b.Number.Value,
    b.Factor
}).Sum(o => o.Number * (o.Factor / 100));

I get the following error:

The cast to value type 'Decimal' failed because the materialized value
  is null. Either the result type's generic parameter or the query must
  use a nullable type.

A: This can be fixed by casting the contents of the Sum like this:
(from b in data
where b.Number.HasValue
select new
{
    Number = b.Number.Value,
    b.Factor
}).Sum(o => (decimal?)(o.Number * ((decimal)o.Factor / 100))) ?? 0;

(note: I found the answer while writing the question and thought I might as well formulate an answer and publish it for anyone else to find)


text:
Q: PHP redirect with header not working Here is my code:
<?php

$url = $_GET["id"];

$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

    $sql = "DELETE FROM Table WHERE id='".$url."'";

    if ($conn->query($sql) === TRUE) {
        echo 'Row deleted successfully';
    } else {
        echo "Error deleting record: " . $conn->error;
    }

    $conn->close();

    header('Location:index.php');
        exit;
    ?>

But header redirect is not working...
Here is the error log:

Strict Standards: header(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead in /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php on line 24
Warning: Cannot modify header information - headers already sent by (output started at /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php:1) in /homepages/5/d394578306/htdocs/XXXXXX/XXXXXX/delete.php on line 24

A:     <?php

Delete the whitespace before the PHP tag - that counts as output and will stop the header() call from working.
You're also doing some echo calls, both of which will also stop the redirect from working as echo will output content/headers to the browser.

A: It appears to me that the timezone warning of the header causes the output, which in turn makes the function itself not work. Try doing this:
@header('Location:index.php')

The @ will suppress error output for that particular function call.
Also, as Bulk correctly pointed out, you should disable your echo calls in lines 17 and 19, or move them below the header method call.

A: Based on the timezone error, try this:
<?php
date_default_timezone_set("--HERE YOUR TIMEZONE---");
$url = $_GET["id"];

$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

    $sql = "DELETE FROM Table WHERE id='".$url."'";

    if ($conn->query($sql) === TRUE) {
        echo 'Row deleted successfully';
    } else {
        echo "Error deleting record: " . $conn->error;
    }

    $conn->close();

    header('Location:index.php');
        exit;
    ?>

Now replace the "--HERE YOUR TIMEZONE---".
Here you can find the correct timezone for your country: http://php.net/manual/en/timezones.php


text:
Q: Cutpoint/threshold not determined using R? Please find My data below. q constitutes a sample of 100 cases.
I have two covariates follow.up and hematoma, each indicating follow up time (in days) and the event of a post-surgically bleeding after specific procedure.
Based on the cumulative incidence curve below, it seems that the risk decreases after the initial couple of days. I wish to mark or estimate after how many days the slope flattens.

I have applied library(maxstat) but I cannot seem to get it to work.
maxstat.test(Surv(follow.up, hematoma) ~ 1, data=q, smethod="Median", pmethod="HL", alpha=0.05)

Which yields
Error in match.arg(type) : 'arg' should be one of "LogRank"

Which intuitively is wrong as there are no subgroups, and therefore no need for a LogRank? Even changing smethod="LogRank" does not solve the problem.
Can you help me apply maxstat to determine a cut-off (or by any other method)?
q <- structure(list(hematoma = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), follow.up = c(699.2430556,
55.21180556, 272.2604167, 2077.253472, 735.1770833, 193.125,
13.25347222, 81.19444444, 81.28125, 115.2881944, 1015.260417,
0.5, 216.21875, 1471.298611, 10.13194444, 182.2673611, 178.2743056,
10.24652778, 143.2013889, 194.2881944, 13.28125, 122.2291667,
115.2743056, 154.2395833, 1026.28125, 112.25, 11.27083333, 924.1076389,
21.27986111, 0.1, 78.26388889, 110.1805556, 419.2638889, 185.2291667,
140.1840278, 13.26388889, 157.2256944, 126.2847222, 1860.246528,
150.21875, 13.26041667, 12.28472222, 12.29166667, 27.20833333,
185.25, 168.21875, 84.19097222, 479.2569444, 101.2708333, 1120.243056,
12.21527778, 13.17708333, 164.2013889, 115.2708333, 294.28125,
150.15625, 13.18055556, 164.28125, 125.28125, 539.1701389, 138.2291667,
18.28819444, 269.25, 518.2847222, 1505.131944, 1153.28125, 238.21875,
202.25, 11.19513889, 4.034722222, 311.2569444, 206.2777778, 1699.246528,
217.2777778, 175.2465278, 13.28472222, 122.1631944, 448.2395833,
6.274305556, 196.1458333, 171.2708333, 1349.229167, 101.5590278,
13.24652778, 13.58680556, 181.4340278, 96.16666667, 136.2881944,
1153.295139, 553.2569444, 131.2638889, 1629.260417, 143.2361111,
300.2673611, 3.1875, 237.2361111, 130.2777778, 363.1840278, 105.2708333,
150.1770833)), .Names = c("hematoma", "follow.up"), row.names = c(NA,
100L), class = "data.frame")


text:
Q: Python : Keeping up the number of points in a live plot I have been trying to create a live plot by matplotlib.
My trial code is this.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import time
from PySide import QtCore

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

N=100

def animate(j):
    graph_data = open('example.txt','r').read()
    lines = graph_data.split('\n')
    xs=[]
    ys=[]

    for line in lines:
        if len(line) > 1:
            x,y = line.split(',')
            xs.append(float(x))
            ys.append(float(y))
    ax.clear()
    ax.plot(xs, ys)

def initFile():
    fid = open('example.txt','w')
    fid.write('')
    fid.close()
    for i in range(0,N):
        fid = open('example.txt', 'a')
        fid.write(str(i) + ',' + str(0) + '\n')
        fid.close()

def updateFile():
    global wThread
    wThread = writeThread()
    wThread.start()

class writeThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.exiting = False

    def run(self):
        i=0
        while 1:
            fid = open('example.txt', 'a')
            fid.write(str(N+i) + ',' + str(np.sin(2*np.pi*0.05*i)) + '\n')
            time.sleep(0.1)
            i=i+1
            fid.close()

initFile()
updateFile()
ani = animation.FuncAnimation(fig, animate, interval = 200)
plt.show()

It works well. But, the plot points are accumulated. I want to keep up the number of points in my plot as N.
How could I do that?

A: Simply restrict the size of your array/list to the last N points:
def animate(j):
    (...)
    ax.clear()
    ax.plot(xs[-N:], ys[-N:])


text:
Q: Problem using Printf and Scanf in a HackerRank practice problem I have been trying to solve this problem in Hackerrank for quite a while now.The issue that i am facing is that I being a beginner on reading the question ended up using cin and cout instead of scanf and printf while taking user input just so as to be able to check as to whether my reasoning was correct or not and although I have solved the problem correctly using the former but am facing difficulty using the latter.
Here is the problem that I have been trying to solve:
https://www.hackerrank.com/challenges/acm-icpc-team/problem
Here is code using cin and cout:
#include<iostream>
#include<stdio.h>
using namespace std;

int main(){
int n,m;
 cin>>n>>m;
int a[n][m]={};
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < m; j++)
    {

       cin>>a[i][j];
    }

}
int b[n*(n-1)/2][m]={};

int x=0;
for (int i = 0; i < n-1; i++)
{
    for (int j = i+1; j < n; j++)
    {
       for (int k = 0; k < m; k++)
       {
           b[x][k] = (a[i][k]|a[j][k]);
       }
       x=x+1;

    }
}

int count = 0;
int c[n*(n-1)/2]={};

for (int i = 0; i < n*(n-1)/2; i++)
{
    c[i]=0;
}
for (int i = 0; i < n*(n-1)/2; i++)
{
    for (int j = 0; j < m; j++)
    {
        if (b[i][j]==1)
        {
           count++;
        }

    }
    c[i]=count;
    count=0;

}

for (int i = 0; i < n; i++)
{
   int temp=c[i];
   int j=i;
   while (j>0 && temp<c[j-1])
   {
       c[j]=c[j-1];
       j=j-1;
   }
   c[j]=temp;

}
int sum=0;
for (int i = 0; i <  n*(n-1)/2; i++)
{
    if (c[ n*(n-1)/2 - 1]==c[i])
    {
        sum++;
    }

}
cout<<c[ n*(n-1)/2 - 1]<<endl;
cout<<sum;

    return 0;
}

While writing the entire code using "printf" and "scanf" , I simply replaced "cin and cout" :
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int n, m;
    scanf("%d", "%d", &n, &m);
    int a[n][m] = {};
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }
    int b[n * (n - 1) / 2][m] = {};

    int x = 0;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            for (int k = 0; k < m; k++)
            {
                b[x][k] = (a[i][k] | a[j][k]);
            }
            x = x + 1;
        }
    }

    int count = 0;
    int c[n * (n - 1) / 2] = {};

    for (int i = 0; i < n * (n - 1) / 2; i++)
    {
        c[i] = 0;
    }
    for (int i = 0; i < n * (n - 1) / 2; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (b[i][j] == 1)
            {
                count++;
            }
        }
        c[i] = count;
        count = 0;
    }

    for (int i = 0; i < n; i++)
    {
        int temp = c[i];
        int j = i;
        while (j > 0 && temp < c[j - 1])
        {
            c[j] = c[j - 1];
            j = j - 1;
        }
        c[j] = temp;
    }
    int sum = 0;
    for (int i = 0; i < n * (n - 1) / 2; i++)
    {
        if (c[n * (n - 1) / 2 - 1] == c[i])
        {
            sum++;
        }
    }

    printf("sum");

    return 0;
}

I am also attaching a copy of the output that I am getting using the former code:
The output is coming out fine when I am manually giving whitespace characters but when am running the same code using printf and scanf it's not working for me for some reason:

Could someone plz guide me as to where was I going wrong?

A: scanf("%d", "%d", &n, &m);

should be
scanf("%d %d", &n, &m);

scanf takes one format string as it's first argument and then (depending on the format string) zero or more arguments after that.
printf is similar, so
printf("sum");

should be
printf("%d", sum);

All of this is well documented here and here.

A: you have 4 problems.

*

*scanf("%d", "%d", &n, &m); will not load the integers into n and m. It will load try to load 1 integer into the second argument(int this case "%d") then ignore n and m. To load multiple integers in the same scanf you need to add all of the %d's in the same string:

scanf("%d%d", &n, &m);

*the second scanf currently has no way of knowing how many digits you want to scan in as the integer and will therefore attempt to load the largest integer possible, because the maximum integer is 2147483647 it has no problem loading 10101 for example as a single integer. This works differently with std::cin as the ">>" operator will read 1 character at a time until it has enough to create a valid integer(1 is a valid integer). You can force scanf to only load a set number of digits by adding the number of digits to load to the format string:

scanf("%1d", &a[i][j]);

*Your printf function will simply print "sum" not the value of the variable sum. To get it to print the value of the sum variable you need to use the same type of formatting string you use in scanf:

printf("%d", sum);

*the original code prints out the value of c[ n*(n-1)/2 - 1] the second doesn't. You could either print this out in a second printf:

printf("%d\n", c[ n*(n-1)/2 - 1]); //note use of \n to force a new line on output
or in the same printf:
printf("%d\n%d", c[ n*(n-1)/2 - 1], sum);


text:
Q: DirectorySearcher does not return all AD group members I try to get all members of an Active Directory group in C#. My code looks like:
var searcher = new DirectorySearcher(defaultNamingContextEntry) {
    Filter = "(memberOf=" + group.Properties["distinguishedName"].Value + ")",
    PageSize = 1000,
    SearchScope = SearchScope.Subtree,
    Sort = new SortOption("sAMAccountName", SortDirection.Ascending)
};
var members = searcher.FindAll();

The code works so far, but has the problem that it does not return all group members.
I believe (I am not sure) that it returns what I can actually see for the "member" attribute in ADSI Edit (the group in question is a bit large to compare everything, but far below 1000), but these are not all members. There are users that are, according to AD Users & Computers, in the group which are not listed. If I look in the "Member Of" page, I can see the group, and ACL settings via the group affect the missing users, too. However, they are not in the result set.
The group in question is the primary group, in case this is relevant.
What is wrong here? What would be the correct parameters or query? Is this a problem of the AD itself?
Update: I have further investigated the problem (and tested Brian's solution, which I strongly recommend if your property collections are really large; I thought that there must be some kind of paging mechanism for properties, but could not find how it works):
I now know that the DirectorySearcher returns the correct result as seen in ADSI edit.
I also know that the "Primary Group" (set by the "Set Primary Group" button on the "Member Of" page in AD Users & Computers) is missing. Unix extensions are enabled in the AD, so we usually use this option. Changing the primary group changes which members are missing. The effect is deterministic.
I have looked into the entries using ADSI edit, but could not find the field that would allow me to add the primary group in my search. Although I have enabled everything (Mandatory, Optional, Constructed, Backlink and System-only attributes), I cannot see the primary group.
My revised question is: what is the correct LDAP filter for retrieving the primary group, too?

A: You need to do value ranging. See http://www.netid.washington.edu/documentation/enumeratingLargeGroups.aspx for an example.


text:
Q: If I change Windows admin user password, then I can't login to Outlook, why? I am seeing this strange behaviour with Windows 7 and Outlook 2010.
If I change the password of User1 (Admin user), login, and start Outlook, it asks for a password. It keeps saying "password incorrect". I can login by using same password on the OWA webclient.
If I change User1's password back to what it was before, Outlook starts without any prompting and I'm able to send and receive emails.
Is there any link between the user account, its password and the PST file's password?


text:
Q: PCA, Covariance of predictors and Noise/Distortion of Data I am reading a note on PCA and in the introduction the author states that large diagonal values in the covariance matrix of the predictors correspond to a strong signal and large off-diagonal values --i.e. covariances-- correspond to high noise or distortion in our data.
He furthermore presents an example from the well-known iris dataset which can be found in base R among other places.
> cov(iris[1:4])
             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length    0.6856935  -0.0424340    1.2743154   0.5162707
Sepal.Width    -0.0424340   0.1899794   -0.3296564  -0.1216394
Petal.Length    1.2743154  -0.3296564    3.1162779   1.2956094
Petal.Width     0.5162707  -0.1216394    1.2956094   0.5810063

In this dataset the covariances between Petal.Length and Sepal.Length and Petal.Width and Petal.Length are rather high.
I can intuitively understand the statement that large variances in the predictors imply a strong signal.  I can also readily comprehend that large covariances signify redundancy in the Signal, i.e. high multicollinearity.
What I find difficult to understand intuitively is that high covariances relate to high noise and distortion in the data.  For a starter, in the particular example of iris data brought forward by the author, the fact that certain  attributes of the flowers appear correlated is in no way a distortion or a noise, simply a physical reality.  But perhaps I do not comprehend the notion of distortion and noise as understood by the author of the note.
Your advice will be appreciated.

A: My understanding is that PCA does not have a concept of "noise", as opposed to other similar methods like factor analysis or probabilistic PCA that come with a model for the data in terms of a signal + noise decomposition. PCA simply determines how well the data can be represented by projections into lower dimension subspaces, and the off-diagonal elements, as you rightly say, tell us about the (pairwise) multicollinearity. It certainly works better on data coming from a Gaussian distribution than data coming from more irregular distributions, but this isn't a requirement.
I wonder what the author would say to the case where we have $n$ observations on one variable $x := (x_1, \dots, x_n)^T$ and our data matrix is $X = (x \hspace{3mm} x) \in \mathbb R^{n \times 2}$, so that $X^T X = x^T x \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$. This ought to be the perfect setting for PCA since we can losslessly project $X$ into a 1-dimensional subspace. If anything, this is a much better setting than when $X^T X$ is diagonal because then we don't gain anything, and PCA just corresponds to deleting columns of $X$ in order of increasing variance.
Could it be that there is some extra context that we are missing from this question, such as how each variable is supposed to be independent so $E(X^T X)$ is diagonal?


text:
Q: Difference b/w Objective C's self and C++'s this? can someone tell the difference between objective C's self and C++ this pointer?

A: Yes.  One is spelt s-e-l-f.  The other is spelt t-h-i-s.
Less facetiously:
self is used in Objective-C classes to represent a pointer the current instance.
this is used in C++ classes to represent a pointer the current instance.
They perform analogous roles but on entirely different structures.

A: The main difference is that this is a keyword, while self is a variable. The result of this is that while this always refers to the object that is executing a particular method, Objective-C methods are free to modify self during execution. This is sometimes used by constructors, which set self = nil on failure.
The reasons for doing so are:

*

*so that subclasses (which chain initialisers with self = [super init]) can see when the initialisation fails and know not to carry on in their own initialisers.

*composing objects can see the failure and know that they don't have a valid component.

Some initialisers will set self to a different, but valid, object. This can be used in class clusters, where the "abstract" class can generate a temporary instance while building the initialised object, but ultimately return a different object based on the properties that were built up during construction.
In addition, it means that you can do the usual things with variable names that confuse everyone that you can't do with keywords, such as defining a more local variable with the same name self in a code block.


text:
Q: ServiceStack.Text json only serialize struct properties Is it possible to make ServiceStack.Text sterilize public fields of a struct just like the .net JavaScriptSerializer does?
Currently if a struct does not define a filed as a property, i.e. property keyword in c++ or get;set; in c# the value does not get serialized.

A: This is not currently possible with ServiceStack serializers.
By design ServiceStack serializers tries to promote the use of special purpose DTOs for use in the service layer/boundary of your services, in this goal we only serialize public properties of types which allows flexibility in how the wire format is generated.
This is opposed to being a general purpose object serializer that would also serialize the internal representation of your types (i.e. private and public fields).


text:
Q: PowerBI and Stream Analytics - Auto refresh doesnt work I have used Azure Stream Analytics to Import Data from a Hub - it worked.
I created an output to Power BI, and created a live Dashboard in Power BI with the dataset from Stream Analytics - it worked as well.
Now, if I manually refresh the report (reload the page), the newest data will be displayed (I push 100 rows in a minute from Azure to Power BI). But if I view the report in the browser, and I do not manually refresh, the report doesn't refresh automatically. Can anyone give me a hint?
Thanks in advance!

A: When using Power BI to view streaming data, it doesnt currently allow you to build reports showing this streaming data which is viewed in real time. You have to use the Q&A function and ask questions such as "Average voltage for last 10 minutes in a line chart" and it will display that streaming with new data. Once you have that base chart, you can modify it as required and then pin this to your dashboard of choice.
I hope they make it so that you dont need to use Q&A and allow you to build reports on streaming data. I feel your pain!...
https://azure.microsoft.com/en-us/documentation/articles/stream-analytics-power-bi-dashboard/#limitations-and-best-practices


text:
Q: android: using custom fonts in Galaxy devices I am using a custom font im my android application and i am applying like this
Typeface tf = Typeface.createFromAsset(getAssets(),"calibri.ttf");
    mEmailSignInButton.setTypeface(tf);

This code works perfectly in any device, except by the samsung galaxy note 2 (i presume that does not work in other galaxy device):

Any clues of what can i do in galaxy devices?
Edit:
I doing like this right now:
This is my application class (overriding my default application class):
public class ApplicationCustom extends android.app.Application {

private static Typeface customTypeface;

@Override
public void onCreate() {
    super.onCreate();
    FontsOverride.setDefaultFont(this, "DEFAULT", "calibri.ttf");
    FontsOverride.setDefaultFont(this, "MONOSPACE", "calibri.ttf");
    FontsOverride.setDefaultFont(this, "SERIF", "calibri.ttf");
    FontsOverride.setDefaultFont(this, "SANS_SERIF", "calibri.ttf");
}

}
A class to override my fonts:
public final class FontsOverride {

public static void setDefaultFont(Context context,
                                  String staticTypefaceFieldName, String fontAssetName) {

    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

}
In my manifest:
<application
    android:allowBackup="true"
    android:name="utils.ApplicationCustom"

Like was suggested, i boot my device...nothing happened, the final result is the same..
Any clues?

A: basically if any devices theme overlapping your fonts than its not working because the device layer is come at last.you can reboot the device and than try it starts working ..because of boot theme will remove....


text:
Q: How to use Partial generic for rest parameters in typescript? Can anyone explain why the below code won't work ?
type D<P> = P extends unknown[] ? (...a: Partial<P>) => void : never;
// => A rest parameter must be of an array type.ts(2370)

But this line works:
type D<P extends unknown[]> = (...a: Partial<P>) => void;

And further, this one line won't work:
type D<P extends unknown[]> = P extends [unknown, ...unknown[]] ? (...a: Partial<P>) => void;
// A rest parameter must be of an array type.ts(2370)


text:
Q: how to calculate total time taken for multiple android webview? i have loaded multiple webviews in android , i know the timetaken for a webview loading is difference between "onPageStarted" and "onPageFinished". But i have multiple webview how to calculate total webviews loaded timetaken ?

A: class PerfIDs
{
    public long time;
    public String url;
    PerfIDs(long time, String url)
    {
        this.time = time;
        this.url = url;
    }
    public Long getUrl(String url) {
        return time;
    }
};

ArrayList<PerfIDs> appPerformanceTime = new ArrayList<PerfIDs>();
long startTime;
long endTime;
long firststartTime;
long lastendTime;
boolean startHold = true;
public void onPageStarted(WebView view, String url, Bitmap favicon) {
  startTime = System.currentTimeMillis();
  if(startHold){
    firststartTime = startTime;
    startHold = false;
  }
  appPerformanceTime.add(new PerfIDs(startTime,url));
  super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
  lastendTime = endTime = System.currentTimeMillis();
  int lastIndex = 0;
  for (int i = 0; i < appperftime.size(); i++) {
    String val = appperftime.get(i).url;
    if(url.equals(val)){
       System.out.println("url--"+url+"time-taken"+(endTime - appperftime.get(i).time));
       lastIndex = i;
     }
   }
if(lastIndex == appperftime.size()-1){
   System.out.println("total time taken --"+(lastendTime - firststartTime));
}
   super.onPageFinished(view, url);
}


text:
Q: Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and deleting stored procedures, triggers, constraints and all the dependencies in one SQL statement?
REASON FOR REQUEST:
I want to have a DB script for cleaning up an existing DB which is not in use rather than creating new ones, especially when you have to put in a request to your DB admin and wait for a while to get it done!

A: This is what I have tried:
SELECT 'DROP TABLE [' + SCHEMA_NAME(schema_id) + '].[' + name + ']' FROM sys.tables

What ever the output it will print, just copy all and paste in new query and press execute.
This will delete all tables.

A: Back up a completely empty database. Instead of dropping all the objects, just restore the backup.

A: this script cleans all views, SPS, functions PKs, FKs and tables.
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

A: To drop all tables:
exec sp_MSforeachtable 'DROP TABLE ?'

This will, of course, drop all constraints, triggers etc., everything but the stored procedures.
For the stored procedures I'm afraid you will need another stored procedure stored in master.

A: I accidentally ran a db init script against my master database tonight. Anyways, I quickly ran into this thread. I used the: exec sp_MSforeachtable 'DROP TABLE ?' answer, but had to execute it multiple times until it didn't error (dependencies.) After that I stumbled upon some other threads and pieced this together to drop all the stored procedures and functions.
DECLARE mycur CURSOR FOR select O.type_desc,schema_id,O.name
from
    sys.objects             O LEFT OUTER JOIN
    sys.extended_properties E ON O.object_id = E.major_id
WHERE
    O.name IS NOT NULL
    AND ISNULL(O.is_ms_shipped, 0) = 0
    AND ISNULL(E.name, '') <> 'microsoft_database_tools_support'
    AND ( O.type_desc = 'SQL_STORED_PROCEDURE' OR O.type_desc = 'SQL_SCALAR_FUNCTION' )
ORDER BY O.type_desc,O.name;

OPEN mycur;

DECLARE @schema_id int;
DECLARE @fname varchar(256);
DECLARE @sname varchar(256);
DECLARE @ftype varchar(256);

FETCH NEXT FROM mycur INTO @ftype, @schema_id, @fname;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sname = SCHEMA_NAME( @schema_id );
    IF @ftype = 'SQL_STORED_PROCEDURE'
        EXEC( 'DROP PROCEDURE "' + @sname + '"."' + @fname + '"' );
    IF @ftype = 'SQL_SCALAR_FUNCTION'
        EXEC( 'DROP FUNCTION "' + @sname + '"."' + @fname + '"' );

    FETCH NEXT FROM mycur INTO @ftype, @schema_id, @fname;
END

CLOSE mycur
DEALLOCATE mycur

GO

A: Try this
Select 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE

Select 'drop Procedure ' + specific_name  from Information_Schema.Routines where specific_name not like 'sp%' AND specific_name not like 'fn_%'

Select 'drop View ' + table_name  from Information_Schema.tables where Table_Type = 'VIEW'

SELECT 'DROP TRIGGER ' + name FROM sysobjects WHERE type = 'tr'

Select 'drop table ' + table_name  from Information_Schema.tables where Table_Type = 'BASE TABLE'

A: In addition to @Ivan's answer, types all need to be included
    /* Drop all Types */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TYPE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Type: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 AND [name] > @name ORDER BY [name])
END
GO

A: I'd do it in two statements: DROP DATABASE ???
and then CREATE DATABASE ???

A: I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo.
declare @n char(1)
set @n = char(10)

declare @stmt nvarchar(max)

-- procedures
select @stmt = isnull( @stmt + @n, '' ) +
    'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures

-- check constraints
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + ']    drop constraint [' + name + ']'
from sys.check_constraints

-- functions
select @stmt = isnull( @stmt + @n, '' ) +
    'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )

-- views
select @stmt = isnull( @stmt + @n, '' ) +
    'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views

-- foreign keys
select @stmt = isnull( @stmt + @n, '' ) +
    'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys

-- tables
select @stmt = isnull( @stmt + @n, '' ) +
    'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables

-- user defined types
select @stmt = isnull( @stmt + @n, '' ) +
    'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1

exec sp_executesql @stmt

Source: an Adam Anderson blog post

A: The best thing to do it is "Generate scripts for Drop"
Select Database -> Right Click -> Tasks -> Generate Scripts - will open wizard for generating scripts
after choosing objects in set Scripting option click Advanced Button

*

*-> Set option 'Script to create' to true (want to create)

*-> Set option 'Script to Drop' to true (want to drop)

*-> Select the Check box to select objects wish to create script

*-> Select the choice to write script (File, New window, Clipboard)

*It includes dependent objects by default.(and will drop constraint at first)
Execute the script
This way we can customize our script.

A: I tried some of the script here, but they didn't work for me, as I have my tables in schemas.  So I put together the following.  Note that this script takes a list of schemas, and drops then in sequence.  You need to make sure that you have a complete ordering in your schemas.  If there are any circular dependencies, then it will fail.
PRINT 'Dropping whole database'
GO

------------------------------------------
-- Drop constraints
------------------------------------------
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE ['+tc2.CONSTRAINT_SCHEMA+'].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

------------------------------------------
-- Drop views
------------------------------------------

DECLARE @sql VARCHAR(MAX) = ''
        , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(v.name) +';' + @crlf
FROM   sys.views v

PRINT @sql;
EXEC(@sql);
GO
------------------------------------------
-- Drop procs
------------------------------------------
PRINT 'Dropping all procs ...'
GO

DECLARE @sql VARCHAR(MAX) = ''
        , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + 'DROP PROC ' + QUOTENAME(SCHEMA_NAME(p.schema_id)) + '.' + QUOTENAME(p.name) +';' + @crlf
FROM   [sys].[procedures] p

PRINT @sql;
EXEC(@sql);
GO

------------------------------------------
-- Drop tables
------------------------------------------
PRINT 'Dropping all tables ...'
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

------------------------------------------
-- Drop sequences
------------------------------------------

PRINT 'Dropping all sequences ...'
GO
DECLARE @DropSeqSql varchar(1024)
DECLARE DropSeqCursor CURSOR FOR
SELECT DISTINCT 'DROP SEQUENCE ' + s.SEQUENCE_SCHEMA + '.' + s.SEQUENCE_NAME
    FROM INFORMATION_SCHEMA.SEQUENCES s

OPEN DropSeqCursor

FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql

WHILE ( @@FETCH_STATUS <> -1 )
BEGIN
    PRINT @DropSeqSql
    EXECUTE( @DropSeqSql )
    FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql
END

CLOSE DropSeqCursor
DEALLOCATE DropSeqCursor
GO

------------------------------------------
-- Drop Schemas
------------------------------------------

DECLARE @schemas as varchar(1000) = 'StaticData,Ird,DataImport,Collateral,Report,Cds,CommonTrade,MarketData,TypeCode'
DECLARE @schemasXml as xml = cast(('<schema>'+replace(@schemas,',' ,'</schema><schema>')+'</schema>') as xml)

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT sql = 'DROP SCHEMA ['+schemaName+']' FROM
(SELECT CAST(T.schemaName.query('text()') as VARCHAR(200)) as schemaName FROM @schemasXml.nodes('/schema') T(schemaName)) as X
JOIN information_schema.schemata S on S.schema_name = X.schemaName

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

A: You have to disable all triggers and constraints first.
EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"

EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"

After that you can generate the scripts for deleting the objects as
SELECT 'Drop Table '+name FROM sys.tables WHERE type='U';

SELECT 'Drop Procedure '+name FROM  sys.procedures WHERE type='P';

Execute the statements generated.

A: try this with sql2012 or above,
this will help to delete all objects by selected schema
DECLARE @MySchemaName VARCHAR(50)='dbo', @sql VARCHAR(MAX)='';
DECLARE @SchemaName VARCHAR(255), @ObjectName VARCHAR(255), @ObjectType VARCHAR(255), @ObjectDesc VARCHAR(255), @Category INT;

DECLARE cur CURSOR FOR
    SELECT  (s.name)SchemaName, (o.name)ObjectName, (o.type)ObjectType,(o.type_desc)ObjectDesc,(so.category)Category
    FROM    sys.objects o
    INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
    INNER JOIN sysobjects so ON so.name=o.name
    WHERE s.name = @MySchemaName
    AND so.category=0
    AND o.type IN ('P','PC','U','V','FN','IF','TF','FS','FT','PK','TT')

OPEN cur
FETCH NEXT FROM cur INTO @SchemaName,@ObjectName,@ObjectType,@ObjectDesc,@Category

SET @sql='';
WHILE @@FETCH_STATUS = 0 BEGIN
    IF @ObjectType IN('FN', 'IF', 'TF', 'FS', 'FT') SET @sql=@sql+'Drop Function '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('V') SET @sql=@sql+'Drop View '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('P') SET @sql=@sql+'Drop Procedure '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('U') SET @sql=@sql+'Drop Table '+@MySchemaName+'.'+@ObjectName+CHAR(13)

    --PRINT @ObjectName + ' | ' + @ObjectType
    FETCH NEXT FROM cur INTO @SchemaName,@ObjectName,@ObjectType,@ObjectDesc,@Category
END
CLOSE cur;
DEALLOCATE cur;
SET @sql=@sql+CASE WHEN LEN(@sql)>0 THEN 'Drop Schema '+@MySchemaName+CHAR(13) ELSE '' END
PRINT @sql
--EXECUTE (@sql)

A: Here I found new query to delete all sp,functions and triggers
declare @procName varchar(500)
declare cur cursor

for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
    exec('drop procedure ' + @procName)
    fetch next from cur into @procName
end
close cur
deallocate cur

A: To add to Ivan's answer, I have also had the need to drop all user-defined types, so I have added this to the script:
/* Drop all user-defined types */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (select TOP 1 [name] from sys.types where is_user_defined = 1)

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TYPE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Type: ' + @name
    SELECT @name = (select TOP 1 [name] from sys.types where is_user_defined = 1)
END
GO

A: To remove all objects in oracle :
1) Dynamic
DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE'
AND OWNER='SCHEMA_NAME';
 CURSOR IY IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND  OWNER='SCHEMA_NAME';
 CURSOR IZ IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND  OWNER='SCHEMA_NAME';
BEGIN
 FOR X IN IX LOOP
   EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' '||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
 END LOOP;
 FOR Y IN IY LOOP
   EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' '||Y.OBJECT_NAME);
 END LOOP;
 FOR Z IN IZ LOOP
   EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' '||Z.OBJECT_NAME||' FORCE ');
 END LOOP;
END;
/

2)Static
    SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
        union ALL
        select 'drop '||object_type||' '|| object_name || ';' from user_objects
        where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
        union ALL
        SELECT 'drop '
        ||object_type
        ||' '
        || object_name
        || ' force;'
        FROM user_objects
        WHERE object_type IN ('TYPE');

A: One more sample
declare @objectId int,  @objectName varchar(500), @schemaName varchar(500), @type nvarchar(30), @parentObjId int, @parentObjName nvarchar(500)
declare cur cursor
for

select obj.object_id, s.name as schema_name, obj.name, obj.type, parent_object_id
from sys.schemas s
    inner join sys.sysusers u
        on u.uid = s.principal_id
        JOIN
        sys.objects obj on obj.schema_id = s.schema_id
WHERE s.name = 'schema_name' and (type = 'p' or obj.type = 'v' or obj.type = 'u' or obj.type = 'f' or obj.type = 'fn')

order by obj.type

open cur
fetch next from cur into @objectId, @schemaName, @objectName,  @type, @parentObjId
while @@fetch_status = 0
begin
    if @type = 'p'
    begin
        exec('drop procedure ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'fn'
    begin
        exec('drop FUNCTION ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'f'
    begin
        set @parentObjName = (SELECT name from sys.objects WHERE object_id = @parentObjId)
        exec('ALTER TABLE ['+@schemaName +'].[' + @parentObjName + ']' + 'DROP CONSTRAINT ' +  @objectName)
    end

    if @type = 'u'
    begin
        exec('drop table ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'v'
    begin
        exec('drop view ['+@schemaName +'].[' + @objectName + ']')
    end
    fetch next from cur into  @objectId, @schemaName, @objectName,  @type, @parentObjId
end
close cur
deallocate cur

A: There is no single statement that can be used to achieve this aim.
You could of course create yourself a stored procedure that you could use to perform these various administrative tasks.
You could then execute the procedure using this single statement.
Exec sp_CleanDatabases @DatabaseName='DBname'

A: try this....
USE DATABASE
GO
DECLARE @tname VARCHAR(150)
DECLARE @strsql VARCHAR(300)

SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' and [name] like N'TableName%' ORDER BY [name])

WHILE @tname IS NOT NULL
BEGIN
    SELECT @strsql = 'DROP TABLE [dbo].[' + RTRIM(@tname) +']'
    EXEC (@strsql)
    PRINT 'Dropped Table : ' + @tname
    SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' AND [name] like N'TableName%'  AND [name] > @tname ORDER BY [name])
END

A: Seems like a rather dangerous feature to me. If you'd implement something like this I would make sure to properly secure it in a way you won't be able to run this per accident.
As suggested before you could make some sort of stored procedure yourself.
In SQL Server 2005 you could have a look this system table to determine and find the objects you would like to drop.
select * from sys.objects

A: DECLARE @name VARCHAR(255)
DECLARE @type VARCHAR(10)
DECLARE @prefix VARCHAR(255)
DECLARE @sql VARCHAR(255)

DECLARE curs CURSOR FOR
SELECT [name], xtype
FROM sysobjects
WHERE xtype IN ('U', 'P', 'FN', 'IF', 'TF', 'V', 'TR') -- Configuration point 1
ORDER BY name

OPEN curs
FETCH NEXT FROM curs INTO @name, @type

WHILE @@FETCH_STATUS = 0
BEGIN
-- Configuration point 2
SET @prefix = CASE @type
WHEN 'U' THEN 'DROP TABLE'
WHEN 'P' THEN 'DROP PROCEDURE'
WHEN 'FN' THEN 'DROP FUNCTION'
WHEN 'IF' THEN 'DROP FUNCTION'
WHEN 'TF' THEN 'DROP FUNCTION'
WHEN 'V' THEN 'DROP VIEW'
WHEN 'TR' THEN 'DROP TRIGGER'
END

SET @sql = @prefix + ' ' + @name
PRINT @sql
EXEC(@sql)
FETCH NEXT FROM curs INTO @name, @type
END

CLOSE curs
DEALLOCATE curs


text:
Q: Date not being displayed in title Could anyone tell me why the date is not being shown in the title of my document. The document class is proc. If I remove \date{\today} my title moves down a return, but no date is displayed when I leave it in.
\title{Title}
\author{Me\\
        Email\\}
\date{\today}
\maketitle

A: This may be due to the definition of \maketitle not containing date. So, you might want to check out where you have \def\@maketitle (it may be in your style file/document class). After finding the definition, you can insert date into it.
The proc document class doesn't typeset the date in \maketitle:
\def\@maketitle{%
  \vbox to 2.25in{%
    \hsize\textwidth
    \linewidth\hsize
    \vfil
    \centering
    {\LARGE \@title \par}
    \vskip 2em
    {\large \begin{tabular}[t]{c}\@author \end{tabular}\par}
    \vfil}}

Contrast it with the article document class:
\def\@maketitle{%
  \newpage
  \null
  \vskip 2em%
  \begin{center}%
  \let \footnote \thanks
    {\LARGE \@title \par}%
    \vskip 1.5em%
    {\large
      \lineskip .5em%
      \begin{tabular}[t]{c}%
        \@author
      \end{tabular}\par}%
    \vskip 1em%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
    {\large \@date}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \end{center}%
  \par
  \vskip 1.5em}


text:
Q: Qt управление процессом пинга Доброго времени суток.
Возник вопрос, каким образом можно организовать на C++ (Qt) управление процессом пинга. При помощи QProcess::execute я запускаю ping с параметром -t, и пингую сервер. Проблема в том, что я не знаю, когда именно он ответит на пинг, и, соответственно, мне нужно организовать приём ответных ICMP пакетов, и, помимо этого, как-то отправлять команду остановки процесса пингования. Каким образом это следует организовать? Открыть udp сокет, поймать пакет и убить процесс PING.EXE? Или это можно сделать как-то попроще?


text:
Q: Perspective image of a rectangle
The image above shows a perspective image of a rectangle, taken by a pinhole camera that is pointed to the center of the rectangle (This means that the axis of the pinhole camera is assumed to pass through the center of the viewed rectangle, or equivalently that the line connecting the center of the rectangle and its image is perpendicular to the viewing plane).
If the side length $\overline{AB}$ is known to be $6$ units, can we find the side length $\overline{BC}$ ?
Additionally, assume that in the image $AB$ is not parallel to $CD$ and $BC$ is not parallel to $AD$.

A: Let $ABCD$ be the ordered vertices of the given quadrilateral, $O$ the intersection point of its diagonals and $V$ the position of the point of view (i.e. the pinhole), which lies on the perpendicular through $O$ to plane $ABCD$. We also know that line $VO$ passes through the centre of a rectangle $A'B'C'D'$ whose vertices lie on the rays opposite to $VA$, $VB$, $VC$, $VD$.
Choose any $A'$ on the ray opposite to $VA$, for instance:
$$
A'=2V-A.
$$
Then it is easy to show that the midpoint $M$ of $A'C'$ lies on line $VO$ only if
$$
C'=V+{1\over k}(V-C),
\quad\text{where}\quad
k={OC\over OA}.
$$
Proof. Point $C'$ lies on line $CO$, hence there exists $t$ such that $C'=V+t(V-C)$. On the other hand $C=O+k(O-A)$, hence:
$$
M={A'+C'\over2}={(3+t)V-A-tC\over2}=
{(3+t)V-t(1+k)O+(tk-1)A\over2}.
$$
But $M$ lies on line $VO$ only if $M=\alpha O+(1-\alpha) V$ for some real number $\alpha$. And this is the case only if $tk-1=0$. Plugging then $t=1/k$ into the expression for $C'$ we obtain the desired result. $\square$
In an analogous way, one can prove that $M$ is also the midpoint of $B'D'$ if:
$$
B'=V + {m (1 + k)\over k(1 + m)} (V - B),\quad
D'= V + {1 + k\over k(1 + m)}(V-D),\quad
\text{where}\
m={OD\over OB}.
$$
The quadrilateral $A'B'C'D'$ so constructed is a parallelogram, but not necessarily a rectangle. We get a rectangle by imposing a further condition, for instance $A'C'=B'D'$. This gives a quadratic equation in the unknown $z=OV$, which can then be solved: two solutions are possible, on either side of plane $ABCD$.
Once $V$ is found one can compute the sides of rectangle $A'B'C'D'$: a simple proportion will then give you the unknown side of the original rectangle.

EXAMPLE.
Let's take for simplicity $ABCD$ in the $xy$ plane in such a way that $O=(0,0,0)$:
$$
A=(-2, -2, 0),\
B=(1, -4, 0),\
C=(3, 3, 0),\
D=(-1, 4, 0),\
V=(0,0,z).
$$
We then have $k=3/2$, $m=1$ and:
$$
A'=(2, 2, 2z),\
B'=\left(-{5\over6}, {10\over3}, {11\over6}z\right),\
C'=\left(-2, -2, {5\over3}z\right),\
D'=\left({5\over6},-{10\over3}, {11\over6}z\right).
$$
Equation $A'C'=B'D'$ boils down to $z^2=137$, that is $z=\pm\sqrt{137}$. We can then compute:
$$
A'B'={7\over3}\sqrt{5\over2},\quad
B'C'={11\over3}\sqrt{5\over2}.
$$
If the real length of $A'B'$ is $6$, a simple proportion will then give the real length of $B'C'$ as $\displaystyle{66\over7}$.
EDIT.
Tinkering a bit with Mathematica I could find a simple formula for $z=OV$:
$$
z^2={ (1 + k)^2 m^2 OB^2-k^2 (1 + m)^2 OA^2
\over (k - m) (k m-1)}.
$$
Of course if the right hand side turns out to be negative then no real solution exists.

A: I'm not an expert on this, but given it a thought I think the following should be right. I can always delete :-|
Assume your object is centered at the origin, and your camera is always looking to the origin at a distance $r$ and with angles $\varphi$ and $\theta$ (spherical coordinates, ISO 80000-2:2019 convention). For the pinhole of the camera we then have $P_{pin}=(x_{pin}, y_{pin}, z_{pin})$:
$$
x_{pin} = r\sin(\theta)\cos(\varphi)\\
y_{pin} = r\sin(\theta)\sin(\varphi)\\
z_{pin} = r\cos(\theta)
$$
The projection is realized by a vector from the object, through the pinhole, onto a plane perpendicular to the viewing vector. Let's put that plane at distance $f$ behind the camera pinhole. The projection plane point where the origin is projected is then given by $P_{pl}=(x_{pl}, y_{pl}, z_{pl})$:
$$
x_{pl} = (r+f)\sin(\theta)\cos(\varphi)\\
y_{pl} = (r+f)\sin(\theta)\sin(\varphi)\\
z_{pl} = (r+f)\cos(\theta)
$$
So we can regard $P_{pl}$ as the normal on the plane, and for every projection point $P_{pr}$ on the plane the vector dot product (relative to $P_{pl}$) with the normal is zero:
$$
(P_{pl}, P_{pr}-P_{pl})=0
$$
which we can simplify as
$$
(P_{pl}, P_{pr})-(P_{pl}, P_{pl})=(P_{pl}, P_{pr})-(r+f)^2=0
$$
A point on your object $P_o=(x_o,y_o,z_o)$ follows a path to the pinhole as follows:
$$
V(\mu)=P_o+\mu(P_{pin}-P_o), \quad 0 \leq \mu \leq 1
$$
and for a certain $\mu>1$ it hits the projection plane in some $V(\mu)=P_{pr}$. So:
$$
(P_{pl}, P_{pr})-(r+f)^2=0\\
(P_{pl}, P_o+\mu(P_{pin}-P_o))-(r+f)^2=0
$$
Work out a bit:
$$
(P_{pl}, P_o)+\mu(P_{pl}, P_{pin}-P_o)=(r+f)^2\\
\mu=\frac{(r+f)^2-(P_{pl}, P_o)}{(P_{pl}, P_{pin}-P_o)}
$$
We can write:
$$
(P_{pl}, P_{pin}-P_o)=(P_{pl}, P_{pin})-(P_{pl}, P_o)
$$
Because $P_{pl}$ and $P_{pin}$ are the 'same' vector but with different length we get:
$$
(P_{pl}, P_{pin})=r(r+f)
$$
Substitute:
$$
\mu=\frac{(P_{pl}, P_o)-(r+f)^2}{(P_{pl}, P_o)-r(r+f)}
$$
So for every object point (put your rectangle in the xy-plane...), every camera position and focal distance $f$ you can calculate the corresponding 3D projection point $V(\mu)$. From that it is easy to calculate the distances between the projected points.
If you have a projection, and the observation location of the camera, then give the actual rectangle points like $(-h/2,-w/2,0)$, $(-h/2,+w/2,0)$, $(+h/2,-w/2,0)$, $(+h/2,+w/2,0)$ in the xy-plane, then calculate the 4 corresponding projection points $V(\mu)$ according to the above scheme (keep $h$ and $w$ as variables), and then you have a set of 4 projection points expressed in $w$ and $h$. Make them equal to the actual 4 projection points to find the size of the original rectangle.
In fact the 6 variables in the model are $(\theta,\varphi,r,f,w,h)$, whereas you will have 4 projection points. So you need only to know 2 of the 6 at forehand in order to calculate the remaining 4.


text:
Q: Inserting items into bootstrap-dropdown from SQL Table I am working on asp.net project and my code behind language is c#. I have one bootstrap dropdown in which i want to get the items from SQL Table. is there anyone who will help me in this regard. thanks in advance.

        Category

        Action
        Another action
        Something else here

Action, Another Action and Something else items should come from database (Category) Table. Using c# language on server side is much appreciable.

A: There are some ways to do it in WebForms, but first you need to make the DIV element of the dropdown menu accessible from the Code Behind.
See this snippet?

            Category

Note that I added 2 attributes : id="myDropdownMenu" and runat="server".
After this you can go to Code Behind to start populating the menu from a data source.
At least there are 2 ways to do this, as far as I know.
By manipulating the InnerHtml property, like this :
    private void DisplayMenuByConstructingHtmlTags(List<string> menuList)
    {
        var menuHtml = "";

        foreach (string menuText in menuList)
        {
            menuHtml += "" + menuText + "\n";
        }

        myDropdownMenu.InnerHtml = menuHtml;
    }

Or, by adding the menu as the child controls, like this :
    private void DisplayMenuByAddingChildControls(List<string> menuList)
    {
        foreach (string menuText in menuList)
        {
            var linkMenu = new HyperLink() { CssClass = "dropdown-item", NavigateUrl = "#", Text = menuText };
            myDropdownMenu.Controls.Add(linkMenu);
        }
    }

It's your call, which one to choose.
Btw, just to complete this example, you may try to call one of those methods from the Page_Load event, like this :
EDIT :
By your request, I've modified the samples by adding a connection to a table in a database. So, this is the module to load the data :
    private List<string> LoadMenuFromTable()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ToString();

        var retVal = new List<string>();
        using (var connection = new SqlConnection(connectionString))
        {
            using (var cmd = new SqlCommand("SELECT menu_text FROM Table_1", connection))
            {
                connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        retVal.Add((string)reader["menu_text"]);
                    }
                }
            }
        }
        return retVal;
    }

And here's how you should call the module :
    protected void Page_Load(object sender, EventArgs e)
    {
        var menu = LoadMenuFromTable();

        DisplayMenuByAddingChildControls(menu);
        // or DisplayMenuByConstructingHtmlTags(menu);
    }

Oh, and remember to import these two libraries to make this sample works :
using System.Configuration;
using System.Data.SqlClient;

Hope it helps.


text:
Q: Yii Select Using Custom Field Im trying to use a custom field to create another custom field, but Im getting error.
I created that sample code to be easier to understand.
Model.php:
public custom1;
public custom2;

Example Code:
...
$criteria->select=array("'custom1' AS custom1, CONCAT('variable: ', custom1) AS custom2");
...

Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'custom1' in 'field list'.

A: Well, because you use function in select it have to use with CDbExpression:
$criteria->select = array(
  new CDbExpression('custom as custom1'),
  new CDbExpression('CONCAT("variable: ", custom) AS custom2'),
);


text:
Q: Thor subcommands in different gems I've seen several examples of subcommands in Ruby but haven't found any yet that use Thor, I guess it's possible that it can't be done but I'd be surprised. What I'm trying to do is have a program foo that has it's own gem and when installed its commands can be called the usual way, and then I want a separate gem bar that registers with foo, is maintained in another repository, but gets installed such that I can call it using foo bar.
From what I can tell from the Thor documentation in order for foo to be aware of bar it would need to do this:
desc "bar ...", "do bar"
subcommand "bar", Bar

But I don't want foo to have to know about bar and for it to just load it when it's called. I don't really understand how to control how gems are installed so that might be the answer, possibly subcommands need to follow some install rules and the parent command does a generic load of that path. Any chance there's an amazing example out there that I can be pointed at?

A: This is not how thor works. Using foo and bar, what you would have is a module foo with a class Cli that inherits from Thor ie
class Cli < Thor

Within your Cli class you would define a method bar
Something like
module foo
  class Cli < Thor
    desc 'bar', 'do stuff'
    def bar
      # all the rad stuff I do
    end
   end
 end

You would then build and install a single gem foo which would be available after you rbenv rehash. Once available
$ foo bar arg1="bang" arg2="boom"

will do all of the rad stuff you told it to do.
You can also write your commands in separate files. You might have a lib structure as follows:
lib
| - foo.rb
| - foo
| | cli
| | - bar_cli.rb
| | - baz_cli.rb

In foo.rb
module Foo
  module Cli
    require_relative 'cli/bar_cli'
    require_relative 'cli/baz_cli'
  end

  class FooCli < Thor
    register(Foo::BarCli, 'bar', 'bar', 'bar commands')
    register(Foo::BazCli, 'baz', 'baz', 'baz commands')
  end
end

In bar_cli.rb
 module Foo
   class BarCli < Thor
     desc 'display', 'Display the bar'
     def display
      # bar display stuff
    end
  end
end

A: 1. No problem with Thor
Let's have a gem foo, providing just a single executable of the same name foo, of these contents:
require 'thor'

class FooCli < Thor
  desc 'hello', 'print a salutation'
  def hello
    puts 'hello'
  end
end

FooCli.start ARGV

If I execute it I get output like this
Commands:
  foo.rb hello           # print a salutation
  foo.rb help [COMMAND]  # Describe available commands or one specific command

There is no problem with adding new subcommands to the executable in code outside of the foo gem. Let's have another gem bar, providing just a single "library" file of the same name bar(.rb), of these contents:
require 'thor'

class BarCli < Thor
  desc 'hi', 'print another salutation'
  def hi
    puts 'hi'
  end
end

# Reopen the FooCli class and add the new subcommand
class FooCli < Thor
  desc 'bar', 'subcommand added by the foo-bar plugin'
  subcommand 'bar', BarCli
end

The only real issue is how to have bar loaded when executing the foo command.
2. Addressing the issue with code loading
2.0 Manual solution
Let's start by loading bar manually, using the -r option of the ruby interpreter:
$ ruby -r bar path/to/foo
Commands:
  foo.rb bar             # subcommand added by the foo-bar plugin
  foo.rb hello           # print a salutation
  foo.rb help [COMMAND]  # Describe available commands or one specific command

We can see that the code in bar.rb took effect. Since it was loaded before foo itself (that's how the -r option works), the bar subcommand appears in the command listing before the standard foo subcommands.
A part of our mission is completed: foo knows nothing about bar, but bar managed to add a subcommand to foo. An obvious downside is that the user has to explicitly mention bar on each invocation of foo (and refer to foo by it's full filesystem path, which is also ... not very convenient.)
2.1 Plugin system with configuration
The loading of bar won't work "magically" out of the box whenever the gem is available, but the users of foo will have to specify somewhere (e.g. in a configuration file) that bar is to be loaded whenever executing foo, and you will add to foo a piece of code loading the configuration file and subsequently requiring the plugins specified there.
This has one downside common with the initial solution discussed above: loading of bar requires a user intervention, but in this case the intervention is at least required only "once in a lifetime", not on every invocation.
2.2 Gem naming magic
If you really want to have bar loaded automatically, whenever it's available, but without foo having to know (specifically) about it, you can use RubyGems facilities for inspecting installed gems in combination with a naming convention. The bar gem won't be called bar, but foo-bar, the new name signifying that it's an extension of foo, and the foo executable will contain an additional piece of code looking for all gems whose name starts with foo- and loading them:
Gem::Specification
  .select {|gemspec| gemspec.name =~ /^foo-/ }
  .collect(&:name)
  .uniq # multiple versions of a single gem may be installed at once
  .each {|name| require name }

This solution, too, has a downside: if your gem is intended for general use and released at Rubygems, you have no control over people creating gems with names starting with foo-. Thus, while trying to automagically load all foo plugins, you may load and execute third-party code you have never wanted to. Even worse, if such a problem occurs, the user of foo, even if he is fortunate enough to understand what's going on, has no other way to prevent loading the offending foo-* gem but uninstalling it.


text:
Q: Ordinary differential equation, IVP using matrix method When I solve a problem of the type $x' = Ax, x(0) = x_0$, where $A$ is a matrix and $x$ is a vector, I typically follow this method:
I compute $\det(A-\lambda I)$ and find the roots and their multiplicity, and then using these eigenvalues $\lambda_i$, I find vectors $v_1, v_2, v_3$ that constitute a basis for $\mathbb{R}^3$. And then, usually, there will be some relationship between the vectors and the initial condition, e.g. $x_0 = -v_1 + v_2$, or something similar of course depending on the initial condition and the vectors in question. Then, staying with the example $x_0 = -v_1 + v_2$, I put $x(t) = -e^{tA}v_1 + e^{tA}v_2$, where $e^{tA} = e^{\lambda_i t}$ for the corresponding eigenvalues.
But I recently came across a case where one thing was a little different. In this case $x_0 = v_1 - 2v_2$, so that $x(t) = e^{tA}v_1 - 2e^{tA}v_2$, but then I was supposed to put $e^{tA}v_2 = e^{\lambda t}(I + t(A-\lambda I))v_2$. I have not been able to figure out the reason for this and I'm hoping someone here has an idea of what is going on.


text:
Q: SortedDictionary in c I am trying to use the following code (written in C#) in C++
SortedDictionary<object[], int> test =
                                    new SortedDictionary<object[], int>(new Comparer());

Is it possible to use SortedDictionary in C++, or are there any alternatives that will allow me to have more or less the same functionality without making too much change to the rest of my codebase?

A: Sounds like you need to get familiar with STL! I think STL map would do?

A: You are looking for std::map.

A: As reading from your comments it looks you want to use System::Collections::Generic::SortedDictionary from C++ CLI. You can more or less use it the same was as you're doing in c#.


text:
Q: ElasticSearch - How to get the source reference for each fragment highlighted I would like to get the reference (it means the full object I see in the _source) from where each fragment highlighted originates.
Example :

*

*Table = article

*Columns = id, label, content

I would like to know for each fragments highlighted what is the id.
My ElasticSearch request :
GET /sa/_search
    {
      "query" : {
        "bool" : {
          "should" : {
            "multi_match" : {
              "query" : "oasis",
              "fields" : [ "label", "content" ]
            }
          }
        }
      },
      "highlight" : {
        "order" : "score",
        "fields" : {
          "label" : { },
          "content" : {
            "fragment_size" : 250
          }
        }
      }
    }

Currently, with this request, I have only the fragment hightlighted, but I can't know which fragment is link to which id.
Does somebody has any idea to that ?


text:
Q: Is their a way to split a single 2d array into multiple 1d arrays of various shapes using the 1st column as an index? I'm trying to split a 2d numpy array into multiple 1d arrays of the 2nd column using the first column as an index. the 2d array is very large (2,100000)
basically i have an array that looks like this (just a lot larger):
[[1,a]
 [1,a2]
 [1,a3]
  ....
 [100,b]
 [100,b2]]

I want to split it into two arrays that look like
[a,a2,a3]

and
[b,b2]

I'm not even sure on where to start or search and would greatly appreciate any help

A: You're looking for itertools.groupby. You need to specify a key function, which specifies how to group the elements in your nested list (in this case, by the first element). In this case, we can use itemgetter.
Per your requirements, you only want each group to contain the second element of the original data, so itemgetter can help there too.
from itertools import groupby
from operator import itemgetter

data = [[1, 'a'],
        [1, 'b'],
        [1, 'c'],
        [2, 'a'],
        [2, 'b'],
        [3, 'c']]

result = {key: list(map(itemgetter(1), group)) for key, group in groupby(data, key=itemgetter(0))}

print(result)

Output:
{1: ['a', 'b', 'c'], 2: ['a', 'b'], 3: ['c']}

Note that you should sort the input nested list first if the keys are not already in order, otherwise they will be split into multiple groups with the same key.

A: You can use np.flatnonzero (or np.nonzero or np.where) and np.diff to find the block boundaries and then split using np.split:
# create example
x = np.c_[np.repeat(*sum(np.ogrid[:2, 1:4])), 1:10]
x
# array([[1, 1],
#        [1, 2],
#        [2, 3],
#        [2, 4],
#        [2, 5],
#        [3, 6],
#        [3, 7],
#        [3, 8],
#        [3, 9]])
np.split(x[:, 1], np.flatnonzero(np.diff(x[:, 0])) + 1)
# [array([1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]


text:
Q: Python Dash Table - How to embed href behind cell value Dash table
Hi,
How can I embed the links into the product name columns so I can remove the link column?
I'd like to access the links by clicking on the product name.
Any help would be greatly appreciated.

A: This is what I would do. I will first drop the Link column. Assuming df is your data.
df_drop_link = df.drop(columns='Link')

html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df_drop_link.columns])] +

        # Body
        [html.Tr([
            html.Td(df.iloc[i][col]) if col != 'Product Name' else html.Td(html.A(href=df.iloc[i]['Link'], children=df.iloc[i][col], target='_blank')) for col in df_drop_link.columns
        ]) for i in range(len(df))]
    )


text:
Q: How explain this step in application of binomial expansion for commutative matrices I am trying to show that for two commuting matrices
$$
e^{\mathbf{A} + \mathbf{B}} = e^{\mathbf{A}}e^{\mathbf{B}} \Leftarrow [\mathbf{A}, \mathbf{B}] = 0
$$
Using the definition of the matrix exponential
$$
e^{\mathbf{A}} = \sum_{n=0}^{\infty} \frac{\mathbf{A}^n}{n!}
$$
I am able to get
$$
e^{\mathbf{A}}e^{\mathbf{B}} = \sum_{n=0}^{\infty} \frac{1}{n!} \sum_{k=0}^{\infty} \frac{n!}{k!n!} \mathbf{A}^{n}\mathbf{B}^{k}
$$
The binomial expansion for commutative matrices is
$$
\sum_{i=0}^{\infty} \frac{p!}{i!(p-i)!} \mathbf{A}^{p}\mathbf{B}^{p-i} = (\mathbf{A+B})^p
$$
I have been staring at the last two equations for hours now. I clearly see the similarity between the expressions, but I cannot see how I can change the summation indexes correctly so that I can make the substitution into equation 3.
Solution using the Cauchy product formula
Starting over, and using the relation from Omnomnomnom's answer, we get that
$$
\begin{align}
e^{\mathbf{A}}e^{\mathbf{B}} &= \left( \sum_{j=0}^{\infty} \frac{1}{j!}\mathbf{A}^j \right)\left( \sum_{k=0}^{\infty} \frac{1}{k!}\mathbf{B}^k \right) \\
&=  \sum_{j=0}^{\infty} \sum_{k=0}^{\infty} \frac{1}{j!k!} \mathbf{A}^j\mathbf{B}^k \\
&= \sum_{n=0}^{\infty} \sum_{m=0}^{n} \frac{1}{m!(n-m)!}\mathbf{A}^n\mathbf{B}^{n-m} \\
&= \sum_{n=0}^{\infty} \frac{1}{n!} \sum_{m=0}^{n} \frac{n!}{m!(n-m)!}\mathbf{A}^n\mathbf{B}^{n-m} \\
&= \sum_{n=0}^{\infty} \frac{1}{n!} (\mathbf{A}+\mathbf{B})^n \\
&= e^{\mathbf{A}+\mathbf{B}}
\end{align}
$$

A: Hint: With the Cauchy product formula, we have
$$
\left(\sum_{j=0}^\infty \frac{1}{j!}A^j\right)\left( \sum_{k=0}^\infty \frac 1{k!} B^k\right) = \sum_{n=0}^\infty \sum_{m=0}^n \frac {1}{m!(n-m)!} A^mB^{n-m}.
$$


text:
Q: Python Datatype for a fixed-length FIFO I would like to know if there is a native datatype in Python that acts like a fixed-length FIFO buffer.  For example, I want do create a length-5 FIFO buffer that is initialized with all zeros.  Then, it might look like this:
[0,0,0,0,0]
Then, when I call the put function on the object, it will shift off the last zero and put the new value, say 1, into the left side:
[1,0,0,0,0]
If I put a 2, it would then shift and put to look like this:
[2,1,0,0,0]
...and so on.  The new value goes at the front and the oldest one is shifted off.  I understand that this would be very easy to implement myself, but I would like to use native python datatypes if at all possible.  Does anyone know which datatype would be best for this?

A: Just one more example to this post
from collections import deque

domains = ['1.com','2.com','3.com']
d = deque(domains)
d.pop() #pop(delete) 3.com here
d.appendleft('new.com')

print d

result:
deque(['new.com', '1.com', '2.com'])

A:
test_queue = deque([0]*5,maxlen=5)

for i in range(10):
    print(i)
    test_queue.appendleft(i)
    print(list(test_queue))

prints:
[0, 0, 0, 0, 0]
1
[1, 0, 0, 0, 0]
2
[2, 1, 0, 0, 0]
3
[3, 2, 1, 0, 0]
4
[4, 3, 2, 1, 0]
5
[5, 4, 3, 2, 1]
6
[6, 5, 4, 3, 2]
7
[7, 6, 5, 4, 3]
8
[8, 7, 6, 5, 4]
9
[9, 8, 7, 6, 5]

A: you can also use list
a = [0,0,0,0,0]

a.pop(0)
a.append(1)

print a
result [0,0,0,0,1]

or for left side in right out, otherwise
a.pop(5)
a.insert(0,1)
print a
result [1,0,0,0,0]

A: x = collections.deque(5*[0], 5)

See the docs for more about collections.deque; the method you call push is actually called appendleft in that type.
The second parameter (maxlen, giving the maximum lengths) was added in Python 2.6; if you're using older versions of Python, it won't be available.


text:
Q: overlapping date intervals with gaps I have been trying to find an elegant data.table solution (but I will take another if there is something better) on how to combine date intervals that deals with (1) nested intervals, (2) intervals with varying priorities, and (3) intervals with gaps (see example input object). I managed to find a nearly successful solution via foverlaps and shift. I am hoping to avoid for/while loops or cartesian products, both which are inefficient and inelegant, but will definitely work. I am hoping that there is something better since this is a common data issue I must deal with. Upon request, I will show my nearly effective solution, if that would be useful.
require(data.table)
# my data looks somewhat like this...
input <- data.table(
  person_ID = c(rep(98723, 4), rep(8534, 2), 11223, rep(22446, 2)),
  team = c(rep("A", 4), rep("B", 2), "A", "B", "A"),
  start_date = as.Date(c("2009-10-1", "2011-11-21", "2012-1-23", "2013-3-2",
    "2009-11-14", "2010-1-1", "2012-1-2", "2011-2-2", "2012-4-3")),
  end_date = as.Date(c("2010-5-23", NA, "2015-01-02", "2013-3-2", "2009-12-31",
    "2010-3-1", "2015-03-22", "2016-1-2", "2014-9-30")))
team_priority <- data.table(team = c("A", "B"), priority = c(1, 2))
input[team_priority, priority := i.priority, on = "team"]

input
  person_ID team start_date   end_date priority
1:     98723    A 2009-10-01 2010-05-23        1
2:     98723    A 2011-11-21       <NA>        1
3:     98723    A 2012-01-23 2015-01-02        1
4:     98723    A 2013-03-02 2013-03-02        1
5:      8534    B 2009-11-14 2009-12-31        2
6:      8534    B 2010-01-01 2010-03-01        2
7:     11223    A 2012-01-02 2015-03-22        1
8:     22446    B 2011-02-02 2016-01-02        2
9:     22446    A 2012-04-03 2014-09-30        1
# problem 1: gap in teams prevents simple min/max solution (see person_ID == 98723)

# problem 2: teams have priorities, so if team B is inside of time interval assigned to time A,
# then we need the records to reflect the following:
# team B -> team A -> team B based on when teams A & B start/stop (see person_ID == 22446)

# NOTE: problem 1 and 2 can be combined (I am trying to fix bad data entry)

# I have to assign priorities based on team involvement (A > B > C, etc)
output <- data.table(
  person_ID = c(rep(98723, 4), rep(8534, 2), 11223, rep(22446, 3)),
  team = c(rep("A", 4), rep("B", 2), "A", "B", "A", "B"),
  start_date = as.Date(c("2009-10-1", "2011-11-21", "2012-1-23", "2013-3-2",
    "2009-11-14", "2010-1-1", "2012-1-2", "2011-2-2",  "2012-4-3", "2014-10-1")),
  end_date = as.Date(c("2010-5-23", NA, "2015-01-02", "2013-3-2", "2009-12-31",
    "2010-3-1", "2015-03-22", "2012-4-2", "2014-9-30", "2016-1-2")),
  group_id = c(1, rep(2, 3), rep(4, 2), 5, 6, 7, 8))

output
    person_ID team start_date   end_date group_id
 1:     98723    A 2009-10-01 2010-05-23        1
 2:     98723    A 2011-11-21       <NA>        2
 3:     98723    A 2012-01-23 2015-01-02        2
 4:     98723    A 2013-03-02 2013-03-02        2
 5:      8534    B 2009-11-14 2009-12-31        4
 6:      8534    B 2010-01-01 2010-03-01        4
 7:     11223    A 2012-01-02 2015-03-22        5
 8:     22446    B 2011-02-02 2012-04-02        6
 9:     22446    A 2012-04-03 2014-09-30        7
10:     22446    B 2014-10-01 2016-01-02        8

A simple MIN/MAX solution will not work! I am not opposed to dealing with the nested intervals (see person_id == 22446) separately, but that is indeed the part I have been unable to figure out while still getting all the other goals met at the same time.

A: There might be other ways to do this more efficiently. But I think this is better than nothing. If someone comes along with something better, awesome, I would happily choose their response. Perhaps I should have made this more palatable by breaking it up into sections, but if I had known what sections, I would not have had to ask in the first place. :) Anyway, here is my solution, I will make it more polished since it will go in my R package, but this at least answers the question in all the ways I have tested so far.
I had to break my wishes in that parts of this have for loops and one part of this makes use of a cartesian product. I could not think a way to avoid them (yet).
overlap_combine <-
  function(overlap_dt, id_cols, team_col, start_col, end_col, overlap_int = 1L,
           replace_blanks = Sys.Date(), priority_col = "priority") {
    setorderv(overlap_dt, c(id_cols, team_col, start_col))
    overlap_dt[, end_col := get(end_col) + overlap_int]
    sd_cols <- c(start_col, "end_col")
    # foverlaps cannot deal with blanks
    overlap_dt[is.na(end_col), end_col := replace_blanks]
    # note: if end_col becomes < start_col due to overlap_int,
    # we assign end_col <- start_col
    overlap_dt[end_col - get(start_col) < 0, end_col := start_col]
    overlap_dt[, index := .I]
    setnames(overlap_dt, start_col, "start_date")
    # setnames(overlap_dt, team_col, "team")
    # finding overlapping combinations via vectors of indices ---
    c_overlap <-
      overlap_dt[overlap_dt[, unique(.SD), .SDcols =
                              c(id_cols, team_col, "start_date", "end_col", "index")],
                 on = c(id_cols, team_col), allow.cartesian = TRUE]
    c_overlap <- c_overlap[i.index != index]
    c_overlap[between(i.start_date, start_date, end_col) |
                between(i.end_col, start_date, end_col),
              ovr_vec := list(list(unique(c(index, i.index)))),
              by = c(id_cols, team_col, "start_date")]
    ovr_l <- c_overlap[, ovr_vec]
    ovr_l <- Filter(Negate(function(x) is.null(unlist(x))), ovr_l)
    ovr_l <- unique(ovr_l)
    # find list of reduced vectors which we need to MIN/MAX ---
    ovr_red_l <- list()
    for (i in seq_along(ovr_l)) {
      tmp_inter <- unique(unlist(sapply(
        ovr_l,
        FUN = function(x) {
          if (length(intersect(unlist(x), unlist(ovr_l[i]))) > 0) {
            result <- union(unlist(x), unlist(ovr_l[i]))
            return(result)
          } else {
            return(ovr_l[i])
          }
        }
      )))
      ovr_red_l[[i]] <- sort(tmp_inter)
    }
    ovr_red_l <- unique(ovr_red_l)

    for (i in seq(ovr_red_l)) {
      setkey(overlap_dt, index)[ovr_red_l[[i]],
                                c("start_date", "end_date", "end_col") :=
                                  list(min(start_date), max(end_date), max(end_col))]
    }
    overlap_dt[, index := NULL]
    overlap_dt <- unique(overlap_dt)
    setkeyv(overlap_dt, c(id_cols, "start_date"))
    # figure out which intervals are nested, separate them out & deal with them
    overlap_dt[, index := .I]
    overlap_dt[, prior_shift := priority - shift(priority, n = 1), by = id_cols]
    overlap_dt[between(shift(start_date, n = 1), start_date, end_col), ovr_shift := 1, by = id_cols]
    overlap_dt[shift(ovr_shift) == 1 & prior_shift < 0, nested_ovr := 1]
    overlap_dt[index %in% overlap_dt[nested_ovr == 1, index - 1], nested_ovr := 1]
        overlap_nested_dt <- overlap_dt[nested_ovr == 1]
    overlap_dt <- overlap_dt[is.na(nested_ovr)]
    nested_melt_dt <-
      melt(overlap_nested_dt, id.vars = c(id_cols, team_col, priority_col),
           measure.vars = c("start_date", "end_col"), value.name = "date_value")
    setkey(nested_melt_dt, person_ID, date_value)
    nested_melt_dt[, boundaries := cumsum(ifelse(variable == "start_date", 1, -1))]
    nested_melt_dt[boundaries==1 & variable == "start_date", bound_ok := 1]
    nested_melt_dt[boundaries==0 & variable == "end_col", bound_ok := 1]
    # create new records that need to be added ---
    add_dt <- nested_melt_dt[0, ]
    if (nrow(nested_melt_dt)>0) {
      for (i in 1:nrow(nested_melt_dt))
        if (nested_melt_dt[i, is.na(bound_ok)]) {
          if (nested_melt_dt[i, variable] == "start_date") {
            add_dt <- rbindlist(list(add_dt,
                                     data.table(nested_melt_dt[i, person_ID],
                                                nested_melt_dt[i-1, team],
                                                nested_melt_dt[i-1, priority],
                                                "end_col",
                                                nested_melt_dt[i, date_value - 1],
                                                NA, NA)))
          } else if (nested_melt_dt[i, variable] == "end_col") {
            add_dt <- rbindlist(list(add_dt,
                                     data.table(nested_melt_dt[i, person_ID],
                                                nested_melt_dt[i+1, team],
                                                nested_melt_dt[i+1, priority],
                                                "start_date",
                                                nested_melt_dt[i, date_value + 1],
                                                NA, NA)))
          }
        }
    }
    # add new records back in
    nested_melt_dt <- rbindlist(list(nested_melt_dt, add_dt))
    setkeyv(nested_melt_dt, c(id_cols, "date_value"))
    nested_melt_dt[, c("bound_ok", "boundaries") := NULL]
    nested_melt_dt[, date_group := .I, by = id_cols]
    nested_melt_dt[variable == "end_col", date_group := date_group - 1L]
    nested_melt_dt <-
      dcast(nested_melt_dt, paste0(paste(id_cols, sep = "+"), "+", team_col, "+",
                                   priority_col, "+", "date_group ~ variable"), value.var = "date_value")
    nested_melt_dt[, end_date := end_col]
    nested_melt_dt[, c("date_group") := NULL]
    overlap_dt[,  c("index", "prior_shift", "ovr_shift", "nested_ovr") := NULL]
    overlap_dt <- rbindlist(list(overlap_dt, nested_melt_dt), use.names = TRUE)
    setorderv(overlap_dt, c(id_cols, start_col, team_col))
    return(overlap_dt)
  }
overlap_combine(overlap_dt = copy(input), id_cols = "person_ID",
                team_col = "team", start_col = "start_date", end_col = "end_date",
                overlap_int = 1L, replace_blanks = Sys.Date() + 1e3,
                priority_col = "priority")

function output
   person_ID team start_date   end_date priority    end_col
1:      8534    B 2009-11-14 2010-03-01        2 2010-03-02
2:     11223    A 2012-01-02 2015-03-22        1 2015-03-23
3:     22446    B 2011-02-02 2012-04-02        2 2012-04-02
4:     22446    A 2012-04-03 2014-10-01        1 2014-10-01
5:     22446    B 2014-10-02 2016-01-03        2 2016-01-03
6:     98723    A 2009-10-01 2010-05-23        1 2010-05-24
7:     98723    A 2011-11-21       <NA>        1 2018-12-17