The radial part of a normal distribution

Question: I am reading a paper that asks me to sample $s_i$ from a distribution like this:
$s_i \sim (2\pi)^{-\frac{d}{2}}A^{-1}_{d-1}r^{d-1}e^{-\frac{r^2}{2}}$
"Here the normalization constant $A_{d−1}$ denotes the surface volume of the d-dimensional unit ball.
Thus $s_i$ matches the radial part of a normal distribution"
What is the radial part of a normal distribution?
The distribution above is related to the inverse of the hyper-surface of the unit ball, but the radius part is not inverted. Can i just sample from a normal distribution and scale? I am trying to get a sample from this distribution in C++.
Thanks in advance for any help in understanding the distribution above.
Answer: I gauss you are working on the fast-food method. As it is pointed out in the paper the distribution matches the radial part of a normal distribution. For $d = 2$ it is equal to Rayleigh distribution so you can use the standard implementations to sample $s_i$. For higher value of d you can sample from a $d$ dimensional zero mean gaussian distribution and then compute the length of the random vector. This method works well in terms of correctness. However, generating n samples using this method needs $nd$ time which is much higher than the overall time complexity of the fast-food algorithm. Thus, it is fine just for testing the correctness of the algorithm.
Update: I recently realized that $s_i$ has chi distribution. Equivalently, you can sample from chi-squared distribution and compute the square root of the samples. I succsesfully tested it in the Matlab and following you can find the source code:
<code>function [ ws ] = FF_samples( ndim, nsamples, sigm)
    ws = [];
    d = 2 ^ ceil(log2(ndim));
    x = ceil(nsamples/d);
    for bi = 1:x
        I = eye(d);

        B = diag(2*randi(2, d, 1) - 3);
        H = hadamard(d);
        P = I(randperm(d), :);
        G = diag(normrnd(0,1, d, 1));
        S = diag( chi2rnd(d,d,1) .^ .5) * sum(diag(G) .^ 2).^-.5;
        %%
        nws = (1/sigm / d)^.5 * S * H * G * P * H * B;
        ws = [ws; nws];
    end
    ws = ws(1:nsamples, 1:ndim);
end
</code>
P.S.: It still needs some improvement since I don't use the fast Fourier transform like algorithm for multiplication of the Hamard matrix to a vector.
Comment: I updated my previous post with a faster algorithm. I found your project very useful and interesting. Please let me know if you need any help.
Comment: Thank you for answering the question, I was indeed implementing Fast-Food. I had a tight deadline and actually only saw your answer now, when reviewing the project. In the end I sampled _d_ times from a 1 dimensional gaussian and computed the length. The implementation is available [here](https://bitbucket.org/johanvts/fastkernel). I am now studying distributions and hope to some day be able to return to make a fast implementation of this distribution part of my Fast-Food implementation.


Targeting the next td after the other td's class

Question:

    Full File
    5

    Waiting

Hi all!
Short and to the point:
I want to target, with jquery, the 'span.label'  knowing the class '.Full'
Answer: Try:
$(this).closest('td').next().find('span.label');

Or
$(this).closest('tr').find('span.label');

Answer: You can do this:
$('.Full').closest('tr').find('.label');

Get the Full jQuery object first.
Next go to the closest parent tr element.
Then using .find() go to the specified span with class as label

EDIT
For specifically targeting the span with class label use:
$('.Full').closest('tr').find('span.label');

Comment: This is what I would use... suggested a minor edit since asker specified span.label.  There may be other label classes.
Answer: Try
$('div.Full').closest('td').next('td').children('span.label');

.closest()
.children() is faster than .find()


Buttons not spaced

Question: For some reason, on a webpage, my buttons are not spaced while I clearly put a margin. could anyone help ?
CSS for the buttons:
.sidebar button {
            margin-top: 30px; margin-bottom: 30px; /* marge de 30px entre les boutons */
            max-width: 100px;
  }

Image of the outcome:

*This isn't a replica of my old question, as has been reported by someone. This one is solely about buttons tyling not appearing while the oter one was about aligning an iframe and a sidebar on the same line.
FULL CODE:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MaThé</title>

            MaThé

            <button class="sidebar" style="margin-bottom: 30px;">Button</button>

            <button class="sidebar" style="margin-bottom: 30px;">Button</button>

            <button class="sidebar" style="margin-bottom: 30px;">Button</button>

Comment: Hi, Welcome to StackOverflow. Your code should work as-is unless there is a style in `.sidebar` that is overwriting it. Can you confirm that your buttons are getting the margin applied to them with an inspector? It would help if could share your HTML too as well as the CSS for `.sidebar`.
Comment: They are spaced. You put margins on the top and bottom. Not on the left or right.
Comment: Does this answer your question? [Put an iframe on the right](https://stackoverflow.com/questions/63944727/put-an-iframe-on-the-right)
Comment: @mamouna this question is a 100% duplicate of your queston https://stackoverflow.com/questions/63944727 I have flagged it and reported it to the moderators. You should not open more than one question for the same issue. Thank you
Comment: .sidebar button {display: inline-block}
Answer: If you have put the 3 button in the div and you have given height to that div
Then as the height is fixed earlier so it is not able to make extra space
Check every div where you may have given some height which is restricting it from getting extra space
Comment: That's not correct. The buttons will overflow the container.  See example below
Answer: Can you better describe the problem?  The code here seems to be fine.

.sidebar button {
            margin-top: 30px; margin-bottom: 30px; /* marge de 30px entre les boutons */
            max-width: 100px;
            display:block;
  }

  .sidebar{
  height:100px;
  background-color:lightgrey;
  }

<button>button</button>
<button>button</button>
<button>button</button>

Comment: nothing is working... my sidebar code :

 .sidebar {

            display: flex;
            flex-direction: column;
            height: 710px;
            justify-content: center;
            width: 30%; /*réserver l'autre 30% du container au iframe*/
            align-items: center; /*Boutons*/
            flex-wrap: nowrap;
            align-content: space-around;
Comment: provide complete html and css

Buttons not spaced


$\int_{1}^{\infty} xf'(x) \space dx$ converges absolutely. Prove\disprove: $\int_{1}^{\infty} f(\xi) \space d\xi$ converges absolutely.

Question:
Let $f:[1, \infty) \rightarrow \mathbb{R}$ s.t $f$ is differentiable at $[1, \infty)$ and $\lim_{x \to \infty} f(x) = 0.$
Suppose that $f'$ is Riemann-integrable and the improper integral $\int_{1}^{\infty} xf'(x) \space dx$ converges absolutely.
 Prove\disprove:  $\int_{1}^{\infty} f(\xi) \space d\xi$ converges absolutely.

Since I've observed & proved the discrete version of this argument, I suspect it is true at its "continues" version as well (which is much more applicable and therefore, in my opinion, more interesting).
 So far I couldn't find a counter-example as well as I struggle to think of a proof strategy for this.
I'd like to have a bit of guidance here, thanks.
Answer: For this kinf of question, it is often useful to think $f$ as the integral of its derivative (since the information you have is on the derivative). The convergence toward $0$ of $f$, you have,
\begin{align*}
\int_1^{+\infty} |f(x)| \, dx & = \int_1^{+\infty} \left|\int_x^{+\infty} f'(t) \, dt\right| \, dx\\
& \leqslant \int_1^{+\infty} \int_1^t |f'(t)| \, dx \, dt \textrm{ by Fubini-Tonelli,}\\
& = \int_1^{+\infty} (t - 1)|f'(t)| \, dt\\
& < +\infty.
\end{align*}
It proves that $\displaystyle \int_1^{+\infty} f(x) \, dx$ converges (absolutely by the way), and you conclude with an integration by parts.
Edit : other method without Fubini-Tonelli. Notice that if $x \mapsto xf(x)$ converges at infinity toward some limit $l$, then $l \neq 0 \Rightarrow f(x) \sim \frac{l}{x} \Rightarrow \displaystyle \int_1^\infty f(x) \, dx = \mathrm{sign}(l)\infty$. Therefore, $l$ must equal $0$. Let us prove directly that $xf(x) \rightarrow 0$.
We have for all $x$, still using $f(x) \rightarrow 0$,
$$
|xf(x)| = x\left|\int_x^{+\infty} f'(t) \, dt\right| \leqslant \int_x^{+\infty} \frac{x}{t}|tf'(t)| \, dt \leqslant \int_x^{+\infty} |tf'(t)| \, dt \rightarrow 0,
$$
because $t \mapsto tf'(t)$ is integrable. Therefore, $xf(x) \rightarrow 0$.
Comment: I added an other method. By the way, the limit necessarily equals $0$.
Comment: Can you see a way to prove it without implicitly using Fubini-Tonelli theorem which I am unfamiliar with? Thanks!
Comment: Thanks, I've made some edits too in order to be more precise with your answer.
By the way, the idea of the second proof is also applicable at the discrete form of that argument by using (analogously) summation by parts (it's pretty cool imo since it draws parallels between the two).


docker: using screen to shut down minecraft server via cron job does not work

Question: I want to use docker for a minecraft server. The thing is that I need to shut it down properly to save the world every 24 hours. And to make things more complicated: the people on the server need be informed about this.
So my idea was using "screen" in conjunction with "cron":
################################
### We use a java base image ###
################################
FROM openjdk:8 AS build

MAINTAINER me <firstname.lastname@example.com>

#################
### Arguments ###
#################
ARG PAPERSPIGOT_CI_URL=https://papermc.io/ci/job/Paper-1.13/lastSuccessfulBuild/artifact/paperclip.jar

##########################
### Download paperclip ###
##########################
ADD ${PAPERSPIGOT_CI_URL} /opt/minecraft/server/paperclip.jar

############################################
### Run paperclip and obtain patched jar ###
############################################
RUN cd /opt/minecraft/server/ \
    && java -jar paperclip.jar; exit 0

RUN cd /opt/minecraft/server/ \
    && mv cache/patched*.jar paperspigot.jar

###########################
### Running environment ###
###########################
FROM anapsix/alpine-java:latest

###########################
### Install screen      ###
###########################
RUN apk --update add screen

#########################
### Working directory ###
#########################
WORKDIR /data

###########################################
### Obtain runable jar from build stage ###
###########################################
COPY --from=build /opt/minecraft/server/paperspigot.jar /opt/minecraft/server/paperspigot.jar

########################
### Obtain starth.sh ###
########################
ADD start.sh /opt/minecraft/server/start.sh

########################
### Obtain restart.sh ###
########################
ADD restart.sh /opt/minecraft/server/restart.sh

###########################################
### Configure and run cron              ###
###########################################
COPY crontab /etc/cron/crontab
# Init cron
RUN crontab /etc/cron/crontab

CMD ["crond", "-f"]

###############
### Volumes ###
###############
VOLUME "/data"

#############################
### Expose minecraft port ###
#############################
EXPOSE 25565

######################################
### Entrypoint is the start script ###
######################################
WORKDIR /data
ENTRYPOINT sh /opt/minecraft/server/start.sh

This is the start.sh script that seems to work:
#/bin/sh
cd /data
/usr/bin/screen -S minecraft /opt/jdk1.8.0_192/jre/bin/java -jar -Xms800M -Xmx800M -Dcom.mojang.eula.agree=true /opt/minecraft/server/paperspigot.jar
screen -ls

This is the restart script triggered via the crontab. I think it never gets started:
#!/bin/sh
# me - V1.1 - 18.05.2018
# Minecraft Server restart
screen -Rd minecraft -X stuff "say Server is restarting in 30 seconds! $(printf '\r')"
sleep 23s
screen -Rd minecraft -X stuff "say Server is restarting in 7 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 6 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 5 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 4 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 3 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 2 seconds! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Server is restarting in 1 second! $(printf '\r')"
sleep 1s
screen -Rd minecraft -X stuff "say Closing server...$(printf '\r')"
screen -Rd minecraft -X stuff "stop $(printf '\r')"
sleep 15s
# echo "Updating to most recent paperclip version."
# wget -q https://papermc.io/ci/job/Paper-1.13/lastSuccessfulBuild/artifact/paperclip.jar -O /home/pi/minecraft/paperclip.jar
echo "Restarting now."
/opt/minecraft/server/start.sh

This is the crontab which should start restart.sh every 5 minutes. Does not happen:
*/5 * * * * /opt/minecraft/server/restart.sh

Maybe this is the wrong way to do this. Maybe there is a much better way to connect somehow to the screen session or to restart the server with a message somehow. But I did not find anything online. Any idea?
Comment: Is there any reason your script is handling the server announcements. Wouldn't an internal server code be better? Check if your pc time is nearing 12:00, and then if so, just warn players in server.
Answer: after some testing and reading I came to the conclusion that using cron inside the container is the wrong why to do it.
I start and restart the docker container with docker. Since it is so fast I dont need to inform the ppl on the server. And the server gets properly stopped.
Answer: There are two possible problems here:

the cron daemon may not be installed in your Docker image, and
the cron job may be having problems locating executables in your Docker container

With regard to the first, I don't see anything installing cron in your Dockerfile. You probably want to check into the base image you're using - I know that I had to install it on an Ubuntu image I built a while back.
As for the second problem, the thing about running jobs in your crontab is that the environment is not what you expect it to be. Specifically, the $PATH variable, which the shell uses to find the commands you want to execute, is not set. As a result, many commands simply do not work because the shell doesn't know where to find them.
The "quick and dirty" way of fixing this is to ensure the $PATH variable is set in your crontab, by adding the following line:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

See this answer for more details.


Parser Error:Only assignment, call, increment, etc

Question: so I was reading the unity 3d script reference. Link below
http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
I wanted to test the example
    using UnityEngine;
    using System.Collections;

public class Example : MonoBehaviour {
    public Transform explosionPrefab;
    void OnCollisionEnter(Collision collision) {
        ContactPoint contact = collision.contacts[0];
        Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
        Vector3 pos = contact.point;
        Instantiate(explosionPrefab, pos, rot) as Transform;
        Destroy(gameObject);
    }
}

but I receive the error
Parse error: Only assignments, call, increment, decrement, await, and new object
at line 20[Instantiate(explosionPrefab, pos, rot) as Transform;]
Could someone please explain to me why I get such an error? and how I could fix it? Thanks.
Comment: Consider searching for error message/error code to find explanation on MSDN. [CS0201](http://msdn.microsoft.com/en-us/library/k626bk8b.aspx) - explains the issue and shows most common case...
Answer: Change this line
Transform transform = Instantiate(explosionPrefab, pos, rot) as Transform;

Alternatively remove the as Transform part if you don't need the instance
Instantiate(explosionPrefab, pos, rot)


Can not open PDF file using WebView

Question: I was trying to show pdf file using a url in webview. Although the WebView is loading webpage like google.com, it does not load anything or throw any exception when I try to load the url of the pdf.
The url loads pdf in google chrome desktop browser, so I guess the problem is not with the url itself.
Here's what I've coded so far:
onCreateView() of Fragment that loads the pdf
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_brochure, container, false);
        webView = view.findViewById(R.id.webView);
//        webView.loadUrl("https://google.com");
        webView.loadUrl("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
//        webView.loadUrl(brochureUrl);
        // Enable Javascript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);

        // Force links and redirects to open in the WebView instead of in a browser
        webView.setWebViewClient(new WebViewClient());
        return view;
    }

Layout (xml file):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_500"
    tools:context=".ui.project_details.project_details_pages.BrochureFragment">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"/>

</LinearLayout>

Manifest file (only the portion that I think to be relavant)
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        ...
        ...
        ...
        android:supportsRtl="true"
        android:usesCleartextTraffic="true">

What am I missing here?
Comment: No. It cannot. A WebView is for html documents. And the example in the answer does not display pdf but html as a google pdf to html converter is used as you can see on the url.
Comment: A WebView cannot display a pdf document.
Comment: @blackapps, it can. although I'm not sure if the display mechanism is same as a standard pdf viewer.
Answer: There some issue while loading pdf with webView. You can use the following code to solve your problem. This method takes the help of drive to view pdf in webView.
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

Comment: it worked! however, I also had to make some minor adjustments. I had to set webView's layout_height to 'match parent' and load the url after I was done with making changes to webview.getSettings(). I thought the .load() might invoke a thread and so the order might not matter. but now I think that this might not necessarily be the case.
Comment: for android 7. It seems the horziontal scroll appeared un knownly. Which is very annoyying...

Can not open PDF file using WebView


'return 404;' does not respect custom error page setup in Nginx

Question: I set up my custom 404 page for most cases in Nginx using global error_page settings in server block, however, if I do the following inside a location block:
if ($uri ~* ...) {return 404;}

then the default Nginx 404 page is returned.
Is there a way to return the custom page in this case?
Updated: currently I have something like this
server {
    ...
    error_page    404    /html/error/404.html;
    ...
    root           /home/www-data/mysite/static;

    location ^~ /blah/blah/ {
        if ($uri ~* ...) { return 404; }
        ...
    }

    location ^~ /html/error/ {
        internal;
    }
}

Comment: I think it has nothing to do with your location match or doc root. I went through the same scenario. Nginx does not use the custom 404 page when you do "return 404" for a particular location or request. Though I could not fix the problem.
Answer: Instead of returning 404 directly rather use:
error_page 404 /404.html;
location / {
            try_files $uri =404;
}

This would produce 404 http status code with custom 404 error page.
Hope this helps.
Answer: "/html/error" shouldn't be in both the root (absolute) and error_path (relative) paths.
Where is the document root?  Is it really '/home/www-data/mysite/static' when there's an 'html/' subdirectory of that?  Are you sure root shouldn't be '/home/www-data/mysite/static/html' ?
What's the pattern on the right side of the ~* match?  You might have a regex error that's causing it to match everything.
Or, the root directory might be wrong, and nginx might be returning 404 because it can't find the file, and not because that "if" pattern matches.
By default, the nginx error log will log the actual filesystem path nginx attempted to access for a request that returned 404 because of a missing file.  See the nginx docs for log_not_found and error_log if those errors are not showing up in the error log.
Comment: thanks for pointing that out. it was a typo in my original question, I have updated the question. However, with this setup, my problem still persists.


How am I possibly getting duplicate keys in my NSMutableDictionary?

Question: This is a log of an NSMutableDictionary I have in my app.
{
one =     (
    "2013-11-15 19.47.55.jpg"
);
three =     (
    "2013-11-15 19.47.55.jpg"
);
"three" =     (
    "2013-11-15 19.45.12.jpg",
    "2013-11-15 19.45.02.jpg"
);
two =     (
    "2013-11-15 19.42.21.jpg",
    "2013-11-15 19.47.55.jpg"
);

}
I'm guessing the quotes indicate there's something different about the second "three" - but I've no idea where to start debugging this. If anyone has any suggestions where to start looking, I can elaborate, and post some source code. I'm just having trouble identifying what would be relevant at the moment.
EDIT:
@Wain and @Vlad, so I think you're right, here's the log of the classes:
2013-11-15 20:32:10.034 Last[9785:60b] one __NSCFString
2013-11-15 20:32:10.036 Last[9785:60b] three __NSCFString
2013-11-15 20:32:10.038 Last[9785:60b] three
2013-11-15 20:32:10.039 Last[9785:60b] two __NSCFString

No class.. ?
Comment: There are no duplicate keys listed above.  There is `three` and `"three"`, but they are different values -- the second is either doubly quoted or contains some invisible character.
Comment: How are you creating it? Log the class of each key.
Comment: Write a small routine to get `allKeys` and print the class name for each element.
Comment: Please post some code associated with adding values to the dictionary.
Comment: So how are you creating the dictionary and keys?
Answer: It looks like one of your keys is being set with something like [myDict setValue:v forKey:[threeObj description]]; and the other one is being set with [myDict setValue:otherV forKey:@"three"];.
After a quick test, I came up with this:
// Pretend MyFirstClass implements a custom -description
MyFirstClass *o = [[MyFirstClass alloc] init];
NSMutableDictionary *d = [NSMutableDictionary dictionary];

// We get "\"Three\""
NSString *key = [o description];

[d setObject:[NSNumber numberWithBool:YES] forKey:[key lowercaseString]];

// In another part of code you're doing something like this:
key = @"Three";
[d setObject:[NSNumber numberWithInt:1000] forKey:[key lowercaseString]];

Output:
2013-11-15 14:29:21.942 Dummy[31958:c07] {
    "three" = 1;
    three = 1000;
}

These are definitely two unique keys. I'd check your code to make sure nothing like this is happening. Maybe you have multiple areas where you're setting values and handling the key creation differently.
Comment: I'm using [key lowercaseString], could that be it?
Comment: Where are you getting key? I think your issue lies where key is being generated.
Comment: If you are getting key by doing something like: key = [myObj description]; then calling lowercaseString, that will be your issue.
Comment: aust - nice write up ... @op as he said they ARE unique keys so the issue must be where you make the keys
Answer: I'd start by checking class type for the duplicates. Can't really get duplicates other way.
try printing out in debug NSStringFromClass([object class]) for each object and key in your dict.


Getter and setter like behavior in one closure

Question: Learning javascript and i am trying to write a simple closure that encapsulate a variable which i can set or get.
here is an example of the behavior i am aiming for specifically:
let x = Field(1) //set value to 1, return the closure itself
x(2)             //set value field to 2
x()              //returns 2
x(3)             //set value to 3
x()              //returns 3

is it possible to do the above and preserve the same exact syntax, i imagined that i should make the closure return itself but when i tried that it obviously lost the value field and created a new instance:
/**
 * if v is passed it functions like a setter
 * if no arguments passed it functions like a getter
 * @param {*} [v]
 */
const Field = function(v){
    let value
    if (arguments.length === 1) { //SET
        value = v;

    } else if (arguments.length === 0) { //GET
        return value;
    } else {
        throw 'Field can have one or no arg'
    }

    return Field //how to i return this exact instance of Field?
}

My question as per the last code comment, how do i return this exact instance of Field?
Answer: Something like this?

const Field = function(v) {
    this.value = v;

    return function() {
        if (arguments.length === 1) { //SET
            this.value = arguments[0];
        } else if (arguments.length === 0) { //GET
            return this.value;
        } else {
            throw 'Field can have one or no arg'
        }
    }.bind(this);
}

let f = new Field(42);
console.log(f());

f(51);
console.log(f());


The rank of a principal submatrix of a positive semi definite matrix

Question: I have this question I met in my studies of matrix theory on which I need help:

Let A be positive semidefinite and real of order $ n \times n $. Let $ A[\alpha] $ be a principal submatrix of A (the submatrix of A indexed by rows and columns given by the vector $ \alpha $) and we are asked to prove the following equalities of rank
  $$\DeclareMathOperator\rk{rank} \rk A[\alpha|1,2,...,n] = \rk A[1,2,...,n|\alpha] = \rk A[\alpha] $$ and we are given the following hint: we are told to assume $ \alpha=\{1,...,k\} $ and as A is positive semidefinite we may factorize it as $ A=BB^T $ where B is the block 2x1 matrix of the form $ B=\begin{pmatrix}X\\Y\end{pmatrix} $ where X is a $ k \times k $ matrix.

To be honest, I have no real idea how to use the clue and why they ask us to make the assumption about $ \alpha=\{1,2,...,k\} $ and how to proceed to the general equality we are asked to prove. I appreciate all helps.
Comment: Can you explain what is the matrix $A[\alpha| 1,\dots,n]$?
Comment: I edited the formatting of the maths so that it is more readable. Please check that this still has the intended meaning.
Comment: This first part of the hint is OK. Suppose the size of $\alpha$ is $k$. Up to a permutation, you may assume without loss of generality that $A[\alpha]$ is the **leading** $k\times k$ principal submatrix, i.e. $\alpha=\{1,2,\ldots,k\}$. The second part of the hint is definitely wrong, however. Note that $k$ is arbitrary but the rank of $A$ is not. If $k<\operatorname{rank}(A)$, the product $BB^T$ can't possibly be equal to $A$.
Comment: @zbigniew2015 The first equality is trivial because the rank of a matrix is equal to the rank of its transpose. For the second one, suppose $\alpha=\{1,2,\ldots,k\}$ and $A[\alpha]=X$, i.e. $A$ is in the form of $\pmatrix{X&Y\\ Y^T&Z}$. Note that $A$ is positive semidefinite if and only if $\pmatrix{QXQ^T&QY\\ Y^TQ^T&Z}$ is positive semidefinite. So you may assume that $X$ is a diagonal matrix.
Comment: @zbigniew2015 Well, that's your job. You may try a few examples first. E.g. do you see why $\left[\begin{array}{cc|c}x&0&\ast\\ 0&0&y\\ \hline\ast&y&z\end{array}\right]$ is *never* positive semidefinite when $y$ is nonzero?
Comment: @zarathustra thank you looks lovely and all correct
Comment: @zarathustra yes, it is the submatrix of A whose rows are indexed by $\alpha$  and whose columns are all columns of A
Comment: @user1551 : thanks maybe the hint is flawed but do you agree with the equality and could you please help in solving the question without the flawed hint?
Comment: @user1551 : Right, but how would I show equality of rank to one of the other two submatrices stated?
Answer: Here's an idea: take $B = \pmatrix{X\\Y}$ where $X$ is a $k \times n$ matrix, where $B$ is such that $BB^T = A$.  In particular, we have
$$
A = \pmatrix{XX^T & XY^T\\YX^T & YY^T}
$$
Let $P = \pmatrix{I & 0}$, where $I$ is the $k \times k$ identity matrix.  Notice that for $\alpha = \{1,\dots,k\}$, we have
$$
A[\alpha] = PAP^T = (PB)(PB)^T = XX^T
$$
Conclude that $A[\alpha]$ has the same rank as $PB = X$.  On the other hand,
$$
A[\alpha \mid 1,\dots,n] = PA = (PB)B^T = XB^T
$$
thus, we conclude that the rank of $A[\alpha \mid 1,\dots,n]$ is at most the rank of $X$, which is to say that
$$
\operatorname{rank}(A[\alpha \mid 1,\dots,n]) \leq
\operatorname{rank}(A[\alpha])
$$
I think you'll find that the reverse inequality, $\operatorname{rank}(A[\alpha \mid 1,\dots,n]) \geq
\operatorname{rank}(A[\alpha])$, is a bit more obvious.


Can you give an example of Metropolis and Metropolis-Hastings algorithm?

Question: I have studied many books and tried to understand both the Metropolis and Metropolis-Hastings algorithm. Everywhere it is written in the context of the Ising model or Lenard-Jones Energy. I am having difficulty understanding the algorithm from this context.
Can you give an example without using the context of Physics/Mechanics/Dynamics?
A source code example would be much appreciated.
Answer: I'm not sure what books you have read, but I personally enjoyed both the explanatory approaches of Ben Lambert (A Student's Guide to Bayesian Statistics) and Richard McElreath (Statistical Rethinking A Bayesian Course with Examples in R and STAN). McElreath even provides a source code example of the Metropolis algorithm and HMC in R.
Comment: (+1) Yes, McElreath sets Metropolis Hastings within the Bayesian modelling setting and hence in a much broader setting than Physics. So do [our Monte Carlo books.](https://amzn.to/3xD2mfC)


extends de templates a partir do projeto para os apps

Question: Tenho um projeto criados a partir do comando startproject ... onde na estrutura do mesmo, criei uma pasta templates, no qual, eu desejo ter templates htmls bases, ou seja, estendendo-os para as templates dos meus apps. É possível? se sim como eu posso fazer? Li aqui em alguma postagem, que eu deveria fazer isto a partir de um app mestre e não do projeto, é isto mesmo?
Answer: Acabei por descobrir depois de muito ler diversos artigos sobre o assunto. Assim: para um extends a partir do projeto, basta incluir no settings.py na configuração TEMPLATE a seguinte configuração 'DIRS': [os.path.join(BASE_DIR, 'site/templates')]... onde "site" é o seu projeto. Logo em seguida, crie uma pasta de nome "templates" na estrutura de seu projeto e uma nova pasta com o nome do se app, por exemplo "blog", ficando assim: "templates\blog". Feito, agora eu posso ter um base.html e usado em meus apps utilizando {% extends "blog/layout.html" %}.
Para mais detalhes, esta fonte me ajudou muito:
https://docs.djangoproject.com/pt-br/2.2/howto/overriding-templates/


Somar ou Mostrar quantidade de itens

Question: Qual a melhor maneira de somar ou mostrar a quantidade de itens numa tabela mysql utilizando o php.
Pois quando executo esse código aparece o seguinte erro: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in H:\Web\root\index.php on line 89

$mysql_connection =  mysql_connect($web_host, $web_user, $web_pass);
        $mysql_connection_from_db = mysql_select_db($web_db);

        $command_ = "SELECT COUNT(`usr_id`) FROM `app_users`";
        $mysql_query = mysql_query($command_);

        $num = mysql_num_rows($mysql_query);

        if(0 == $num) { $PESSOAS = 0; }
        else{
            while($row = mysql_fetch_assoc($mysql_query))
            {
                $PESSOAS = $PESSOAS + 1;
            }
        }

Linha 89:
$num = mysql_num_rows($mysql_query);
OBS: O objetivo é que o usuário clique em participar e ele adicione um nome qualquer mais um id na tabela e quando carregar a página o sistema php mostra quantos itens tem naquela tabela, ou no caso, $PESSOAS, que determina o número de participantes.
Answer: Você pode pegar o resultado direto com o mysql_fetch_assoc() ou mysql_fetch_array().
$command_ = "SELECT COUNT(`usr_id`) FROM `app_users`";
$result = mysql_fetch_assoc(mysql_query($command_));

O COUNT() sempre irá retornar apenas 1 linha, por isso o erro do seu código, você está fazendo um looping.
E uma dica, não utilize o mysql_connect() ele esta deprecated, utilize a função mysqli_connect().
Comment: É o mesmo do mysql (http://php.net/manual/pt_BR/function.mysqli-connect.php)
Comment: Entendi, quando você roda essa query direto no banco de dados te retorna algum dado?
[Neste link](http://php.net/manual/pt_BR/function.mysqli-connect.php#112689) tem um exemplo de como fazer a consulta, porém na sua não irá precisar do `while()` você pode pegar direto como mostrei na resposta
Comment: mas o mysqli é o mesmo do mysql? ou uma linguagem sql diferente?
Comment: ok vou tentar! : )
Comment: ops! mantem o mesmo **mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in H:\Web\root\index.php on line 86**
Comment: ja troquei pelo mysqli
Comment: Jeferson Assis eu quero fazer esse sistema igual ao do stackoverflow quando um usuário abre uma pergunta aqui no site, mostra o número de visualizações entendeu? mas quando um usuário se cadastra no site aparece quantos usuários estão cadastrados.
Comment: Olha quando eu executo no phpmyadmin ele me retorna uma tabela indicando a quantidade. ex:

-------------------
+-- COUNT --+
------------------
1
Comment: Ops, quando eu uso mysqli_query aparece o seguinte: **Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in H:\Web\root\index.php on line 86

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in H:\Web\root\index.php on line 86**
Comment: apareceu mais um quando eu hospedei os arquivos na nuvem... **Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/a1478344/public_html/warface/index.php on line 86**
Comment: Segue este link para a demonstração : http://brasilr2.net76.net/warface/
Comment: Olha tentei executar isso e aparece apenas o numero 1: **$PESSOAS = mysqli_num_rows( mysqli_query( $mysql_connection ,$command_ ));**
Answer: Funcionou deste jeito!
Com base da resposta do Jeferson Assis pude compreender que não é preciso executar
SELECT COUNT(*) FROM `participacoes`
Mas sim executar:
SELECT * FROM `participacoes`
E proseguir com o php:
$mysql_connection =  mysqli_connect($web_host, $web_user, $web_pass, $web_db);
$sql = 'SELECT * FROM `participacoes`';
$PESSOAS = mysqli_num_rows( mysqli_query( $mysql_connection , $sql ));
Note que eu apenas utilizei apenas para que o sistema conte o número de itens não o total do número de itens:
$PESSOAS = mysqli_num_rows( mysqli_query( $mysql_connection , $sql ));
se não acabaria num loop infinito e não seria reposto nenhum dado.

Somar ou Mostrar quantidade de itens


mpi in c how to extends the use of MPI_Type_create_subarray?

Question: How can I use the  MPI_Type_create_subarray to pass a arrays of characters but of very large size of type unsigned long long int
as the overall rows (total_nrows) = 31,613,582,882 and the number of rows to be written by each rank (real_rows3) around 2,580,689,006, in case using 14 ranks.
unsigned long long int globalsizes[2] = {total_nrows, 365};
unsigned long long int localsizes [2] = {real_rows3, 365};
unsigned long long int starts[2]      = {startrow, 0};
MPI_Datatype localarray;

 MPI_Type_create_subarray(2, globalsizes, localsizes, starts, MPI_ORDER_C, MPI_CHAR, &localarray);

Answer: Long story short, you cannot.
From the MPI standard :
int MPI_Type_create_subarray(int ndims,
                           const int array_of_sizes[],
                           const int array_of_subsizes[],
                           const int array_of_starts[],
                           int order,
                           MPI_Datatype oldtype,
                           MPI_Datatype *newtype)

Arguments are int so there is an intrinsic limit of 2^31-1.
That being said, you might be able to achieve a similar result by using an intermediate (and larger) datatype.
For example, an array of 2^32 MPI_CHAR can be seen an array of 2^22 vectors of 2^10 MPI_CHAR. That obviously does not work with any number, but that might help you.
An other option is to use BigMPI.
Basically, int (32 bits) are replaced with MPI_Count (64 bits).
Keep in mind BigMPI is not part of the MPI 3.1 standard, so this is not an option if you have to write portable code.
[edit]
There is a chance BigMPI will land into the MPI standard, and possibly with MPI 4.0.
Comment: BigMPI isn't part of MPI-3 but it is strictly compliant with MPI-3 and ISO C99 as far as I know, so it should be very portable (it is most likely limited by MPI implementations that are not _internally_ count-safe). I used the MIT license because I went everyone to be able to use it or copy from it with impunity.
Comment: Also, you should say it's not in the MPI 3.1 standard, because there seems like a chance it will make it into 4.0


How to extract the schema of an Access (.mdb) database?

Question: I am trying to extract the schema of an .mdb database, so that I can recreate the database elsewhere.
How can I pull off something like this?
Comment: Try this vba module https://github.com/timabell/msaccess-vcs-integration
Comment: "Access doesn't have SQL" sure it does e.g. look in MSDN for "Access SQL Reference" e.g. http://msdn.microsoft.com/en-us/library/bb259127.aspx
Comment: See also http://stackoverflow.com/questions/187506/how-do-you-use-version-control-with-access-development
Comment: What language? Does it matter?
Comment: I don't really understand the question.  The extracted text should be in Access SQL, so that I can recreate the database if needed.
Comment: Language can be relevant if you choose _not_ to use Access SQL, such as my answer below which uses ADOX from Python. Constructing DDL out of an Access db is a PITA (as shown by the verbosity of Remou's answer below)...
Comment: Access doesn't have SQL, but Jet does.
Answer: It is possible to do a little with VBA. For example, here is a start on creating script for a database with local tables.
Dim db As Database
Dim tdf As TableDef
Dim fld As DAO.Field
Dim ndx As DAO.Index
Dim strSQL As String
Dim strFlds As String
Dim strCn As String

Dim fs, f

    Set db = CurrentDb

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.CreateTextFile("C:\Docs\Schema.txt")

    For Each tdf In db.TableDefs
        If Left(tdf.Name, 4) <> "Msys" Then
            strSQL = "strSQL=""CREATE TABLE [" & tdf.Name & "] ("

            strFlds = ""

            For Each fld In tdf.Fields

                strFlds = strFlds & ",[" & fld.Name & "] "

                Select Case fld.Type

                    Case dbText
                        'No look-up fields
                        strFlds = strFlds & "Text (" & fld.Size & ")"

                    Case dbLong
                        If (fld.Attributes And dbAutoIncrField) = 0& Then
                            strFlds = strFlds & "Long"
                        Else
                            strFlds = strFlds & "Counter"
                        End If

                    Case dbBoolean
                        strFlds = strFlds & "YesNo"

                    Case dbByte
                        strFlds = strFlds & "Byte"

                    Case dbInteger
                        strFlds = strFlds & "Integer"

                    Case dbCurrency
                        strFlds = strFlds & "Currency"

                    Case dbSingle
                        strFlds = strFlds & "Single"

                    Case dbDouble
                        strFlds = strFlds & "Double"

                    Case dbDate
                        strFlds = strFlds & "DateTime"

                    Case dbBinary
                        strFlds = strFlds & "Binary"

                    Case dbLongBinary
                        strFlds = strFlds & "OLE Object"

                    Case dbMemo
                        If (fld.Attributes And dbHyperlinkField) = 0& Then
                            strFlds = strFlds & "Memo"
                        Else
                            strFlds = strFlds & "Hyperlink"
                        End If

                    Case dbGUID
                        strFlds = strFlds & "GUID"

                End Select

            Next

            strSQL = strSQL & Mid(strFlds, 2) & " )""" & vbCrLf & "Currentdb.Execute strSQL"

            f.WriteLine vbCrLf & strSQL

            'Indexes
            For Each ndx In tdf.Indexes

                If ndx.Unique Then
                    strSQL = "strSQL=""CREATE UNIQUE INDEX "
                Else
                    strSQL = "strSQL=""CREATE INDEX "
                End If

                strSQL = strSQL & "[" & ndx.Name & "] ON [" & tdf.Name & "] ("

                strFlds = ""

                For Each fld In tdf.Fields
                    strFlds = strFlds & ",[" & fld.Name & "]"
                Next

                strSQL = strSQL & Mid(strFlds, 2) & ") "

                strCn = ""

                If ndx.Primary Then
                    strCn = " PRIMARY"
                End If

                If ndx.Required Then
                    strCn = strCn & " DISALLOW NULL"
                End If

                If ndx.IgnoreNulls Then
                    strCn = strCn & " IGNORE NULL"
                End If

                If Trim(strCn) <> vbNullString Then
                    strSQL = strSQL & " WITH" & strCn & " "
                End If

                f.WriteLine vbCrLf & strSQL & """" & vbCrLf & "Currentdb.Execute strSQL"
            Next
        End If
    Next

    f.Close

Comment: This is really good.  How do you get the default values out, foreign keys, etc?
Comment: @David W. Fenton: the DAO model isn't as rich as the SQL DLL syntax e.g. DAO can't still can't create 'fast foreign keys'. I know, I know: you've never used a fast foreign key and therefore you don't miss it but it's still a limitation :)
Comment: It is necessary to use ADO to add default values. Foreign keys etc can be added with CONSTRAINT ReferForeignField FOREIGN KEY(, ,..,) REFERENCES  (, ,..,)

I will see what i can do to add to the example.
Comment: If you're using DAO, you should be using the relationships collection to apply foreign key restraints, no?
Comment: Yes, but if it is to be done out in sql, like most schemas, I think, it looks like it ought to be ADO. As has already been said, for DAO the best bet is probably to simply copy the mdb. YesNo?
Comment: This is impressive. But it would be even better if it could get query definitions out too.
Answer: It's an ancient question now, but unfortunately perennial :(
I thought this code may be of use to others looking for solutions. It's designed to be run from the command line via cscript, so no need to import code into your Access project.  Similar to (and inspired by) the code from Oliver in How do you use version control with Access development.
' Usage:
'  CScript //Nologo ddl.vbs <input mdb file> > <output>
'
' Outputs DDL statements for tables, indexes, and relations from Access file
' (.mdb, .accdb) <input file> to stdout.
' Requires Microsoft Access.
'
' NOTE: Adapted from code from "polite person" + Kevin Chambers - see:
' http://www.mombu.com/microsoft/comp-databases-ms-access/t-exporting-jet-table-metadata-as-text-119667.html
'
Option Explicit
Dim stdout, fso
Dim strFile
Dim appAccess, db, tbl, idx, rel

Set stdout = WScript.StdOut
Set fso = CreateObject("Scripting.FileSystemObject")

' Parse args
If (WScript.Arguments.Count = 0) then
    MsgBox "Usage: cscript //Nologo ddl.vbs access-file", vbExclamation, "Error"
    Wscript.Quit()
End if
strFile = fso.GetAbsolutePathName(WScript.Arguments(0))

' Open mdb file
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase strFile
Set db = appAccess.DBEngine(0)(0)

' Iterate over tables
  ' create table statements
For Each tbl In db.TableDefs
  If Not isSystemTable(tbl) And Not isHiddenTable(tbl) Then
    stdout.WriteLine getTableDDL(tbl)
    stdout.WriteBlankLines(1)

    ' Iterate over indexes
      ' create index statements
    For Each idx In tbl.Indexes
      stdout.WriteLine getIndexDDL(tbl, idx)
    Next

    stdout.WriteBlankLines(2)
  End If
Next

' Iterate over relations
  ' alter table add constraint statements
For Each rel In db.Relations
  Set tbl = db.TableDefs(rel.Table)
  If Not isSystemTable(tbl) And Not isHiddenTable(tbl) Then
    stdout.WriteLine getRelationDDL(rel)
    stdout.WriteBlankLines(1)
  End If
Next

Function getTableDDL(tdef)
Const dbBoolean = 1
Const dbByte = 2
Const dbCurrency = 5
Const dbDate = 8
Const dbDouble = 7
Const dbInteger = 3
Const dbLong = 4
Const dbDecimal = 20
Const dbFloat = 17
Const dbMemo = 12
Const dbSingle = 6
Const dbText = 10
Const dbGUID = 15
Const dbAutoIncrField = 16

Dim fld
Dim sql
Dim ln, a

    sql = "CREATE TABLE " & QuoteObjectName(tdef.name) & " ("
    ln = vbCrLf

    For Each fld In tdef.fields
       sql = sql & ln & " " & QuoteObjectName(fld.name) & " "
       Select Case fld.Type
       Case dbBoolean   'Boolean
          a = "BIT"
       Case dbByte   'Byte
          a = "BYTE"
       Case dbCurrency  'Currency
          a = "MONEY"
       Case dbDate 'Date / Time
          a = "DATETIME"
       Case dbDouble    'Double
          a = "DOUBLE"
       Case dbInteger   'Integer
          a = "INTEGER"
       Case dbLong  'Long
          'test if counter, doesn't detect random property if set
          If (fld.Attributes And dbAutoIncrField) Then
             a = "COUNTER"
          Else
             a = "LONG"
          End If
       Case dbDecimal    'Decimal
          a = "DECIMAL"
       Case dbFloat      'Float
          a = "FLOAT"
       Case dbMemo 'Memo
          a = "MEMO"
       Case dbSingle    'Single
          a = "SINGLE"
       Case dbText 'Text
          a = "VARCHAR(" & fld.Size & ")"
       Case dbGUID 'Text
          a = "GUID"
       Case Else
          '>>> raise error
          MsgBox "Field " & tdef.name & "." & fld.name & _
                " of type " & fld.Type & " has been ignored!!!"
       End Select

       sql = sql & a

       If fld.Required Then _
          sql = sql & " NOT NULL "
       If Len(fld.DefaultValue) > 0 Then _
          sql = sql & " DEFAULT " & fld.DefaultValue

       ln = ", " & vbCrLf
    Next

    sql = sql & vbCrLf & ");"
    getTableDDL = sql

End Function

Function getIndexDDL(tdef, idx)
Dim sql, ln, myfld

    If Left(idx.name, 1) = "{" Then
       'ignore, GUID-type indexes - bugger them
    ElseIf idx.Foreign Then
       'this index was created by a relation.  recreating the
       'relation will create this for us, so no need to do it here
    Else
       ln = ""
       sql = "CREATE "
       If idx.Unique Then
           sql = sql & "UNIQUE "
       End If
       sql = sql & "INDEX " & QuoteObjectName(idx.name) & " ON " & _
             QuoteObjectName(tdef.name) & "( "
       For Each myfld In idx.fields
          sql = sql & ln & QuoteObjectName(myfld.name)
          ln = ", "
       Next
       sql = sql & " )"
       If idx.Primary Then
          sql = sql & " WITH PRIMARY"
       ElseIf idx.IgnoreNulls Then
          sql = sql & " WITH IGNORE NULL"
       ElseIf idx.Required Then
          sql = sql & " WITH DISALLOW NULL"
       End If
       sql = sql & ";"
    End If
    getIndexDDL = sql

End Function

' Returns the SQL DDL to add a relation between two tables.
' Oddly, DAO will not accept the ON DELETE or ON UPDATE
' clauses, so the resulting sql must be executed through ADO
Function getRelationDDL(myrel)
Const dbRelationUpdateCascade = 256
Const dbRelationDeleteCascade = 4096
Dim mytdef
Dim myfld
Dim sql, ln

    With myrel
       sql = "ALTER TABLE " & QuoteObjectName(.ForeignTable) & _
             " ADD CONSTRAINT " & QuoteObjectName(.name) & " FOREIGN KEY ( "
       ln = ""
       For Each myfld In .fields 'ie fields of the relation
          sql = sql & ln & QuoteObjectName(myfld.ForeignName)
          ln = ","
       Next
       sql = sql & " ) " & "REFERENCES " & _
             QuoteObjectName(.table) & "( "
       ln = ""
       For Each myfld In .fields
          sql = sql & ln & QuoteObjectName(myfld.name)
          ln = ","
       Next
       sql = sql & " )"
       If (myrel.Attributes And dbRelationUpdateCascade) Then _
             sql = sql & " ON UPDATE CASCADE"
       If (myrel.Attributes And dbRelationDeleteCascade) Then _
             sql = sql & " ON DELETE CASCADE"
       sql = sql & ";"
    End With
    getRelationDDL = sql
End Function

Function isSystemTable(tbl)
Dim nAttrib
Const dbSystemObject = -2147483646
    isSystemTable = False
    nAttrib = tbl.Attributes
    isSystemTable = (nAttrib <> 0 And ((nAttrib And dbSystemObject) <> 0))
End Function

Function isHiddenTable(tbl)
Dim nAttrib
Const dbHiddenObject = 1
    isHiddenTable = False
    nAttrib = tbl.Attributes
    isHiddenTable = (nAttrib <> 0 And ((nAttrib And dbHiddenObject) <> 0))
End Function

Function QuoteObjectName(str)
    QuoteObjectName = "[" & str & "]"
End Function

If you are looking to export query definitions as well, this question should help. It's a little different because you don't usually create querydefs with plain DDL CREATE VIEW foo AS ... syntax, in fact I'm not sure you can (?)
But here's a little piece of a script I wrote for backing up queries to separate .sql files (which is part of a larger script for backing up all front-end db code, see Oliver's answer for this question).
Dim oApplication
Set oApplication = CreateObject("Access.Application")
oApplication.OpenCurrentDatabase sMyAccessFilePath
oApplication.Visible = False

For Each myObj In oApplication.DBEngine(0)(0).QueryDefs
    writeToFile sExportpath & "\queries\" & myObj.Name & ".sql", myObj.SQL
Next

Function writeToFile(path, text)
Dim fso, st
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set st = fso.CreateTextFile(path, True)
  st.Write text
  st.Close
End Function

Comment: @LondonRob: added
Comment: This still works with Access 365 on Windows 10.
Comment: As I commented above, it'd be great if this included query definitions too.
Answer: The following C# outlines how to obtain the schema from a .mdb file.
Obtain a connection to the database:
String f = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database.mdb";
OleDbConnection databaseConnection = new OleDbConnection(f);
databaseConnection.Open();

Get the name of each table:
DataTable dataTable = databaseConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
int numTables = dataTable.Rows.Count;
for (int tableIndex = 0; tableIndex < numTables; ++tableIndex)
{
    String tableName = dataTable.Rows[tableIndex]["TABLE_NAME"].ToString();

Get the fields for each table:
    DataTable schemaTable = databaseConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName, null });
    foreach (DataRow row in schemaTable.Rows)
    {
        String fieldName = row["COLUMN_NAME"].ToString(); //3
        String fieldType = row["DATA_TYPE"].ToString(); // 11
        String fieldDescription = row["DESCRIPTION"].ToString(); //27
    }
}

Where do the 3, 11 and 27 come from? I found them by inspecting DataRow.ItemArray with a debugger, does anyone know the 'correct' way?

Here is the screenshot ProVega alludes to in the comments of this answer:
Comment: To get the field name for each column in the database:
OleDbDataReader.GetName(i), where i is used to iterate through each of the field index numbers.
OleDbDataReader.GetFieldType(i) returns the data type of the column.
Comment: Glad I got your attention. I was thinking about doing the edit myself but wasn't sure how to get the image. I suppose edit the deleted answer and copy/paste the imgur link.
Comment: Aha, I knew there must be a way! Cheers.
Comment: I updated your answer with the actual string values for the rows you wanted.  I will add a screenshot of all the options in an answer below.
Comment: for all those wondering where the screenshot is, ProVega has posted it as an answer further down the thread
Comment: And that answer has been deleted. The screenshot could have been included in edit of this answer.
Comment: @June7 glad you commented, I uploaded from the deleted answer.
Answer: If you're happy to use something other than pure Access SQL, you could persist a collection of ADOX objects and use those to recreate the table structure.
Example (in Python, doesn't currently recreate relationships and indexes as it wasn't needed for the project I was working on):
import os
import sys
import datetime
import comtypes.client as client

class Db:
    def __init__(self, original_con_string = None, file_path = None,
                 new_con_string = None, localise_links = False):
        self.original_con_string = original_con_string
        self.file_path = file_path
        self.new_con_string = new_con_string
        self.localise_links = localise_links

    def output_table_structures(self, verbosity = 0):
        if os.path.exists(self.file_path):
            if not os.path.isdir(self.file_path):
                raise Exception("file_path must be a directory!")
        else:
            os.mkdir(self.file_path)
        cat = client.CreateObject("ADOX.Catalog")
        cat.ActiveConnection = self.original_con_string
        linked_tables = ()
        for table in cat.Tables:
            if table.Type == u"TABLE":
                f = open(self.file_path + os.path.sep +
                         "Tablestruct_" + table.Name + ".txt", "w")
                conn = client.CreateObject("ADODB.Connection")
                conn.ConnectionString = self.original_con_string
                rs = client.CreateObject("ADODB.Recordset")
                conn.Open()
                rs.Open("SELECT TOP 1 * FROM [%s];" % table.Name, conn)
                for field in rs.Fields:
                    col = table.Columns[field.Name]
                    col_details = (col.Name, col.Type, col.DefinedSize,
                                   col.Attributes)
                    property_dict = {}
                    property_dict["Autoincrement"] = (
                        col.Properties["Autoincrement"].Value)
                    col_details += property_dict,
                    f.write(repr(col_details) + "\n")
                rs.Close()
                conn.Close()
                f.close()
            if table.Type == u"LINK":
                table_details = table.Name,
                table_details += table.Properties(
                    "Jet OLEDB:Link DataSource").Value,
                table_details += table.Properties(
                    "Jet OLEDB:Link Provider String").Value,
                table_details += table.Properties(
                    "Jet OLEDB:Remote Table Name").Value,
                linked_tables += table_details,
        if linked_tables != ():
            f = open(self.file_path + os.path.sep +
                     "linked_list.txt", "w")
            for t in linked_tables:
                f.write(repr(t) + "\n")
        cat.ActiveConnection.Close()

A similar reverse function reconstructs the database using the second connection string.
Comment: Correction: forget informal, looks like it's now official for the Access2007 era. See: http://msdn.microsoft.com/en-us/library/bb245488.aspx -- it's a whole section of MSDB entitiled 'Microsoft Access SQL Reference'. I can't see a single mention of 'Jet' :)
Comment: There is no such thing as "Access SQL." Access uses Jet SQL by default, but that's wholly independent of Access.
Comment: @mavnn: yes, shame on you. The fact that *everyone* knew exactly what you meant has no bearing on the matter whatsoever :)
Comment: @David W. Fenton: what about the SQL syntax used by the Access Data Engine (ACE for short)? That could be informally referred to as 'Access SQL' on a friendly Q&A site such as SO, don't you think? :)
Comment: Just to keep references current, here is the link to the Microsoft Access SQL Reference. For the moment, anyway.
https://msdn.microsoft.com/en-us/library/bb259125%28v=office.12%29.aspx
Answer: You can use the ACE/Jet OLE DB Provider and an ADO Connection object's OpenSchema method to get schema information as a Recordset (which is arguable better than a Collection because it can be filtered, sorted, etc).
The basic methodology is to use adSchemaTables to get the base tables (not VIEWs), then use each TABLE_NAME to fetch adSchemaColumns for ORDINAL_POSITION, !DATA_TYPE, !IS_NULLABLE, !COLUMN_HASDEFAULT, !COLUMN_DEFAULT, !CHARACTER_MAXIMUM_LENGTH, !NUMERIC_PRECISION,!NUMERIC_SCALE.
adSchemaPrimaryKeys is straightforward. adSchemaIndexes is where you will find UNIQUE constraints, not sure wether these can be distinguished from unique indexes, also the names of FOREIGN KEYs to plug into the adSchemaForeignKeys rowset e.g. (pseudo code):
rsFK.Filter = "FK_NAME = '" & !INDEX_NAME & "'")

-- watch for the gotcha that Jet 3.51 allows a FK based on a nameless PK (!!)
Names of Validation Rules and CHECK constraints can be found in the adSchemaTableConstraints rowset, using the table name in the OpenSchema call, then use the name in the call to the adSchemaCheckConstraints rowset, filter for CONSTRAINT_TYPE = 'CHECK' (a gotcha is a constraint named 'ValidationRule' + Chr$(0), so best to escape the null characters form the name). Remember that ACE/Jet Validation rules can be either row-level or table-level (CHECK constraints are always table-level), so you may need to use the table name in the filter: for adSchemaTableConstraints is [].[].ValidationRule will be [].ValidationRule in adSchemaCheckConstraints. Another gotcha (suspected bug) is that the Field is 255 characters wide, so any Validation Rule/CHECK constraint definition of more than 255 characters will have a NULL value.
adSchemaViews, for Access Query objects based on non-paramaterized SELECT SQL DML, is straightforward; you can use the VIEW name in adSchemaColumns to get the column details.
PROCEDURES are in adSchemaProcedures, being all other flavours of Access Query objects including parameterized SELECT DML; for the latter I prefer to replace the PARAMETERS syntax with CREATE PROCEDURE PROCEDURE_NAME in the PROCEDURE_DEFINITION. Don't boterh looking in the adSchemaProcedureParameters, you won't find anything: the parameters can be enumerated by using an ADOX Catalog object to return an ADO Command e.g. (pseudo code):
Set Command = Catalog.Procedures(PROCEDURE_NAME).Command

then enumerate the Comm.Parameters collection for the .Name, .Type for DATA_TYPE, (.Attributes And adParamNullable) for IS_NULLABLE, .Value for COLUMN_HASDEFAULT and COLUMN_DEFAULT, .Size, .Precision, .NumericScale.
For ACE/Jet-specific properties such as Unicode compression you need to use another kind of object. For example, a Long Integer Autonumber in Access-speak can be found using an ADO Catalog object e.g. (pseudo code):
bIsAutoincrement = Catalog.Tables(TABLE_NAME).Columns(COLUMN_NAME).Properties("Autoincrement").Value

Good luck :)
Answer: Check out the docmd.TransferDatabase command. It is probably your best bet for build integration that needs to replicate the data structure
Answer: Compare'Em
http://home.gci.net/~mike-noel/CompareEM-LITE/CompareEM.htm
will happily generate the VBA code need to recreate an MDB.  Or the code to create the differences between two MDBs so you can do a version upgrade of the already existing BE MDB.  It's a bit quirky but works. Note it does not support the new ACE (Access2007) ACCDB etc formats.
I use it all the time.
(OneDayWhen's edit was one third right and two thirds wrong.)
Answer: It's hard to do DDL scripts / queries in Access. It can be done but you'd be better off just creating a copy of the database - deleting all the data and compacting it. Then use a copy of this for recreating the database elsewhere.
Comment: But that wasn't your question. You didn't ask about build integration, you asked about extracting the schema. You can certainly script the schema build process by writing the code, just like the rest of your application.
Comment: I feared this might be the answer.  So build integration is out of question.
Answer: Very helpful post!
I have revised the script to generate the data definition language for SQL server.  I thought it might be useful to someone, so I'm sharing it.  The one problem I ran into is that the VBS script extracts all fields in the table for indexes.  I'm not sure how to solve this just yet, so I extract only the first field.  This will work for most primary keys.  Finally, not all of the data types are proven, but I think I got most of them.
Option Compare Database

Function exportTableDefs()

Dim db As Database
Dim tdf As TableDef
Dim fld As DAO.Field
Dim ndx As DAO.Index
Dim strSQL As String
Dim strFlds As String

Dim fs, f

    Set db = CurrentDb

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.CreateTextFile("C:\temp\Schema.txt")

    For Each tdf In db.TableDefs
        If Left(tdf.Name, 4) <> "Msys" And Left(tdf.Name, 1) <> "~" Then
            strSQL = "CREATE TABLE [" & tdf.Name & "] (" & vbCrLf

            strFlds = ""

            For Each fld In tdf.Fields

                strFlds = strFlds & ",[" & fld.Name & "] "

                Select Case fld.Type

                    Case dbText
                        'No look-up fields
                        strFlds = strFlds & "varchar (" & fld.SIZE & ")"

                    Case dbLong
                        If (fld.Attributes And dbAutoIncrField) = 0& Then
                            strFlds = strFlds & "bigint"
                        Else
                            strFlds = strFlds & "int IDENTITY(1,1)"
                        End If

                    Case dbBoolean
                        strFlds = strFlds & "bit"

                    Case dbByte
                        strFlds = strFlds & "tinyint"

                    Case dbInteger
                        strFlds = strFlds & "int"

                    Case dbCurrency
                        strFlds = strFlds & "decimal(10,2)"

                    Case dbSingle
                        strFlds = strFlds & "decimal(10,2)"

                    Case dbDouble
                        strFlds = strFlds & "Float"

                    Case dbDate
                        strFlds = strFlds & "DateTime"

                    Case dbBinary
                        strFlds = strFlds & "binary"

                    Case dbLongBinary
                        strFlds = strFlds & "varbinary(max)"

                    Case dbMemo
                        If (fld.Attributes And dbHyperlinkField) = 0& Then
                            strFlds = strFlds & "varbinary(max)"
                        Else
                            strFlds = strFlds & "?"
                        End If

                    Case dbGUID
                        strFlds = strFlds & "?"
                    Case Else
                        strFlds = strFlds & "?"

                End Select
                strFlds = strFlds & vbCrLf

            Next

            ''  get rid of the first comma
            strSQL = strSQL & Mid(strFlds, 2) & " )" & vbCrLf

            f.WriteLine strSQL

            strSQL = ""

            'Indexes
            For Each ndx In tdf.Indexes

                If Left(ndx.Name, 1) <> "~" Then
                    If ndx.Primary Then
                        strSQL = "ALTER TABLE " & tdf.Name & " ADD  CONSTRAINT " & tdf.Name & "_primary" & " PRIMARY KEY CLUSTERED ( " & vbCrLf
                    Else
                        If ndx.Unique Then
                            strSQL = "CREATE UNIQUE NONCLUSTERED INDEX "
                        Else
                            strSQL = "CREATE NONCLUSTERED INDEX "
                        End If
                        strSQL = strSQL & "[" & tdf.Name & "_" & ndx.Name & "] ON [" & tdf.Name & "] ("
                    End If

                    strFlds = ""

                    '''  Assume that the index is only for the first field.  This will work for most primary keys
                    '''  Not sure how to get just the fields in the index
                    For Each fld In tdf.Fields
                        strFlds = strFlds & ",[" & fld.Name & "] ASC "
                        Exit For
                    Next

                    strSQL = strSQL & Mid(strFlds, 2) & ") "
                End If
            Next
           f.WriteLine strSQL & vbCrLf
        End If
    Next

    f.Close

End Function

Answer: Roland's answer above (edited by Tobias) worked for me but with a couple of changes. Firstly I solved the issue of finding all fields in the primary key; then the writing to file of the index sql code was in the wrong place:
Option Compare Database
Function exportTableDefs()

Dim db As Database
Dim tdf As TableDef
Dim fld As DAO.Field
Dim ndx As DAO.Index
Dim strSQL As String
Dim strFlds As String

Dim fs, f

    Set db = CurrentDb

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.CreateTextFile("C:\temp\Schema.txt")

    For Each tdf In db.TableDefs
        If Left(tdf.Name, 4) <> "Msys" And Left(tdf.Name, 1) <> "~" Then
            strSQL = "CREATE TABLE [" & tdf.Name & "] (" & vbCrLf

            strFlds = ""

            For Each fld In tdf.Fields

                strFlds = strFlds & ",[" & fld.Name & "] "

                Select Case fld.Type

                    Case dbText
                        'No look-up fields
                        strFlds = strFlds & "varchar (" & fld.SIZE & ")"

                    Case dbLong
                        If (fld.Attributes And dbAutoIncrField) = 0& Then
                            strFlds = strFlds & "bigint"
                        Else
                            strFlds = strFlds & "int IDENTITY(1,1)"
                        End If

                    Case dbBoolean
                        strFlds = strFlds & "bit"

                    Case dbByte
                        strFlds = strFlds & "tinyint"

                    Case dbInteger
                        strFlds = strFlds & "int"

                    Case dbCurrency
                        strFlds = strFlds & "decimal(10,2)"

                    Case dbSingle
                        strFlds = strFlds & "decimal(10,2)"

                    Case dbDouble
                        strFlds = strFlds & "Float"

                    Case dbDate
                        strFlds = strFlds & "DateTime"

                    Case dbBinary
                        strFlds = strFlds & "binary"

                    Case dbLongBinary
                        strFlds = strFlds & "varbinary(max)"

                    Case dbMemo
                        If (fld.Attributes And dbHyperlinkField) = 0& Then
                            strFlds = strFlds & "varbinary(max)"
                        Else
                            strFlds = strFlds & "?"
                        End If

                    Case dbGUID
                        strFlds = strFlds & "?"
                    Case Else
                        strFlds = strFlds & "?"

                End Select
                strFlds = strFlds & vbCrLf

            Next

            ''  get rid of the first comma
            strSQL = strSQL & Mid(strFlds, 2) & " )" & vbCrLf

            f.WriteLine strSQL

            strSQL = ""

            'Indexes
            For Each ndx In tdf.Indexes

                If Left(ndx.Name, 1) <> "~" Then
                    If ndx.Primary Then
                        strSQL = "ALTER TABLE " & tdf.Name & " ADD  CONSTRAINT " & tdf.Name & "_primary" & " PRIMARY KEY CLUSTERED ( " & vbCrLf
                    Else
                        If ndx.Unique Then
                            strSQL = "CREATE UNIQUE NONCLUSTERED INDEX "
                        Else
                            strSQL = "CREATE NONCLUSTERED INDEX "
                        End If
                        strSQL = strSQL & "[" & tdf.Name & "_" & ndx.Name & "] ON [" & tdf.Name & "] ("
                    End If

                    strFlds = ""

                    '''  use the ndx collection rather than tdf
                    For Each fld In ndx.Fields
                        strFlds = strFlds & ",[" & fld.Name & "] ASC "
                        Exit For
                    Next

                    strSQL = strSQL & Mid(strFlds, 2) & ") "
                End If
                ''' write to file for each iteration of the loop to get multiple indexes
                f.WriteLine strSQL & vbCrLf
            Next
        End If
    Next

    f.Close

End Function


Erro no create asp.net

Question:
Não foi possível descriptografar o token antifalsificação. Se este
  aplicativo for hospedado por um Web Farm ou cluster, garanta que todos
  os computadores executem a mesma versão do ASP.NET Web Pages e que a
  configuração  especifique chaves de validação e
  criptografia explícitas. Não é possível usar AutoGenerate em um
  cluster.

Após procurar no google solução não consegui encontrar solução, como posso resolver?
Comment: E o que isso tem a ver com o create?, apresente o seu código... Mas ao que parece o seu problema é relacionado ao `Antiforgery Token`... Aonde e quando você recebe essa mensagem de erro
Comment: Explique melhor o seu problema
Comment: Tenho um formulario enorme, parti ele usando partial view, em varias paginas, ao tentar inserir um botao de create e submetero formulario em qualquer das paginas obtenho esse erro
Answer: Isso se deve a não teres o <code>@Html.AntiForgeryToken()</code> no form ou teres em duplicado (pelas várias partial views).
Comment: @RaphApresentacao o recomendado é utilizar e não remover. Verifique se você tem tanto na view quando na controller. Provavelmente deu erro por que só setou para um deles...
Comment: Foi isso  mesmo eu removi. O AntiForgeryToken() e foi resolvido

Erro no create asp.net


Mostar dados da tabela PHP

Question: Estou com um problema, queria mostrar os dados da tabela respetivos a consulta que é feita. Só consigo mostrar os dois valores dentro do ciclo for. O que quero é mostrar os dados fora do ciclo for, tipo guardar para um array e mostrar esse array.
for($y=2; $y>0; $y--){
                    $base_hndl  =   new SQLite3($dir.$base);
                    $requete    =   "SELECT id, title, start, end, description, jour, mois, annee, date
                        FROM \"event\"
                        WHERE jour=\"$i\"
                        AND id=$y";

                    $resultat   =   $base_hndl->query($requete);
                    $affiche    =   $resultat->fetchArray();

                    $result = "$affiche[title]
";

                    echo $result;

                }

Answer: crie fora o seu laço uma variável vazia do tipo Array. Em seguida dentro do for, utilize a função array_push para inserir no final da variável o resultado encontrado.
Para percorrer a variável utilize o foreach
$array_resultados = array();
for($y=2; $y>0; $y--){
                        $base_hndl  =   new SQLite3($dir.$base);
                        $requete    =   "SELECT id, title, start, end, description, jour, mois, annee, date
                            FROM \"event\"
                            WHERE jour=\"$i\"
                            AND id=$y";
                    $resultat   =   $base_hndl->query($requete);
                    $affiche    =   $resultat->fetchArray();
                    array_push($array_resultados, $affiche);

            }
foreach($array_resultados as $key =>$value){

                $echo "".$value['title']."
";

}

Comment: Não consigo mostrar os dados na tabela.
Comment: Você deseja exibir os resultados EM uma tabela ou os resultados DE uma tabela?
Comment: Os resultados de uma tabela respetivos a consulta.

Mostar dados da tabela PHP


Exercises for Tuvan Throat-Singing (Overtone-Singing)?

Question: I've been fascinated for many years with Tuvan Throat-Singing, particularly the group Huun-Huur-Tu. A few years ago I happened upon a Scientific American article (which I have since misplaced) that enumerated several of the styles.

Khoomei. False-vocal-chord vibration, selecting overtones with a round lip-shape and a soft tongue (Wu, Woah, Wuh, Weh).
Sygyt. Laryngeal vibration, selecting overtones with a tightened throat and a sharply arched tongue (Aaaaa, Iiiiii, Eeeee).
Kargyraa. False-vocal-chord vibration, overtones as with Sygyt.

Does anyone know more than that? (This is the sum of my technical knowledge on throat-singing and it's not enough: I can get about 3, maybe 4 distinct notes with Khoomei; but zero progress on the other two. And often I run out of breath before I can even find the tones.)
Answer: Once you get a few tutorials, you may find a lot of related videos, and maybe you also found the ones below. For me these seem to be the most interesting ones:
(Poliphonic) overtone singing with Anna-Maria Hefele
Answer: Since you're asking for warm-ups, not 'how to'...
I sing in half a dozen throat styles, especially syzgyt.
After studying Hefele a few years back, I moved on to analyzing the intervals I could achieve with vowels (caps are long): I-U II-i III-E IV-o V-A VI-O VII-a VIII-U and minors iii-e v-u vi-O.
With that you can do solfege warm-ups: DU Di DE Do DA DO Da DU... RU Ri RE Ro RA RO Ra RU... MU Mi ME Mo MA MO Ma MU...
You will find that most songs which stayed famous for decades have chords that match those vowels. I'm sure it was unconscious, but that's simply what sounded best, instrumental chords which matched vocal formant chords.
..and that was helpful for awhile but eventually I outgrew that as well.
[I was lately able to make good use of that repurposing it for a polytonal take on yodeling. yo Du LA HE HU = I bV V III(+oct) VIII. Practice dipthong howls to simplify things first.]
It's not quite like we can simply sing multiple notes. Rather it's like our vocal formants come complete with a standard instrumental overtone series, but we are capable of accentuating some harmonics and dampening others to sound more like multiple fundamental notes. The process is bi-directional. Anna-Maria uses vowel sounds as an entry-level means of accessing that harmonic accentuation/dampening, but the vowel formants are ultimately beside the point. The real point is acquiring total accentuation and dampening control of the harmonics. On a prepared guitar this can be done by attaching a miniscule  weight (like a ring of brass wire) to the string, especially near the bridge - in just the same way as it's the high stuff in the mouth which can boost or choke the division-wavelengths of the larger wavelength (by being located in or out of phase with them). Technically we are adding 'Helmholz resonators' which both need to be located correctly, and have 'a' resonant frequency with the harmonic overtones we are accentuating (or make them non-resonant to kill frequencies).
You have roughly 35 registers you can be working in, five locations you can use as your vibrational source, and seven locations you can use as resonators. If you are lucky the five overlap and the seven overlap, but even then it takes practice or planning to know when in a song to change registers for the smoothest transition between them.
That said, these five vibrational registers, along the lines of chest-voice, falsetto, head, whistle are what a typical singer is going to warm up with (if even that). As a polytonal singer for each of those notes (which may well span five octaves if you've learned to use them all) one additionally has to consider the accompanying resonance spanning across the seven resonant chambers top to bottom. For any given note you can pick any second note as a resonant accompaniment. For every single vibrated note you can portamento through your entire range of resonators. For each of those notes, somewhere in that portamento range you will find octaves and fifths of that note which produce those signature syzgyt-sound harmonics intermodulations, those little buzzy rainbow spots, where your sine waves convert to triangle waves due to all the 'generated' harmonic content (as opposed to natural horn/windpipe harmonics).
And that is roughly my recommended exercise, to go through your scales, but, for each note, to additionally slide through the entire octaves of accompanying resonant notes, stopping at all the syzgyt hotspots you can find. With practice you will instantly recall where to find them.
Actually even that is rather tedious, though worth doing once or twice to start with. From there on out I would simply sing your favorite warmups (mine are Peer Gynt's Solvang's Song (in Marita Solberg opera style), Over the Rainbow, and Amazing Grace) but in a style in which your 2nd resonant frequency is like a 2nd bird in flight, swooping a graceful curvy flight-path behind the first (your vibrated tone), stopping for some syzgyt warbling on occasion.
Anna-Maria Hefele was the holy-grail for me just a year or two ago, but today upon a revisit I realized I've even outgrown her, as apparently she is limited to alternating between instrumental syzgyt style and lyrical vocals, while i have learned to do both at once (but not with all vowels; I have to sing some words with entirely wrong vowels). (Perhaps she can too, and simply doesn't for exactly that reason.)
Her voice isn't as rare as the internet makes it out to be. Traditional cowboy yodeling involves some throat singing, which now that I think on it, they probably picked up through contact with the Inuit. This is in turn has left a mark on some bluegrass folk vocal styles. Also many sweet voices naturally resonate unconsciously, though it tends to be in one interval like a fourth or sixth.
Lately I've been emulating synthesizers (even more lately, other vocalists). Anyhow, I also found it useful to sing into a free app pocket oscilloscope on my Amazon device to get my sine (strings) and triangle (horns) waveforms down perfect. Squares, like some arcade-sound synths, are terribly challenging, but can be somewhat reached. Back when I was just after note combos, a good spectrograph tuner was indispensable. Mine arranged the octave in a circle, further rings out for higher octaves - way useful to learn true full-range 'polytonal', as opposed to just throat of some variety.
I volunteer twice weekly in a small venue that plays a wide range of genres of world class musicians
(including Tuvan and Mongolian throat singing bands, one of which gave classes the afternoon before the show - which made an absolute world of difference over what I'd picked up on my own. It instantly unlocked doors and I was star pupil)
, three per night, and over the past year I have evolved to essentially being the backup if not lead singer for every single band playing. Because I typically hadn't met them till after the performance and was sneaking into the act as an unseen audience member, I learned to emulate all the instruments so I could start off just like a reverb extension of their music, totally transparent, then play it by ear to see how much latitude response I had from the band. Typically I'm thrown solos, if not having a delightful counterpoint jam. - Anyhow, the point there is practice practice practice. If you can fit in emulating any instruments in any genre, as polytonal as possible (when you get better, yes, you can actually start working in a third note) - you're golden.
My only gripe is that, while I sing basso-profundo to mezzo-soprano, F0 to F5, having been born male, my chest voice is a couple octaves lower than I'd like it to be, and I'm limited to emulating female vocalists with head voices (which is rarer for females, Marita Solberg for instance). There are a few exceptions I can emulate like Joan Baez, Bobbie Gentry, and Elizabeth Fraser, but still very few. I'm gaining ground here too though, just starting to touch on balancing multiple slightly-voiced lower vibrators, while still working in head voice, like Tori Amos. The more I keep at it, revisiting things which seemed hopeless earlier, the more I keep being able to do. I took to serious singing very late in life and hope it can last. I do find my voice giving out at shows increasingly, especially if it's cold and damp.
For my own shows I find i typically veer into musical vision quests, and end up channeling the music of several western native tribes.
Our local tribe of musicians in Bellingham, WA is actually fairly saturated in throat singers. I don't know if that's a national trend or we're just ahead of the game.
On a reread of your question, I see you are also looking for help even finding the magic spots. Memorize the ones you have found as references. If you can set them to a lyrical song, that will help. Most importantly, move around a lot, doing wauw-wauw-wauw's and reer-reer-reer's (all the vowels, really) all over the place. As with the bass stuff deep in your chest, all that crazy stuff in your mouth is on a sliding frequency spectrum (with some location gaps). Get a feel for sliding along that spectrum. While your bass resonance and treble resonance are in totally different locations, if your bass resonance moves higher, your treble resonance to find that sweet spot will need to move higher too (equally in pitch distance, but less so in physical distance). Think of it like a guitar fretboard, various notes plus n-frets higher in pitch. They are both logarithmic. An inch of travel near the heart is going to require a matching 1/4" of travel in the mouth, or along those lines anyhow.
Another hint that helped me a lot: Buy some good authentic Tuvan throat singing CDs and sing along with them in the car. It's like learning to sing to regular vocals. It helps to emulate a reference.
Anyhow, good luck to all of you angels joining the ranks and making music more alive, down to the vibrating soul of creation.
Answer: Here are some more or less useful "tutorials" on YouTube:
How to sing OVERTONES (Miroslav Grosser)

Overtone singing - basic techniques (Jonny Cope)

Throat Singing tutorial (HomemadeBanjo)

Throat Singing Tutorial (Subtleinductor)
Comment: Thanks for the fast response. If only I hadn't screwed up my sound card yesterday!!! +1 in anticipation of usefulness.
Comment: I listened to some of these today, and I very much like the "HomemadeBanjo" one (with the spectrum analyzer). And then I was led to Inuit Throat singing, which is very similar to a strange song on Black Texicans (Alan Lomax Recordings). Weeeird stuff. *Thanks again!*
Answer: I know about the movie Genghis Blues, which is a documentary about an American Singer that goes on an adventure to train for an international throat singing contest.


Least Squares Estimator Vs Ordinary Least Squares Estimator

Question: Is there any difference between the two terms  "Least Squares Estimator" and "Ordinary Least Squares Estimator". For convenience, I'll refer to them as LS and OLS respectively. I have read various articles on this and could find LS, OLS, Weighted LS, Fuzzy LS and so on. But my problem is between LS and OLS. Are they referred to the same method of estimation or not?
https://cpb-us-w2.wpmucdn.com/people.uwm.edu/dist/2/109/files/2016/04/2000_NAAJ-zdngkl.pdf
Please see page 9/22 of the above link for reference.
Answer: Dropping out the Estimator keyword, Least Squares and Ordinary Least Squares, referred as LS and OLS respectively, are not the same. LS is much more general. It consist of linear and non-linear LS. And, linear LS consist of OLS, and some other types (e.g. GLS: Generalized LS, WLS: Weighted LS). The nonlinear part is itself a different world. In LS methods, the key thing is minimizing the sum of squared residuals. So, any one of the above listed method having this objective functions is a LS estimator. So, LS estimator is not that much definitive. When you make assumptions about the model and the error, it'll boil down to some of the listed alternatives. But, sometimes (and maybe commonly), it is being used for referring to OLS. The author of any article/note saying just LS estimator is probably referring to some sort of special case of it, by making related assumptions, probably somewhere in the article/notes. In your link, Page 9, Section 4.4, it is referring to OLS, in which he actually refers to it in the beginning of the second paragraph.


What does the subscript of a CDF mean?

Question: I am working with the composition method for generating a random variable $X$. I have always seen CDFs denoted as $F_X(x)$ but my question is what does it mean if the CDF is $F_I(X)$. So specifically what does the change from $X$ to $I$ imply?
Edit: I flipped the X and x in my original post.
Comment: No, you have always seen them written as a **function** $F_X(x)$ ($X$ and $x$ weren't at the right place). Now  $Y:=F_I(X)$ is a (deterministic) function of a random variable therefore itself a **random variable** and no longer a function ($I$ being another random variable).
Comment: Besides, I have cancelled the "statistics" tag : it's only probability issues that are concerned here.
Answer: I think you swaped uppercase and lowercase $X$.
By definition for a given random variable $X$ you can evaluate the CDF $F_X$ at the point $x$ : $$F_X(x) = \mathbb{P} (X \leq x)$$
If you want to calculate the CDF of an other random variable $Y$ the expression becomes :
$$F_Y(x) = \mathbb{P} (Y \leq x)$$
Answer: I have NEVER seen $F_x(X),$ but always only $F_X(x).$ The capital $X$ identifies which random variable it is; the lower-case $x$ is the argument to the function. Thus $F_X(3) = \Pr(X\le 3)$ and $F_Y(3) = \Pr(Y\le 3).$
Without this distinction between capital $X$ and lower-case $X,$ how would one even understand something like $\Pr(X\le x)\text{?}$

What does the subscript of a CDF mean?


Question regard inverse limit ( homeomorphism)

Question:
Let $\left \{ X_n: n \in \mathbb{N} \right \}$ be a sequence of metric spaces such that $X_{n+1}\subseteq X_{n}$, for all $ n \in \mathbb{N}$. Define $f_n: X_{n+1} \longrightarrow X_{n}$ as $f_n(x)=x$, for all $x \in X_{n+1}$. Prove $X_{\infty} \cong \bigcap_{n \in \mathbb{N}}X_n $.

This is more like a check to see if my work is correct:
What i tried was to  define
\begin{align*} \alpha: X_{\infty} &\longrightarrow \bigcap_{n \in \mathbb{N}}X_n  \\
x=(x,x,\cdots&) \longrightarrow x
\end{align*}
I proved $\alpha$ is bijective, by proving is open i said the following:
Let $U$ be a open subset of $X_\infty$ and $(x_n) \in U $ then there exist  (We proved is a basis for $X_\infty$)  $\rho^{-1}(U_{n_0})$, $ n_0 \in \mathbb{N}$ such that
$$
(x_n) \in \rho^{-1}(U_{n_0}) \subset U
$$
Hence $\rho((x_n)) \in U_{n_0} $ , i.e, $x \in U_{n_0}$ ($\rho$ is just the projection map restricted to $X_\infty$).
Now here comes the tricky part:

One can see that $f_n$ is continous for all $n \in \mathbb{N}$, in fact is an homeomorphism (is the inclution map) so that $f^{-1}(U_{n_0})$ is an open set in $X_{n_0+1}$ and I can keep going like this, for all $N\geq n_0$, also because $U_{n_0}$ is open in $X_{n_0}$, it is also open for every $X_1\supseteq  X_2\supseteq  \cdots \supseteq  X_{n_0-1}$
In that case I've proved that there exist open set that contains $x$ for all $X_n$ , so    if $U$ is open in $X_\infty$ then $\alpha(U)$ is open.

Is this correct?
Comment: I'm not familiar with the definition of $X_\infty$ in this context, could you provide it?
Comment: Is the notation used for the inverse limit: https://en.wikipedia.org/wiki/Inverse_limit
Comment: [Linked](https://math.stackexchange.com/questions/3254836/inverse-limit-contininuity-question-to-prove-x-infty-cong-bigcap-n-in).
Answer: A truly rigorous verification of your proof may depend on the exact definition of inverse limit which you are using (for instance, in Engelking's "General topology" it required to provide the bounding maps from $X^m$ to $X^n$ for any $m\ge n$). Next, you didn't define what is $f$ (in $f^{-1}(U_{n_0})$). At last, opennes of $U_{n_0}$ in $X_{n_0}$ does not imply that $U_{n_0}$ is open in $X_n$ for $n<n_0$, because it is not given that $X_n$ is an open subspace of $X_{n_0}$. On the other hand, it seems that it suffices to have $U_{n_0}$ open in $X_{n_0}$, because then $(x_n) \in \rho^{-1}(U_{n_0}) \subset U$, so then $x\in U_{n_0}\cap \bigcap_{n\in\Bbb N} X_n$, which should be an open subset of $\bigcap_{n\in\Bbb N} X_n $ (I assumed that $f_m$'s are topological embeddings, so $X_{m+1}$ is a subspace of $X_m$ for each $m$).


Azure Data Lake Store Benchmarks

Question: To Developers,
I am doing benchmarks for Azure Data Lake and I am seeing about ~7.5 MB/S for a read of an ADL Store and a write to a VHD all in the same region.  This is the case for PowerShell and C# with the code taken from the following examples:
PowerShell Code is from https://azure.microsoft.com/en-us/documentation/articles/data-lake-store-get-started-powershell/
C# Code is from https://azure.microsoft.com/en-us/documentation/articles/data-lake-store-get-started-net-sdk/
Are the above code samples acceptable for a benchmark test or will a new SDK be delivered that will enhance the throughput?
Also, are there expected throughput numbers when ADL Store becomes generally available?
Thanks,
Marc
Comment: Since the Azure Data Lake services are still in preview, I don't think that any benchmarks will deliver valid results. That'll change between now and GA anyway. There are also cache mechanisms in place, which will distort your results. As soon as the services are GA, I would be happy if there are benchmarks, like the one you started with.
Comment: You also need to consider, that the analytical services will be able to retrieve several blocks simultaneously.
Comment: @SaschaDittmann i don't disagree with your premise but i still find OP's question to be valid. OP's question is whether the linked code is worthy to be used in a benchmarking context. Creating a fair benchmark execution path is always non-trivial and warrants raising concerns on whether the code provides an accurate view or misleading view of performance.
Comment: To Sasha and Chris, thanks for the input. Saveen Reddy (MS Azure Data Lake  Evangelist) commented that Azure Data Lake Store will be GA'ed Summer-ish 2016.                                                                                Regards, Marc
Comment: I totally agree, that this is a valid question - that's why I gave it a +1 - and I've got already some ideas how to setup a benchmark test. As soon as I'm done with my solution, I'm going to post it here.
Answer: The code provided in the documentation can be used to build benchmark tests. The SDK will go through a few releases and updates prior to Azure Data Lake being generally available. These will include performance improvements in addition to features.
On the topic of performance benchmarks, our general guidance is as follows. The Azure Data Lake services are currently in preview. We are continually working to improve the services including performance through this preview phase. As we get closer to general availability, we will consider releasing additional guidance on the type of performance results to expect. Performance results depend heavily on many factors such as test topology, configuration and workload. Therefore it is difficult to comment your observations without examining all of these. If you can reach us offline with the details, we will be happy to take a look.
Amit Kulkarni (Program Manager - Azure Data Lake)
Answer: I started to write an Azure Data Lake Storage Throughput Analyzer and put the first code bits on GitHub.
You should run that tool on an Azure VM to not measure you internet connection.
Please feel free to add you thoughts and code contributions to my GitHub repo as well.
I hope this helps.
Comment: Sascha, Thanks will try it out. Regards, Marc

Azure Data Lake Store Benchmarks


Java-Number of scores needs to be one less in answer

Question: So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {

    public static void main(String[] args)
    {
        double[] scores = new double[10];
        double sum = 0.0D;
        int count = 0;

        Scanner sc = new Scanner(System.in);

        do {
            System.out.print("Enter a new score (-1 to end): ");
            scores[count] = sc.nextDouble();

            if (scores[count] >= 0.0D)
                sum += scores[count];

        }

        while (scores[(count++)] >= 0.0D);

        System.out.println("The total number of scores is:  " + count );

        double average = sum / (count - 1);
        int numOfAbove = 0;
        int numOfBelow = 0;

        for (int i = 0; i < count - 1; i++) {
            if (scores[i] >= average)
                numOfAbove++;
            else
                numOfBelow++;
        }

        System.out.printf("Average is " + "%.2f\n",average);
        System.out.println("Number of scores above or equal to the average " + numOfAbove);
        System.out.println("Number of scores below the average " + numOfBelow);

   }

    }

How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
Comment: I did this System.out.println("The total number of scores is:  " + (count-1)); but it seems quite ghetto so I think theres probably another way
Answer: System.out.println("The total number of scores is:  " + count );

You probably want:
System.out.println("The total number of scores is:  " + (count - 1));

Answer: You could also change your loop from a do while to a while loop as follows,
while (true) {
  System.out.print("Enter a new score (-1 to end): ");
  double tempDouble = sc.nextDouble();

  if (tempDouble >= 0.0D)
    scores[count] = tempDouble;
    sum += scores[count];
    count++;
  else
    break;
}

That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.