How can I recover an Exchange 2013 mailbox which I disabled?

Question: My company has Exchange 2013 and I disabled a mailbox in the Exchange Admin Center under the presumption that this would work in the same way as disabling an account in Active Directory would. (Ability to re-enable the account at any time).
I just went looking in the recipient list to see if I could re-enable the disabled account however, it is totally missing.
Is it possible to recover the mailbox? What is the process?
Answer: Disabled mailboxes do not show up in the main view. To reconnect a disabled mailbox:

In the EAC, navigate to Recipients  > Mailboxes.
Click More, and then click Connect a mailbox.
A list of mailboxes that are disconnected on the selected Exchange server in your Exchange organization will be displayed.
Note:
  This list of disconnected mailboxes includes disabled mailboxes, deleted mailboxes, and soft-deleted mailboxes.
Click the disabled mailbox that you want to reconnect, and then click Connect.
In the window that asks if you're sure that you want to reconnect the mailbox, click Yes.
Exchange will reconnect the disabled mailbox to the corresponding user account.

https://technet.microsoft.com/en-us/library/jj863439(v=exchg.150).aspx
If you cannot see the mailbox when trying to reconnect, run the following in the Exchange Management Shell.
<code>Get-MailboxStatistics -Database "DB NAME" | ForEach { Update-StoreMailboxState -Database $_.Database -Identity $_.MailboxGuid -Confirm:$false }
</code>
Comment: Thanks for this answer. I followed your instructions however, the mailbox did not appear in the 'connect a mailbox' window.
Comment: How long ago did you disable it?
Comment: Within the last hour.
Comment: Exchange keeps disconnected mailboxes for 30 days (by default), so it should still be stored. Please confirm the mailbox retention period by looking for DeletedItemRetention or anything related to that in the output of the following Exchange PowerShell command:
Get-MailboxDatabase -Identity YourDBName | Format-List
Also try the Shell method in the link above and see if it succeeds.
Comment: I fixed the problem by running
`Get-MailboxStatistics -Database "DB NAME" | ForEach { Update-StoreMailboxState -Database $_.Database -Identity $_.MailboxGuid -Confirm:$false }`

Prior to following your solution.
Comment: Good find, looks like it might have been caused by slow AD replication since you disabled it so recently. More information for anyone interested [here](https://technet.microsoft.com/en-us/library/jj860462(v=exchg.150).aspx).
Answer: You can identify disabled mailboxes in the exchange organization from below command:
Get-MailboxDatabase | Get-MailboxStatistics | Where { $_.DisconnectReason -eq "Disabled" } | ft DisplayName,Database,DisconnectDateUse
Steps to recover a deleted mailbox:

Having an enabled AD user to attach it to
Use Exchange Management Shell (EMS) to Run Connect-Mailbox cmdlet

3. After connecting the mailbox, you can export it using the New-MailboxExportRequest cmdlet.
You can also check this link.


Vertically center a loader using tailwindCSS with Laravel Nova dashboard

Question: I have an empty page, and I want to display a loader before redirecting.
 <template>

        <atom-spinner
            :animation-duration="1000"
            :size="160"
            :color="'#1f6492'"
        />

</template>

If I do that, the h-screen class will take the screen size, without taking the header size, and the margins. So, at the end, it will not be centered vertically.
If I had a way to fill my screen with the , I could do it easily
How should I do to center the loader in the center of the screen ?
Here is a screenshot:
Comment: Can you fork one of these? https://codesandbox.io/examples/package/tailwindcss and share the link.
Comment: I forked it but it is React not Vue, and I can't figure out how to make it work :(
Answer: A small piece of inline CSS may do the trick:

  <atom-spinner
    :animation-duration="1000"
    :size="160"
    :color="'#1f6492'"
  />

The 60px value should be adjusted to match the height of the header.
There may be a better way, but assuming that you don't have access to the parent element that wraps the header and the content area, I can't recall a Tailwind class that can manage this.
Comment: yep, it did the trick ! I had to add !important so that it work.


How to know if there are visible annotations in a map area in SwiftUI

Question: i've came here after searching for a while a solution to the problem i have but i couldn't find anything helpfull.
I'm displaying a map in iOS16 using only swiftUI and i'm wondering if its any way to know if the region of the map it's displaying has any annotations or not. I want to display a list in the bottom of the map with the annotations that are visible in that map area, but if the user drag to another position without annotations i want to hide that list.
Many thanks by the way.
Answer: Since the SwiftUI design is to generate the view data hierarchy from the model data you need to do this before there are any annotations added to the map. Ie make a state to hold the visible map rect (that you supply and binding to the Map) and using onChange or task(id:) query your database using the new map rect.


Fastest way to solve linear congruent equation

Question: Whats the fastest way of solving $85x=12\pmod{19}$. I can solve it but I want a quick way. I can use facts like $0=\pm19\pmod{19}$ but I am not that fast using that method.
Answer: $85x=12 \mod 19$ is the same as $9x=12 \mod 19$. Multiply by 2 to get $18x=24 \mod 19$ or $x=-24=14 \mod 19$
Comment: why is $x=−24=14\pmod{19}$?, are you dividing?
Comment: $-24=-24+2*19=14 \mod 19$.
Answer: Hint $\displaystyle\rm\ mod\ 19\!:\ x\equiv \frac{12}{85}\equiv\frac{12}{17\cdot 5}\equiv\frac{12}{-2\cdot 5}\equiv\frac{-6}5\equiv \frac{-25}{5}\equiv \frac{-5}1$
Or: $\displaystyle\rm\ \ \,mod\ 19\!:\ x\equiv \frac{12}{85}\equiv\frac{12}{9}\equiv\frac{24}{18}\equiv\frac{5}{-1}\ \ $ (this is Gauss' algorithm)
Answer: Note that $85=9\ (\rm{mod}\ 19)$. So you're solving $9x=12\ (\rm{mod}\ 19)$. The fastest way would be to know an inverse of $9$ modulo $19$ (for example $17$) and multiply through by this inverse to get $x=12\cdot 17=14\ (\rm{mod}\ 19)$. Alternatively, expand the definition of a congruence to get $9x=12+19n,\ n\in\Bbb{Z}$, rewrite that as $9x-19n=12$, and solve it as you would solve a normal linear Diophantine equation.
Answer: First 'reduce' $85x=12\pmod{19}$ into a 'standard form':
$\tag 1 85x=12\pmod{19} \text{ iff } 9x=12\pmod{19} \text{ iff } 3x=4\pmod{19}$
The smallest positive integer that solves $3x=4\pmod{19}$ is found by taking these two steps:

$\quad \text{Let } k \ge 1 \text{ be the smallest integer such that } 3 \text{ divides } 4 + 19k$
$\quad \displaystyle \text{Set } x = \frac{4 + 19k}{3}$

Does $3$ divide $23$? No.
Does $3$ divide $42$? Yes and $\frac{42}{3} = 14$.
$\tag {ANS} x \equiv 14 \pmod{19}$


javascript: google geo - map

Question: i have the following map of the world:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Google Visualization API Sample</title>

instead of displaying a map of the entire world i would like to know how to display just the US?
Answer: From your example, set the region option on the geomap:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Google Visualization API Sample</title>

Not quite sure why you are setting the popularity of other countries to just center on the US though.
Comment: To get the states use "US" instead of "us_metro" for region option
Comment: jack where can i find a tutorial on this? i dont want any other countries besides the US and its sttates
Comment: then just use region: 'us_metro', in the code you supplied replace  geomap.draw(data, null); with the two lines I gave you.
Comment: that gives me all the counties and i do mean COUNTIES i just want the states, how do i do it?
Comment: It won't give you the states. The us_metro is region will give you the basic metropolitan areas of the United States. That appears to be as detailed as it will be.

javascript: google geo - map


Counting the number of combinations of pairs for two sets with the same number of elements.

Question:
I have two rows, on the first row, I have $A = \{1,2,3, \ldots, n\}$ and on the second row $B = \{n+1, n+2, \ldots, 2n\}$. What is the number of combinations of pairs that can be obtained with an element from every set?

For example if $A = \{1,2\}$ and $B = \{3,4\}$, then we have: $(1,3),(2,4)$ - first combination; $(1,4),(2,3)$ - the second combination. That mean for $n=2$ we have $2$ combinations.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Hint: You are really just trying to count the number of bijective functions $f\colon A \to B$, where $|A| = |B| = n$. The contents of each set aren't really important; you could pretend that $A = B$ so that you would be merely counting permutations.
Comment: Tk for your response, but I'm not sure if it is OK. For example for n=3, we have the following combinations: (1,4), (2,5), (3,6) - a combination; (1,4), (2,6), (3,5) - another comb; (1,4), (3,6),(2,5) - comb; (1,4), (3,5), (2,6) - comb.; (1,5),(2,4),(3,6) comb ..etc
Comment: For $n = 3$, there are exactly $6$ combinations:
$$
(1, 4), (2, 5), (3, 6) \\
(1, 4), (2, 6), (3, 5) \\
(1, 5), (2, 4), (3, 6) \\
(1, 5), (2, 6), (3, 4) \\
(1, 6), (2, 4), (3, 5) \\
(1, 6), (2, 5), (3, 4)
$$
Comment: OK. In my case will be: 2n! because for n = 3 we also will have: (1,4),(3,6), (2,5);   (1,4),(3,5),(2,6);  (1,5),(3,6),(2,4); (1,5),(3,4),(2,6);  (1,6),(3,5),(2,4);  (1,6),(3,4),(2,5).


rsync backup keep deleted files

Question: I have to backup a set of userdata with rsync. There is just one little thing I cant figure out how to do.
When a user deletes a file it is kept on the server. This is fine since it might have been deleted by mistake, but it would be nice if it did not stay there forever.
So how do I make rsync delete files on DEST when they have not been precent on SRC for a certain amount of time (say, 7 days)
I know that I could just write a script that manually uses rsync on each file in the folder and then determines if the file on DEST should be deleted, but it would be kind of dumb to do this just to learn later on that rsync has this feature already. I cant find it though.
Many thanks for you time
Answer: Rsync won't do this on its own. Something like rsnapshot will let you maintain multiple generations of rsync-based backups (hourly, daily, monthly, etc) such that you can retrieve an accidently-deleted file. By using hard links, rsnapshot lets you keep a number of snapshots laying around without using a lot more space than the "cost" of a full backup.
There are other solutions out there that do the same thing-- rsnapshot just happens to be one I have personal experience with. (I highly recommend using the "sync_first" option if you do decide to use it...)
Comment: Many thanks, will look into it, seems to be just the thing I need.
Comment: Sadly, rsnapshot is no longer [maintained](https://github.com/rsnapshot/rsnapshot/issues/191).
Answer: The --backup --backup-dir= flags might be what you are looking for, if you specify a relative path for the backup-dir a directory will be created inside your destination directory and any file deleted will be stored with it's original pathing inside that directory.  If you want to use an absolute path that of course will also work.
Purging old deleted files is another problem, that my usage of --times makes more complicated , as the timestamp on the deleted files will reflect the last modified time on the file and not the time of deletion.  One option I am considering is to build the backup-dir value using some sort of date string and use that to parse and purge over time.  e.g. --backup-dir=/DELETED_FILES/$(date "+%Y_%m_%d-%H_%M_%S")
Play with it on some sample files, the simplist version of this would be:
rsync --delete --backup --backup-dir=DELETED_FILES/ --recursive --times src/ dest/

or a date stamped version to play with would be:
rsync --delete --backup --backup-dir=DELETED_FILES/$(date "+%Y_%m_%d-%H_%M_%S") --recursive --times src/ dest/

I would place the DELETED_FILES directory on an absolute path outside of the destination directory, you might want to do otherwise.
Comment: Amazing, I just started writing my own backup dir logic and came across this. There's already built-in functionality to do this!
Answer: Once a week, I use the --delete option of rsync
RSYNC_OPT="--stats --delete --delete-excluded -avvzpogte  ssh --exclude-from /root/etc/exclude.txt"

Rest of the time, I do incremental backup
RSYNC_OPT="--stats -avvzpogte ssh --exclude-from /root/etc/exclude.txt"

Both scripts are called by cron
Comment: I actually considered this, but just wanted to know if there was a more "elegant" solution. But thanks none the less :)
Answer: Have you done a "man rsync"?  The --delete switch does what you want, but use it carefully.
If you really want to have that seven-day delay, consider using rsnapshot.  It uses hard-links to conserve space for all identical files.
Answer: Look into rsnapshot.  It uses rsync to do the transfer but on top of that it manages point in time snapshots using hardlinks.  It will let you determine how often and how many snapshots to hold onto as well.

rsync backup keep deleted files


Make simple substraction in PostGIS with Map Algebra operation

Question: I have multiple raster images in my PostGIS database, and created tiles of each raster. Now I want to subtract the values of one raster from a second raster image and I want to save the changed values in a third raster image. On postgis.net are some examples but they weren't so helpful for my specific question. Can anyone help me?
Answer: For some useres, who have the same problem I got the answer. Following command calculaes the diffrence between two rasters, that are saved in separate table in postGIS:
<code>SELECT ST_MapAlgebra(t1.rast,t2.rast, '([rast1]-[rast2])') AS rast INTO diffrence FROM table1 t1, table2 t2;
</code>


Why am I getting a "C compiler cannot create executables" (successfully written C code prior to this and compiles that)?

Question: This is the error I am getting when typing ./configure :
<code>checking build system type... x86_64-apple-darwin11.3.0
checking host system type... x86_64-apple-darwin11.3.0
checking target system type... x86_64-apple-darwin11.3.0
checking whether the C compiler works... no
configure: error: in `/opt/ruby-1.9.3-p125':
configure: error: C compiler cannot create executables
See `config.log' for more details
</code>
As is obvious by above, I am trying to compile the Ruby source code. I did some research but doesn't look like anybody has attempted compiling the code themselves on Lion. I am currently running 10.7.3 OS X Lion, Macbook Pro.
Comment: Do you have a the [developer tools](https://developer.apple.com/xcode/) installed?
Comment: Stupid question maybe, but what does the `config.log` say?
Comment: Yes, the latest Xcode. I have compiled C programs before no problem, its just compiling source code. Its my first time and I am trying to learn.
Comment: @owlstead not stupid, I think its more stupid that I don't know how to access it?
Comment: Try mipadi's advice first, then look for it. If you find it, open it in a plain text editor. If you cannot find it one of the geniusses here will probably know where it is :)
Answer: If you have Xcode 4.3+, did you install the command-line tools? You can download them from within Xcode's preference pane, or from here.
Comment: hmm, I am not sure if I have the command line tools installed. I will check. How can I test whether I do or not?
Comment: Looking, but I see nothing that allows me to download it or if I even have it.
Comment: 4.2 I just looked around and it is not the latest, but would getting the command line tools matter that much in an update?
Comment: @Andy: Xcode 4.3+ is bundled differently. If you have 4.2, there's an option to install command-line tools when you run the installer.
Comment: Downloading it now. Since we are on the subject of Xcode, each bundle is installed and kept on my mac. Feel like its a waste of space. Should I delete the older versions? And it seems Lion also changed the directory structure of Xcode. Any idea why?
Comment: @Andy: Xcode 4.3 is packaged as a `.app`, making it easier to distribute and update through the App Store. Once installed, you can safely delete `/Developer`.


SSRS Category grouping for one big pie

Question: Dataset:

This is the dataset I am having an issue with. I expect to have more as time goes on so the solution will have to be dynamic. As you can see, the City is exactly the same, but when I put it into my pie chart I get this:

I've looked for over two hours now as to how to combine these two wedges to get one big pie, but =sum(Fields!Quantity.value) will not do it in the values or the Category Groups areas on the chart. What would the expression be, and would it go in the values area or the Category Groups area under Chart Data?
Thank you so much!
Comment: Suggestion: pie charts are not the best way to display data esp. using 3d affects.  https://www.perceptualedge.com/example12.php
Comment: How about `=SUM(Fields!Quantity.value)` ?
Comment: Sorry, I mistyped that line. It SHOULD be Quantity that's not summing up.
Comment: Is your City in the **Category Groups**? If so, are you sure that one of them doesn't have a space at the end?
Answer: In your char properties, for Values select Quantity column:

And for the Category Groups, select City column:

So you will end up with SUM(Quantity) for values and city for category groups:

This should fix the chart and should be displayed as one big pie:

Side note, you should ensure that the City values doesn't have any trailing spaces at the end so that when grouping it will group correctly.
Comment: I think your answer, @MahmoudGamal , is correct and am marking it as such. I didn't want to cloud the question with some additional details, but those details probably would have made the question more useful to the community. I don't know how else to explain it other than A) more columns were at work behind the scenes, and B) there's a data integrity issue that is being worked on that didn't allow my graph to work as advertised. Thanks!

SSRS Category grouping for one big pie


war-handler no longer in lib-noir?

Question: I'm trying to upgrade my Clojure web app to the latest version of lib-noir and it's failing to compile because middleware/war-handler no longer exists. If I remove "(def war-handler (middleware/war-handler app))" from my app will it still work correctly?
Answer: war-handler was removed in this commit because it was deemed no longer necessary. From the cahnge it looks like you can now use wrap-base-url or app-handler to get the same effect.

war-handler no longer in lib-noir?


SharePoint 2010: Linq to Objects, Check if User is in another List and use of current Item

Question: my use-case: I have 2 SPLists, let's call one events, the other attendees.
What I want: Show a "register" or "unregister" button (in a visual web part at the dispform of the event-list) depending of the current User can be located in the attendee-list for the current event.
So, if the current user is registered for the event, page_load should show the "unregister"-button or the "register"-button if he's not.
I get the current Item via
currEventItem = (SPListItem)SPContext.Current.Item;
And the current user via
currentUser = website.CurrentUser;
userString = currentUser.ID.ToString() + ";#" + currentUser.LoginName.ToString();
Now I wanted to use System.Linq (Linq to Objects) to execute the following Query (pseudo-sqlsyntax):
select * from AttendeeList where userString equals attendeeList.Name
AND currEventItem.Title equals AttendeeList.EventTitle
The Name-Field in the attendeeList is a user (person or group, using german version here so I hope this is the actual translation) field.
My Problem, and the actual question: I don't get the linq syntax to work. Could anyone help me out here? Would be great!
edit: Later on, I want to show the corresponding button depending on the result is NULL or not NULL. Hope this works? If this is not the way to go, another solution would be greatly appreciated :)
Answer: This will give you true or false which you can apply to your checkbox?:
Boolean exists = (AttendeeList.Where(m=> m.Name == userString)
                 .Where(m=> m.EventTitle == currEventItem.Title).Count() > 0);

Comment: Thank you for helping me find the way ;) The actual syntax is `bool foundUsers = (from SPListItem item in tn.Items
                             where item["Name"].ToString() == userString
                             && item["Veranstaltung"].ToString() == currVstItem.Title
                             select item).Count() > 0;`
Comment: you should be able to use item.Name if the procedure is strongly defined but if it works then excellent


Why is it obvious that this integral is undefined?

Question: If we have the following integral:
$$\int_0^1\frac{1}{\left(x+a\right)\left(x+2\right)}\,dx$$
Why is it that it is obvious that this integral will be undefined for $0>a>-1$?
I have a rough idea that one knows that this creates an asymptote at $x=-a$ and this means that if $-a$ lies in the range $0<-a<1$ then you are trying to get the area under something rushing off to an asymptote. Why is it that this is so immediately obvious? Could somebody explain the reasoning to reach the conclusion that it is undefined for the values above to confirm that mine above is correct?
Answer: It isn't obvious until you have looked at many of these. I will try to give an informal explanation of why some people would think of it as obvious.  It isn't just about the asymptote, but about the order of the asymptote: $x^{-1}$, $x^{-2}$, and $x^{-1/2}$ behave differently around their asymptotes at $x = 0$.
Informally, if we have a "order $1$" asymptote, like $1/x$ has at $x = 0$, then the area trapped by the curve on each side of the asymptote will be infinite.   In particular, we have rigorous results such as $\int_0^1 x^{-1}\,dx = \infty$ and $\int_{-1}^0 x^{-1}\,dx = -\infty$.
This leads to an informal rule of thumb which can be applied in this setting to see that the overall integral won't converge.  The $1/(x+2)$ part won't affect the behavior between $0$ and $1$ because $1/(x+2)$ is bounded on that interval.   The $1/(x+a)$ piece is raised to the power $1$, so it will behave like $1/x$ would at $x = 0$.
The second part of the informal rule of thumb says that if we have a function such as $1/\sqrt{x}$ (or more generally $1/x^c$ for $0 < c < 1$), then the area trapped by the vertical asymptote will be finite.  In particular, we rigorously obtain $\int_0^1 x^{-1/2}\,dx = 2$.  Similarly, the informal rule of thumb says that $$\int_0^1 \frac{1}{(x+a)^{2/3}(x+2)}\,dx$$ will converge for any value of $a \in [0,1]$.  Because of the $2/3$ power, this integral will act like the integral of $x^{2/3}$ does around $x = 0$.
The final part of the informal rule of thumb says that if we have $1/x^c$ for $c \geq 1$, then the area trapped by the vertical asymptote will be infinite. So, rigorously, the integral $\int_0^1 x^{-3}\,dx$ will not exist.
There is one other issue which happens when the asymptote is not at the edge of the interval of integration. In this case, in order for the overall integral to exist, the integrals on both sides of the asymptote must exist, and in particular both of these must be finite. This is why we do not compute $\int_{-1}^1 x^{-1}\,dx$ to be zero.
That is the rule of thumb when there is a vertical asymptote. There is a different rule for horizontal asymptotes. So, for example $\int_2^\infty 1/x^c\,dx$ converges if and only if $c > 1$, while $\int_0^2 1/x^c\,dx$ converges for $0 < c < 1$.  (We can convert between the two forms, actually, by thinking about expressing the area as a double integral and changing the order of integration.)
Comment: This may be getting beyond the intent of the question, but in more advanced settings, this kind of phenomenon explains why there are conditions on which $L^p$ spaces are contained in which other $L^p$ spaces. See https://en.wikipedia.org/wiki/Lp_space#Embeddings for the statement of the result.
Answer: Assuming $a\ne2$,$$\begin{align}\int_0^1\frac1{(x+a)(x+2)}\,dx&=\frac1{2-a}\int_0^1\left(\frac1{x+a}-\frac1{x+2}\right)\,dx\\
&=\frac1{2-a}\left[\ln(x+a)-\ln(x+2)\right]_0^1\\
&=\frac1{2-a}\left(\ln\left(\frac{1+a}{a}\right)-\ln\left(\frac{3}{2}\right)\right)\end{align}$$
So for $a\in(-1,0)$, you have $\frac{1+a}{a}<0$, and so the integral is undefined in this range.
Comment: $\frac{1}{x+a}$ has a non-integrable singularity at $-a$. Plug $a = -\frac{1}{2}$ into your formula, and it contains a $\ln (-1)$.


In a CW complex, what is the closure of a cell $e_{\alpha}^n$?

Question: Is the closure of a cell $e_{\alpha}^n$ exactly $\Phi_{\alpha}^n(D_{\alpha}^n)$?I can only show $\Phi_{\alpha}^n(D_{\alpha}^n)\subset\overline{e_{\alpha}^n}$.
Comment: I guess that $D^n_\alpha$ is the closed unit ball in $\Bbb R^n$?
Comment: @Saucy O'Path exactly
Comment: Saucy O'Path I get it,thank you!
Answer: Note that $D^n_\alpha$ is compact, so $\Phi^n_\alpha(D^n_\alpha)$ is compact and thus $\overline{e^n_\alpha}\subset\Phi^n_\alpha(D^n_\alpha).$  And this is sufficient, since $CW$ complexes are Hausdorff (see Proposition A.3 of Hatcher's book for the details).


Trying to get all this terminology straight in logic

Question: Really confused on the terminology here.
According to a few resources as-linked:
Valid is defined as a logical form where it is impossible to have true premises leading to a false conclusion. It doesn't mean the premises are necessarily true. Just that if they were true, the conclusion would need to be true as well.
Sound is defined as a valid logical form where the premises are indeed true.
But then we also have "semantic consequence" denoted $\Gamma \vDash \varphi$ which normally means "if everything on the lefthand side is true, then the stuff on the righthand side is true." Sometimes this is also referred to as "validity" or "tautology."
But this also seems like it is clashing with the definition of "sound" as well.
So I'm really quite confused how we're supposed to be defining and separating these terms out. I'm seeing different answers on Wiki, different answers in books, different answers in other Math StackExchange posts, etc.
I'm going nuts over here trying to separate all these concepts (metalogic vs. logic, soundness vs. validity, semantic vs. syntactic, etc) when every other resource is constantly merging stuff together in vague ways.
Once and for all what is the definition of validity? Soundness? Completeness? Syntactic consequence? Semantic consequence? Logical consequence? Tautology? Theorem? Axiom? Inference? Formula? Sentence? Expression? Proposition? Statement? Relation? Connective? Operator? Are any of these actually synonyms of each other? How are they different?
Comment: @user525966 The definitions you give for "valid" and "sound" strike me as more common in philosophical literature than in mathematics or (formal) logic. Obviously there is some connection intended between these more "philosophy" definitions and the mathematical ones, but they aren't the same. Personally, I find a lot of "logic for philosophy" to be quite bad and to create more confusion than it dispels.
Comment: In $\vDash\varphi$ is is not $\vDash$ that is a tautology. Rather, $\vDash\varphi$ asserts that $\varphi$ is a semantic consequence of nothing -- which happens to be the case when $\varphi$ is a tautology.
Comment: @user525966: For example, in first-order logic the formula $\forall x(x=x)$ is always true, but is not a tautology. To the extent one uses "tautology" about non-propositional formulas at all, it means a substitution of a propositional tautology. The only _propositional_ formula that can be substituted to give $\forall x(x=x)$ is a single propositional variable, and a single propositional variable is not a tautology.
Comment: The definitions you're asserting here certainly don't match how I usually see the words used.
Comment: I can't tell if you're being snarky or not. I clearly can't just "ignore everyone". I want to understand the correct definitions of these words. I can't tell which resources have it right and which do not since there are so many differences, even among answers on this very website. Or am I left to surmise that there *is* no consistency and it's all very much informal and however people want to define them?
Comment: I have literally never heard the $\vDash$ relation referred to as a "tautology". A tautology is the same thing as a valid formula of propositional logic.
Comment: @user525966: It means that $\varphi$ is "valid" and "always true" and "a semantic consequence of the empty set". If $\varphi$ is a _propositional_ formula this is also expressed by the word "tautology". The word "sound" is not used about formulas.
Comment: That's something of a laundry list at the end, which I'm afraid makes the question too broad to fit our format here well.
Comment: That doesn't make those definitions match how I usually see the words used. If you're looking for a terminology that's consistent with those definitions, you might need to find a particular book that's using those words in your favorite way, and then ignore everyone who uses them differently.
Comment: You start by asserting definitions of the words that according to my experience are quite at odds with how they're usually used. I have trouble seeing which kind of answer you're expecting other than "Yes, user525966, we're going to throw our entire existing terminology away and instead start using the definitions you have graciously supplied in the disguise of asking a question."
Comment: Are you saying the Wiki has it incorrect?
Comment: I'm saying that if you want an explanation of anything you should not start by fixing what the only explanation you're prepared to accept MUST be. That's not a question, that's just fishing for people to agree with YOUR favored definition.
Comment: It's not fishing. It's a direct question meant to separate the usual from the not usual. Does the wiki have it wrong or not? You say it's normally used in a different way -- how does the Wiki have it wrong, and what's the usual way you refer to instead?
Comment: Your question here starts by ASSERTING some particular non-standard definitions of the words "valid" and "sound". Then you want definitions for a laundry list of other words -- presumably definitions that would work together with your asserted definitions of "valid" and "sound". I maintain that this is not a question. It is an attempt to tell the world how you have decided we must all use the words.
Comment: Okay you're going off the rails here. I'm clearly not doing that and you're very clearly avoiding my very simple/direct question (twice now), which would easily prove/disprove your initial assertion or not.
Comment: The first three paragraphs of the "question" are CLEARLY trying to assert some definitions of the word "valid" and "sound". That's what happens in English when you state: "Valid is defined as ..."
Comment: My post is clearly asking for the definitions. I'm not "asserting" anything other than posting the definitions as-listed on Wiki and other resources (all of which are linked). "I'm" not asserting these things -- Wiki is, these other posts are, etc. It's the entire purpose of the post -- untangling all these definitions to get something consistent and commonly-used/understood. And yet when I ask you to tell me how the Wiki is wrong (which you imply it is), you refuse to elaborate.
Comment: @user525966 People use the same words to mean different things. This is quite common in mathematics in general and is hardly unique to mathematics. This is just something you have to deal with. Yes, it does make it harder to understand what's going on. You simply have to look at how a word is being defined in each context. This is especially true in mathematical contexts, as there is often a need for a variety of words for similar concepts that are different for technical reasons that may or may not be important in other contexts.
Comment: @HenningMakholm I added the line "According to a few resources as-linked:" to make it extra clear that *I* am not asserting these definitions, but if you click the links as-mentioned in the paragraphs, that's where the definitions are coming from. Usually that's the whole point of presenting links but I'm being extra explicit here. You say these definitions are non-standard. So I am asking you, how are they non-standard? How is the Wiki wrong?
Comment: The definitions are non-standard because they do not match how the words are used in practice. "Valid" is used about a formula whose truth value is "true" in every interpretation of the non-logical symbols in it. "Sound" is used about a proof systems that proves only valid formulas (when used without non-logical axioms), and only proves formula that are semantic consequences of the non-logical axioms when such axioms ARE used.
Comment: One example is https://en.wikipedia.org/wiki/Double_turnstile#Meaning or Logic and Structure (Dirk van Dalen), page 18 (the book Mauro Allegranza recommended), etc
Comment: Many of the above concepts are already discussed in your previous post : [Defining premise and conclusion](https://math.stackexchange.com/questions/2907582/defining-premise-and-conclusion).
Comment: @HenningMakholm if something is a semantic consequence of nothing then that implies it's always true is it not?
Comment: Or is it that $\vDash$ is the same as "valid" and happens to be the same as "tautology" is propositional logic?
Comment: @user525966: Yes, something that is a semantic consequence of nothing is always true. However $\vDash$ is neither "valid" nor a tautology. $\vDash$ is the symbol for (a) the semantic consequence relation and (b) the evaluation relation in a particular interpretation. The latter of these is used to _define_ validity (and tautologies) but it makes no sense to say that the $\vDash$ relation itself is "valid" or a "tautology". These are words that are used about fomulas, not metalogical relations!
Comment: @HenningMakholm I'll rephrase. If we have the string $\vDash \varphi$ does this mean "$\varphi$ is valid" and "$\varphi$ is a tautology" and "$\varphi$ is always true" and "$\varphi$ is a semantic consequence of the empty set" and "$\varphi$ is sound"?
Comment: @HenningMakholm How can $\varphi$ be always true and yet not a tautology outside of propositional logic?
Comment: Interesting, makes sense, thanks
Comment: While I like answering your questions on here, learning what the terminology means will not teach you logic (or any kind of math) very well alone. You have to go through books (and video lectures if you can find them) and do exercises. If you haven't seen this guide, it's a good place to start.  http://www.logicmatters.net/resources/pdfs/TeachYourselfLogic2017.pdf When you commit to a book, you can simply trust its terminology and definitions, and then look to wikipedia and other books to contextualize.
Comment: @spaceisdarkgreen Of course, but not knowing the terminology makes it impossible to go further into doing anything more with it
Comment: @spaceisdarkgreen I have indeed seen that document before, though I found it super verbose and I had frustrations with most of his recs.
Answer: It is important to stick to mathematical logic here as opposed to the definitions from philosophy. The first sentence of the wikipedia

In mathematical logic, a logical system has the soundness property if
  and only if every formula that can be proved in the system is
  logically valid with respect to the semantics of the system.

while not fully precise, is the sense in which 'sound' is generally used in mathematical logic. This corresponds to a system having valid axioms and validity-preserving rules of inference, so you can see how it corresponds loosely to the philosophical notion of true premises and correct (i.e. truth-preserving) argumentation.
As for validity, the wikipedia sentence

A formula of a formal language is a valid formula if and only if it is
  true under every possible interpretation of the language. In
  propositional logic, they are tautologies.

uses 'valid' in the way it is used in mathematical logic. Here the connection to the philosophical notion of a valid argument that you cite is a little less direct. Let $A$ and $B$ be your premises and $C$ your conclusion. And say $$ (A\land B) \to C $$ is valid in the mathematical sense. That means that $A\land B \to C$ is true in any interpretation, which means that it is impossible for $A$ and $B$ to be true and for $C$ to be false. So the two notions of validity connected, but even more loosely than was the case for soundness.
Note that the validity of $(A\land B)\to C$ is the same thing as $C$ being a semantic consequence of $A$ and $B,$ i.e. $$ A,B\models C$$ which has more of the flavor of "a valid argument from $A$ and $B$ to $C$," though strictly speaking, there's no 'argument' here. (However, the syntactic variation $A,B\vdash C,$ which is equivalent in the presence of a completeness theorem, means there's a proof of $C$ from assumptions $A$ and $B$... that's more of an 'argument'.)
I've tried to be conciliatory to the philosophical definitions here, but in math it's important to get comfortable with the fact that precise definitions vary from treatment to treatment. (Heck, the other day I learned that not all books have the same definition of 'compact set' in a general topological space, which was a definition that I thought was more or less sacrosanct.) It should also go without saying that the definitions don't need to conform to the colloquial meaning of the words, though it's nice when they're at least not wildly misleading.
In a field with as many moving parts in mathematical logic we will often need to adjust and adapt our terminology as we develop new ideas and try to apply mathematical logic to more exotic situations.  Even in the beginning of my answer where I gave some 'general purpose' definitions and remarks, I had some particular contexts in mind, and we will need to make these things fully precise in any detailed treatment.  For instance, when we move to the specific context of classical propositional logic, "valid" becomes synonymous with "tautology" and we make precise the ideas of "interpretation" and "truth" in a given interpretation.  When we flesh things out in a given context (especially when working in more exotic situations than, say, classical propositional or predicate logic) everything I said is subject to revision.
Comment: As a rough guideline, if you see words like "argument", "logical form", "syllogism" or a heavy emphasis on "premises" and "tautology", you are probably in "philosophy logic" land. In mathematical logic land, you'll more see "(well-formed )formulas", "proof", "derivation", "rules( of inference)", "model", "semantics", and, obviously, a heavy emphasis on symbolic expressions. This isn't a perfect discriminator though, especially for older works.
Comment: @Derek Agree with all of these except "tautology" is used quite a bit in mathematical logic.
Answer: The notation $\Gamma \models \varphi$ means $\varphi$ is true in every structure in which all statements in $\Gamma$ are true.
The notation $\Gamma \vdash \varphi$ means $\varphi$ can be proved by using the statements in $\varphi$.
The latter depends on some notion of proof. One wants such a notion to satisfy three desiderata:

Soundness, i.e. if $\Gamma\vdash\varphi$ then $\Gamma\models\varphi.$
Completeness, i.e. if $\Gamma\models\varphi$ then $\Gamma\vdash\varphi.$
Effectiveness, i.e. there is a proof-checking algorithm, which will correctly identify its input as either a valid proof or not.

Note that $\Gamma$ is allowed to be a set of statements whereas $\varphi$ is just one statement. So why not conjoin all the statements in $\Gamma$ into one? The problem here is that if one is allowed to join infinitely many statements into one, then putting such an infinite conjunction in the role of $\varphi$ has the result that one cannot satisfy all three desiderata simultaneously. Any proof of that takes a lot of work.
Comment: @user525966 In the standard semantics of classical first order logic, sentences are interpreted in structures, i.e. structures are the interpretations. For instance, the first order sentence $\forall x \exists y(x R y)$ can be interpreted in the structure $(\mathbb R, <)$ (where we're interpreting the relation symbol $R$ as $<$) to mean the reals have no maximal element. So it's true in this structure. If a set of first order sentences are all true in a structure, we say the structure is a model of the set of sentences. https://en.wikipedia.org/wiki/Structure_(mathematical_logic)
Comment: Does $\vDash \varphi$ (empty left-hand side) mean $\varphi$ is a tautology?
Comment: @user525966 : It means $\varphi$ is true in every "structure" (I haven't been explicit here about what a "structure" is). Sometimes people reserve the word "tautology" for things in propositional logic rather than predicate logic (predicate logic uses universal and existential quantifiers; propositional logic only uses Boolean connectives such as "and", "or", and "not"). Sometimes people express it by saying this means $\varphi$ is "universally valid".
Comment: How would you describe "structure"? Is this the same as "interpretation" or "model"? What does it mean?


Complementary Principle

Question: In a test of 10 questions, a student must answer exactly at least to 5 questions. How many choices do you have? R 252
What if at least 2 of the exact answers must be from the first 5 questions.
I mean, the questions are {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} the right answer are: {1, 3, 7, 8, 9} or {1, 2, 3, 6, 7}.
R: 226 (hint to the second question: use the principle of complementary)
For the first part I used Com(10, 5) and it's correct. But I don't know what do do in the second part.
Comment: Sorry I used google translate, I edited the question check if you can understand it now.
Answer: We will look at the complimentary, that is how many possibilities you have where only zero or one are in the first five questions.
There is one way to have no answers among the first five, since it would require all the answers to be among the last five. If we place one among the first five and four among the last five, this can be done in $\binom{5}{1}\binom{5}{4}=25$ ways. So the final answer is:
$252-1-25=226$
Comment: Well if the total possibility are 252, and you can calculate it with: com(10, 5) = 10! / 5! (10-5)!      I guess it's a number between 252 and 226
Comment: @DrwMay No. I edited my answer to show an entire solution, perhaps it will make sense now?
Comment: Awesome! thank you so much

Complementary Principle


Passing a parameter into an event handler

Question: I would like to use this event handler to run a function passing in these parameters.
$('#checkingDeposit').on('click', { amount: 100, account: 'savings' }, bank.deposit);

deposit: function(event, amount, account) {
  console.log('deposit running');
  console.log(event.data);   //object of key value pairs
  console.log(event.data.account);    //output 'savings'
  console.log(event.data.amount); //output 100
  this[event.data.account] += event.data.amount;
  console.log(this[event.data.account]);  //NaN
  return this[event.data.account];
}

Am i getting a NaN when i try to console.log this[event.data.account] because i am trying to pass a string (ie 'savings') to the this object?
Thanks in advance
Brad
Comment: Hallo, please use the snippet tool, to create a minimal working example.
Answer: You must pass a function or a function reference to an event binding expression so if you need to pass arguments, you can wrap the actual function call (with parameters) in an anonymous function and pass that to the event binding expression.

let bank = {
  deposit:50
};

$('#checkingDeposit').on('click', function(event) {
  deposit(event, {amount:100, account:'savings'}, bank.deposit)
});

function deposit(event, obj, account){
  console.log('deposit running');
  console.log(obj.account);    //output 'savings'
  console.log(obj.amount); //output 100
}

<button type="button" id="checkingDeposit">Deposit</button>


Convert C# .net object array into another

Question: I get this error

Error  Cannot convert type TestMVC.GetServiceRequests.serviceRequests[] to System.Collections.Generic.IEnumerable<TestMVC.Models.ServiceRequest>

I'm trying to copy .net object array from webservice into another .net c# object array and they both have the same structure.
I tried type casting but this did not work.
var serviceRequest = svcClient.GetServiceRequests(getServiceRequest).responseData;
return  (IEnumerable<ServiceRequest>)  serviceRequests;

ServiceRequest[] serviceRequests = new ServiceRequest[]
{
     new ServiceRequest {  customerName = "Customer123", contactName = "Pat Nelson", vin = "4DRBUAFN75A977722", unitNo = "275", serviceRequestId = "1", requestedDate = "08/08/15", requestedTime = "PM", connectCompleted = "true",
                                  captureCompleted = "false", collectCompleted = "false", agreeCompleted = "false", updateDate = "08/17/2015", createDate = "08/17/2015", note = "note note note note note note note note note note note note note note note note note note note note note note  note note note note ", userId = "yyy1ri3"},

     new ServiceRequest {  customerName = "Customer456", contactName = "Pat Nelson", vin = "1HSMTAAN1DH328986", unitNo = "325", serviceRequestId = "2", requestedDate = "09/01/15", requestedTime = "AM", connectCompleted = "false",
                                  captureCompleted = "true", collectCompleted = "true", agreeCompleted = "false", updateDate = "08/17/2015", createDate = "08/17/2015", note = "note note note note note note note note note note note note note note note note note note note note note note  note note note note ", userId = "yyy1ri3"},

};

Comment: Please post actual code.
Comment: What kind of Webservice do you use? WCF or something else?
Comment: It seems pretty clear when you read the error message, a `serviceRequests` is not a `ServiceRequest` so an array of `serviceRequests` shouldn't be considered an IEnumerable of `ServiceRequest`... unless you can show us the definition of the `serviceRequests` class and show us that it is.
Comment: The second set of code you added. is that client side or server/service side?
Answer: When you import a web service as a reference in Visual Studio, new classes are automatically created for the objects returned from calls to the web service.
In this case the GetServiceRequests() methods returns a list of objects of class serviceRequests. This class was automatically created by Visual Studio.
You cannot assign objects of that class to your own class ServiceRequest, even when the classes are defined to have the exact same properties.
So you need to work with the class created by Visual Studio not your own class.
If the web service is a WCF or ASMX webservice, you can tell Visual Studio not to create own classes for the objects returned by the web service.
In order for this to work, the commonly used class (in this case ServiceRequest) must be declared in a separate assembly that is referenced by both the webservice and the client calling the webservice. Then when you add the webservice reference to the client, open the "Advanced" dialog and enable "Reuse types in referenced assemblies".
If it is some other type of web service, this is not possible.
Answer: The error indicates (correctly) that an array of one type cannot be cast as an IEnumerable of a different type.
One is TestMVC.GetServiceRequests.serviceRequests and the other is TestMVC.Models.ServiceRequest.
It doesn't matter whether they have the same structure. One type won't be automatically converted to another.
Don't think of it as an error - the compiler is preventing an error.
Casting a class as another class or interface only works when the class is derived from that class or inherits that interface.
If you have an instance of class A (or an array) and you want class B, and both conveniently have the same properties, then you would need create a new instance of B and copy its properties from A. (In other words, mapping.)
Answer: The two types
TestMVC.GetServiceRequests.serviceRequests[]

and
System.Collections.Generic.IEnumerable<TestMVC.Models.ServiceRequest>

do not match.
Given that they have the same structure. You can map the two types in order to get the resulting type you want. Then convert the resulting collection to an array using the ToArray extension method.
This is a manual way to do.
public ServiceRequest[] SomeMethod() {
    //..other code
    TestMVC.GetServiceRequests.serviceRequests[] serviceRequests = svcClient.GetServiceRequests(getServiceRequest).responseData;

    return serviceRequests.Select(s=> new ServiceRequest {
        customerName = s.customerName,
        contactName = s.contactName,
        //...etc...
    }).ToArray();
}

there are mapping frameworks you can also use to do the heavy lifting for you if you object has a lot of properties. One such tool is TinyMapper
which could be used like
public ServiceRequest[] SomeMethod() {
    //..other code
    TestMVC.GetServiceRequests.serviceRequests[] serviceRequests = svcClient.GetServiceRequests(getServiceRequest).responseData;

    return serviceRequests.Select(s=> TinyMapper.Map<ServiceRequest>(s)).ToArray();
}

Comment: System.InvalidCastException was unhandled by user code
  HResult=-2147467262
  Message=Unable to cast object of type 'System.Collections.Generic.List`1[TestMVC.GetServiceRequests.serviceRequests]' to type 'System.Collections.Generic.IEnumerable`1[TestMVC.Models.ServiceRequest]'.
Comment: The formatting of the question didn't show `TestMVC.Models.ServiceRequest` so my original answer was based on that. I've updated the answer given then new information


Do classical and rock musicians train with different goals?

Question: I expect most musicians aim to master the instrument they play. But articles & interviews I've read suggest that:

Classical musicians:

Place importance on precision and theoretical knowledge
Should master many styles/techniques. This way, the director can select pieces covering a wide stylistic repertoire, and the orchestra can play in an appropriate (but different) manner for each piece, on demand.

Rock musicians:

Value self-expression, individual "quirks"
When recording, try to capture an excellent "take" by both tweaking the texture of the sound (effects, microphone placement, etc.) and selecting a specific performance, often among the first ones, which has enthusiasm. Some call this a "rock moment" saying that if you don't capture it when it happens, it might be very hard to get another one.

This suggests that, while all serious musicians strive to master their instrument, classical musicians aim for reproducibility (consistently delivering the same performance) while a rock musician aims for his or her individual "voice" when performing (but each performance ends up having a slightly different character, enthusiasm – still within his or her unique voice, or style).
Of course any such "rule" will have exceptions, but in general, do classical and rock musicians have indeed different goals? Are the things I noticed (reproducibility vs spontaneity) generally accepted as such, and do you know of others?
Let's make a list of similarities and differences, based on trustworthy sources (e.g. what you know from real musicians; articles from a reputable source).
Comment: I know there are new classical pieces being written right now and there are also about 1000 Beatles cover bands that spend all their time reproducing the Beatles songs and not writing anything new. I think it depends more on the musician's goal and whether they want to be a writer or performer not necessarily the genre they are grouped in.
Comment: I would also like to add that the same piece may be played differently by different musicians depending on how they interpret it and/or how the conductor interprets it.
Comment: There is one difference I would like to point out though (which is too minor for an answer): for a classical musician, technique is much more important than for a jazz/pop musician. This is based upon the technical difference between jazz/pop and classical students at the conservatory here. Jazz/pop students tend to focus more on other things, among which is improvisation.
Comment: Famous phrase uttered while tuning up:  "Close enough for jazz"  :-)
Comment: all of these require application of Western Music theory
Answer: I think that the differences you mentioned have more to do with the size of the groups involved than their preference for classical or rock music. Also, I'm willing to wager that there is as much diversity in terms of goals among members of the same category (rock or classical) as there is between the two.
You mentioned orchestral music, but that is only a small subset of classical music. Imagine rehearsing for a solo piano performance of a piece by Chopin; which of your bullet-points most aptly apply to that situation? You can have all the technique on earth, but if you don't let your own expression of the music be the focal point, your performance will suffer for it.
Or consider a string quartet, and how many magical moments happen spontaneously in a live performance that could never be reproduced. Sure, they don't call them 'rock moments' but isn't that just a matter of semantics?
It just happens that most rock groups are closer to the size of a string quartet than the size of an orchestra. Just for a counter-example though, here's a very technical and precise piece of music being performed by a large rock ensemble led by Frank Zappa.
One of my favorite rock bands, Gentle Giant, falls under all four of your bullet points.
I'm sure almost every musician values self-expression, and can appreciate a spontaneous, irreproducible musical moment, but playing with a large group requires giving ground to other values, and one of those must be precision, if for no other reason than to avoid total chaos.
Comment: I had always assumed all musicians strive for precision and reproducibility. Crafting an individual voice, absolutely, but being able to reproduce it over and over.

When I started reading of respected rock musicians valuing the "inspiration of the moment" on their recordings I was very surprised. Dream Theater, who are very skilled and competent, said they were set-up to record in the studio from the moment they started writing, and value having those early sounds. And I kept finding similar examples.

I had small classical groups in mind too, great comment about group size!
Answer: Perhaps it's about the difference between a recital and improvisation -
Classical musicians tend to have learnt to read music, and sight-read from that while playing.
Rock musicians tend  to play from memory or by ear.
So I can see an argument that Classical is more about a recital, so fall into the description you give above, and some rock is more like improvisation (ish) so your description fits there too.
However consider a rock band playing covers as accurately as possible. I'd call that a recital,and even if they're playing from memory it's still about accuracy and repeatability.
Same setup (doens't matter what instruments they're playing really) but going for freeform jazz or a rock jam.. I think they're aiming at "being in the moment" rather than repeatabiity / accuracy.
Suppose the jam goes well and they want to reproduce it at later gigs, so they learn it from the recording.. same peiece of music but the intention is different - it becomes a recital.
Gotta love the potential for variation in approach :-)


R: Testing the null hypothesis of zero skew

Question: I need to test the null hypothesis that my steady returns have a zero skewness with a confidence level of 95%. Do you have any ideas which formula I can take for this kind of test ? I tried the Agostino test for skewness, but think it's not the best way, because I can't set a confidence level.
library(moments)
?agostino.test

Comment: Your difficulty appears to arise from a misunderstand of how hypothesis tests work. Confidence levels are for confidence intervals. You choose a significance level for a hypothesis test. The D'Agostino test implemented in the R package `moments` returns a p-value, with which it is easy to do a hypothesis test at any desired significance level. (On the other hand, it's not at all clear what value there would be in performing hypothesis tests of skewness of returns - I suspect that would be of almost no use at all - but that's another issue: returns are going to be skew, even if only a little)
Answer: perhaps you could have a look on pastecs package and stat.desc function.
library(pastecs)
stat.desc(iris$Sepal.Length, norm=TRUE)

Comment: What is this function? How does it work / how does it test skewness? Note that we aren't an R tech support site. Questions that just ask for code suggestions are off topic because they aren't real statistics questions. By the same token, this isn't a real answer by our standards. Can you edit this to add some substance?


If $a_n\leq b_n$, then $\lim \sup a_n \leq \lim b_n$

Question: Hello I want to make sure my work is correct!
Suppose that $\{a_n\}$ and $\{b_n\}$ are sequences such that $a_n \leq b_n$ for all $n $ and $b_n \to b$. Prove that $\lim \sup a_n \leq b.$

Let $\epsilon > 0$ be given. Choose an $N$ s.t. $|b_n-b|<\epsilon$ for $n\geq N$ where $b = \lim \sup b_n$.
$a = \lim \sup a_n$.
Proof by contradiction: If $a \geq b$, then, since $a_n\leq b$,
$b\leq a\leq b_n$, meaning $|b_n-a|<|b_n-b|<\epsilon $, implying $b_n \to a$. This is a contradiction,
therefore, $a\leq b$.
Answer: No. It may happen that $b_n \to a$. That is not a problem.
What you can do is as follows : You know that $a_n \leq b_n$ for all $n \in \mathbb{N}$. Hence, for any $k \in \mathbb{N}$
$$
u_k := \sup\{ a_n : n\geq k \} \leq \sup\{ b_n : n\geq k\} =: v_k
$$
Now, $v_k \to b$, and hence
$$
\limsup a_n = \lim u_k \leq \lim v_k = b
$$
Answer: Another approach: Let $c_n:=b_n-a_n \geq 0$ . Since $c_n \geq 0$, $LimSup c_n >0$.
Claim: Let $c_n$ be a sequence of nonnegative terms. Then $LimSup c_n>0$.
Proof of Claim: $LimSup${$c_n$}$:=c$ is , by definition, the largest limit point of $c_n$ , so that, in particular, it is a limit point of the sequencee $c_n$. Assume, BWC , that $C_n$ has $c<0$ as a limit point. But then the ball $B(c, |c|/2)=(c-|c|/2,c+|c|/2)$ will  not intersect {$c_n$} , since $c+|c|/2=c-c/2=c/2<0$ , i.e., the neighborhood $B(c, |c|/2)$ of $c$ that does not intersect the sequence, so that $c<0$ cannot be a limit point of {$c_n$}. It follows that $LimSup$ {$c_n$}$:=b_n-a_n \geq 0$, so that $LimSup a_n \geq LimSup $b_n$


getLastKnownLocations always returns null

Question: I am unable to getLastKnownLocations on my Android device (Samsung Galaxy Note N7000) as it is always null, towers is detected as network so it is fine, anybody got any idea how to get my location?
    d = getResources().getDrawable(R.drawable.songs_gray);

    //Placing pinpoint at location
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();

    towers = lm.getBestProvider(crit, false);

    Toast.makeText(LocationActivity.this, "Towers: " + towers, Toast.LENGTH_SHORT).show();

    Location location = lm.getLastKnownLocation(towers);

    Toast.makeText(LocationActivity.this, "Location: " + location, Toast.LENGTH_SHORT).show();

    if(location !=null){
        lat = (int) (location.getLatitude()*1E6);
        longi = (int) (location.getLongitude()*1E6);
        GeoPoint ourLocation = new GeoPoint(lat, longi);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
        CustomPinpoint custom = new CustomPinpoint(d, LocationActivity.this);
        custom.insertPinPoint(overlayItem);
        overlayList.add(custom);
    }else{
        Toast.makeText(LocationActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
    }

Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

Answer: With getLastKnownLocation() you can only get a Location object when the specified location provider is active.
The documentation says:

Returns a Location indicating the data from the last known location
  fix obtained from the given provider. This can be done without
  starting the provider. Note that this location could be out-of-date,
  for example if the device was turned off and moved to another
  location.
If the provider is currently disabled, null is returned.

To detect the current position and not the last detected one you need to enable the location provider(s). This tutorial should help you to understand how to work with location providers as GPS and network.
Answer: the last known location is only available if the location has been determined by another app prior to your call.  start maps or some other app and let it get a location lock. then run your app.
if you really need location in your app, you need to fall back to some other method, because you cannot depend on there being a last known location.
as a side note, ACCESS_MOCK_LOCATION isn't required here. from the docs,

Allows an application to create mock location providers for testing
Comment: How come Google Maps app knows where I am yet this command still returns null?
Answer: Nevermind found out my problem! Just needed to on Google's Location Services on my phone


Allowing content access only though aliases and views

Question: I'm building a site in Drupal 8 that will have complex content best viewed using views. The basic pages should use nice and clean URL aliases.
Is there a way to stop the visitor from accidentally using /node/x in the URL and only allow accessing the views and pages that have aliases and organised in the website menus?
Answer: Yes, in Drupal 7 this functionality was covered under the Global Redirect module. It has since been merged in the Drupal 8 version of Redirect.
Under the Redirect settings (/admin/config/search/redirect/settings), the Global Redirect section contains options to enable alias, non-clean, & canonical redirecting. This will enable you to redirect any requests from /index.php?q=node/X or /node/X to /my-canonical-content-alias.


Problemas com fórmulas para extrair textos com espaços diferentes

Question: Pretendo extrair apenas as numerações em vermelho para a tabela seguinte "Red", porém os espaços estão diferente e eu já testei um monte de fórmulas para resolver essa questão.
Utilizei uma fórmula um pouco complexa, mas ela não deu certo, tudo isso por causa que os espaços entre os números vermelhos são diferente, eu utilizei essa fórmula:
=ARRUMAR(DIREITA(ESQUERDA(SUBSTITUIR(ARRUMAR(A207);" ";REPT(" ";10));30);50))
Como eu faço para extrair apenas as numerações em vermelho??
Comment: Mas qual é a lógica para saber que número precisa extrair, seria o que segue uma sequência sem repetir?
Comment: Estou no trabalho e aqui estou sem tempo, mas você pode fazer com VBA utilizando a função MID mesclada com esse código aqui https://superuser.com/questions/1067320/check-excel-cell-if-font-is-a-certain-color
Comment: Eu queria apenas os números em vermelho de acordo com cada células referente. No caso tem uns que são repetidos, mas caso eu altere para outro tipo de numeração, eles tem que ficarem organizados de acordo com a posição e a quantidade
Comment: @ Max sei pouquíssimo de VBA, mas sei editar códigos e gravar macros. Eu posso esperar, caso você queira preparar um código ou uma fórmula mesmo no Excel
Comment: através de fórmula é impossível
Comment: O que deseja extrair está formatado como vermelho ou você apenas colocou como vermelho para indicar o que deseja extrair?
Comment: @anonimo Eu apenas pintei em vermelho para indicar o que eu quero extrair
Comment: Veja se a lógica é a seguinte: eliminar o eventual 11 se ocorrer no início da string e depois pegar tudo a partir da primeira ocorrência de 1 até o espaço que o segue.
Comment: @anonimo Essa fórmula que eu postei ela faz quase isso, mas os número tem que estar um em baixo do outro não importa a quantidade e ela funciona nesse caso! Mas quando os números se encontram de forma separadas, não da certo!
Comment: Se desse para utilizar essa mesma fórmula e incrementar algo mais, seria bom! Mas o outro usuário acima disse que era impossível com fórmulas, seria possível somente se utilizar VBA
Comment: Sinceramente: não entendi o que tal fórmula faz. Para mim é sem sentido.
Comment: @anonimo A fórmula extrair valores em sequencia com os valores das linhas, que vem depois, testa ela e altere as numerações "10,30,50" para regular o que você deseja exibir na extração de algum texto, nome, sobrenome, referencias de algum produto etc...
Answer: Faça o seguinte:
Insira o código abaixo em um módulo. Alt + F11, Insert, Module.
Function ExtrairTextoPorCor(pRange As Range) As String

        Dim xOut As String
        Dim xValue As String
        Dim i As Long
        xValue = pRange.Text

        For i = 1 To VBA.Len(xValue)
    'O RGB determina a cor que a fonte está, caso esteja diferente, faça a alteração no trecho do código RGB(255,0,0)
            If pRange.Characters(i, 1).Font.Color = RGB(255, 0, 0) Then
                xOut = xOut & VBA.Mid(xValue, i, 1)
            End If

        Next

        ExtrairTextoPorCor = xOut
    End Function

Volte para a planilha e procure uma célula vazia e insira a fórmula =ExtrairTextoPorCor(A207)
Comment: conseguiu aplicar a solução?
Comment: Sim, deu certo! Só uma coisinha que incomoda um pouco é que, se tiver por exemplo duas numerações com cores iguais, ex: 111 00 111, vamos supor que estes dois "111" está em vermelho, nesse caso ele vai extrair dessa forma: "111111" sem dar o espaço entre eles. Porém se formatar os espaçamento em vermelho ele obedece e extrai o espaço, "111 111"
Comment: Utilize esse código
Answer: Function ExtrairTextoPorCor(pRange As Range) As String

        Dim xOut As String
        Dim xValue As String
        Dim i As Long
        xValue = pRange.Text

        For i = 1 To VBA.Len(xValue)
    'O RGB determina a cor que a fonte está, caso esteja diferente, faça a alteração no trecho do código RGB(255,0,0)
            If pRange.Characters(i, 1).Font.Color = RGB(255, 0, 0) Then
                xOut = xOut & VBA.Mid(xValue, i, 1)
            ElseIf pRange.Characters(i, 1).Text = " " Then
                xOut = xOut & VBA.Mid(xValue, i, 1)
            End If
        Next
        ExtrairTextoPorCor = xOut
End Function


Solve system of equations: $2x^2-4y^2-\frac{3}{2}x+y=0 \land 3x^2-6y^2-2x+2y=\frac{1}{2}$

Question: $$
\begin{cases}
 2x^2-4y^2-\frac{3}{2}x+y=0 \\
 3x^2-6y^2-2x+2y=\frac{1}{2}
\end{cases}
$$
I multiplied the first with $-6$ and the second with $4$ and get two easier equations:
$9x-6y=0 \land -8x+8y=2 $ and out of them I get that $x=\frac{1}{2}$ and that $y=\frac{3}{4}$ but when I put it back into the original systems equation I dont get the right answer. Can somebody explain why?
Comment: you can get rid of the multiple of $x^2 - 2 y^2$ in essentially one way. So you only get one linear equation by elimination.
Answer: If $2x^2-4y^2-\frac32x+y=0$ and $3x^2-6y^2-2x+2y=\frac12$, then$$3\times(2x^2-4y^2-\frac32x+y)-2\times(3x^2-6y^2-2x+2y)=-1;$$in other words, $-\frac x2-y=-1$. So, replace $y$ with $1-\frac x2$ in the first equation, and you'll get a quadratic equation whose roots are $-3$ and $1$. So, the solutions of the system are $\left(-3,\frac52\right)$ and $\left(1,\frac12\right)$.
Answer: Multiplying the fírst equation by$-6$ and the second by $4$ and adding both we get
$$x+2y=2$$ or $$x=2-2y$$ plugging this in the first equation we have
$$2(2-2y)^2-4y^2-\frac{3}{2}(2-2y)+y=0$$
Can you solve this?
Simplifying and factorizing we get $$(2 y-5) (2 y-1)=0$$ so $$y=\frac{5}{2}$$ or $$y=\frac{1}{2}$$
Answer: It looks like you took the two scaled equations $$-12x^2+24y^2+9x-6y = 0 \\ 12x^2-24y^2-8x+8y=2$$ and then simply lopped off the common quadratic parts to produce two linear equations that are entirely unrelated to the original system. Once you've scaled the two equations so that the coefficients of their squared terms match, you eliminate those terms by actually adding the two equations together, producing the single linear equation $x+2y=2$.


JButton and jgraphx wont show up at the same time

Question: I have tried several ways, but still havent found the solution. I have a jgraph in a frame and I want to add a Jbutton in that frame also in a specific location. However I only get one of them when i run the program, because they expand to the whole window. Any ideas how to fix this?
Thanks in advance.
public class GUIquery extends JFrame {

    JFrame frame;
    static JGraph jgraph;
    final mxGraph graph = new mxGraph();
    final mxGraphComponent graphComponent = new mxGraphComponent(graph);

    public GUIquery() {
        super("Test");
        GraphD();
        imgbtn();
    }

    public void GraphD() {
        Object parent = graph.getDefaultParent();
        graph.getModel().beginUpdate();
        try {
          ........
        }catch  {
          ........
        } finally  {
           graph.getModel().endUpdate();
        }
        getContentPane().add(graphComponent);
    }

    public void imgbtn() {
        JPanel jpanel = new JPanel();
        jpanel.setSize(100, 100);
        jpanel.setLocation(1200, 60);
        JButton imgbtn = new JButton("Export as Image");
        imgbtn.setSize(100, 100);
        imgbtn.setLocation(1200, 60);
        jpanel.add(imgbtn);
        add(jpanel);
    }

    public static void main(String[] args) {
        GUIquery frame = new GUIquery();
        frame.setLayout(null);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 320);
        frame.setVisible(true);
    }
}

Answer: Don't use null layouts. They inevitably result in trouble.
From your code snippet it is impossible to tell where you want them to be relative to each other, the following puts the button below the graph.
The content pane uses BorderLayout by default. For BorderLayout, you need to use place components at different positions:
// the default position, but it does not hurt to be explicit
add(graph, BorderLayout.CENTER);

...

// and the panel
add(jpanel, BorderLayout.SOUTH);

If the positioning is not what you want, take a look at the visual guide to layout managers to pick the layout manager that suits your needs best.
In the button panel the setLocation() and setSize() calls are useless. The layout manager of the panel is responsible for setting the button's bounds. If the default FlowLayout is not what you want for it, use the guide to pick another for the panel too.
Comment: Thanks for your reply. This must be it. add(graph..) though wont apply in the method
Comment: I want the graph and button next to each other
Comment: Adding to the frame is the same as adding to the content pane. I didn't mean they'd be in the same method, just somewhere in the code. For placing the button right of the graph you can use `BorderLayout.RIGHT`. See the [BorderLayout tutorial](http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html) for more. Take also a look at the other layout manager images to check if something is closer to what you want.
Comment: i add them in separate methods. the add for button in the button method works fine. But the add(graph, BorderLayout.CENTER); in the GraphD method wont be accepted. It says "The method add(String, Component) in the type Container is not applicable for the arguments (mxGraph, String)"
Comment: Ok i got it right. I had to add the graph component and not graph. My problem is though that none of these layouts work for me. I just need a small button, like as if it is inside the graph
Comment: OK, good. The best could be making a new question with an image of the desired layout. The issue has changed from "How to make the components visible?" to "How to get the exact layout I want?". Without seeing an image of the wanted result i would be pure guesswork to give any suggestions. Include an example attempt and preferably an [SSCCE](http://sscce.org/) as usual.


Why are woodbats preferred to train with over aluminum bats?

Question: Let me start this off by saying that I have played baseball my whole life, and actually played in college (not for a club team.. the actual team) and  I can't think of why this method of training is preferred.
A lot of younger, developing players (middle school, high school, & college) prefer to hit with woodbats during their winter training, rather than the bats that they are going to be using during the regular season.
Now, the only reason why I have heard as to why this is, is because a woodbat has a smaller 'sweet spot' if you will, or in other words, it doesn't have as much forgiveness as a metal / aluminum bat.  So in translation, if you can make solid contact with a woodbat, then you definitely can make solid contact with a metal / aluminum bat, especially with the amount of forgiveness that those bats give.
My question to that is.. why would you train with a bat that you only use a few months out of the year and you don't use in games?  Shouldn't you train with what you are going to use in games, so that you can build large amounts of confidence with that piece of equipment?
Answer: A reason to use a bat with a smaller sweet spot during practice is to train your accuracy. A lot of training revolves around optimizing your technique. Hitting with a wooden bat requires better technique (I don't play baseball, this is an assumption) or forces you to read the trajectory of the pitch better. During practice, it doesn't matter if you miss, so you should focus on that so when a real game happens, you're confident in your skill to strike the ball.
Similarly in soccer, when you dribble around cones. Rare are the times where you're going to slalom with the ball, but it increases your ball control and gives you confidence since you can consistently do something harder than you need in a match.
Answer: To answer your question,"Why would you train with a bat that you only use a few months out of the year and you don't use in games?" It comes down to learning the fundamentals. Functionally, a wood bat and aluminum bat serve the same purpose, however, as both you and akadian alluded to, there is a smaller sweet-spot on a wood bat, and you get a lot more "real" feedback, if you will. This trains the batter to work with a smaller margin of error, so when they are swinging their aluminum bat in a game, they are more likely to make good contact, even if they are a little early/late getting to the pitch, because they have trained to be more precise.
On an extreme level, many players also use some type of training bat that is much thinner than a normal bat (usually a shortened broom handle) and hit either ping pong balls or whiffle golf balls. It reduces the amount of physical exertion required to get hundreds of swings in per day, and trains an insane amount of hand-eye coordination. Speaking from experience, this exercise helps a LOT.
On a completely different note, however, there are also some practical reasons as well. One of these is keeping balls in the ballpark. All the way through high school (and to a lesser extent, college), there were 3-4 of us on my team that would consistently hit balls over the fence numerous times during batting practice. This caused lots of wasted time due to fence hopping and ball finding, and also diminished our supply of baseballs rather quickly. Using a wood bat helps keep a lot of balls in the park that would otherwise go out.
The most important thing, however, is MECHANICS MECHANICS MECHANICS!!!!! If you do not maintain good mechanics throughout EVERY single swing you take, you will not get the results you are looking for. So, whether it is hitting with a wood bat, aluminum bat, or a broom handle, the underlying mechanics should never change. Ultimately, I never found switching up what I am hitting, or what I am hitting it with to be an issue when it came to game time. Anyway, that's my $0.02, hope that helps!


Create a range from consecutive zip codes

Question: I have a zone table with starting and ending zip codes, but it was loaded with each zip code individually. I now need to create a report that displays the zips in the assigned zones, but it is returning a bunch of records. What I want to do is create a range from this list of consecutive zips.
My table contains the following
FromZip ToZip
07543   07543
07604   07604
07509   07509
07510   07510
07511   07511
07512   07512
07513   07513
07514   07514

I would like to return
FromZip ToZip
07543   07543
07604   07604
07509   07514

Answer: Please try a query like below
select
  MIN(FromZip) as FromZip,
  MAX(ToZip) as ToZip
from
 (
  Select
   *,
   ROW_NUMBER() OVER(ORDER BY ToZip asc) as ranking
   from tbl
 ) t
 group by
   (CAST(ToZip AS INT)-Ranking)
 order by
   (CAST(ToZip AS INT)-Ranking)

Live SQL demo here


Injected service is undefined right in the constructor

Question: For the note, I'm quite uninitiated to Angular (1 or 2 for that matter).
I'm trying to write a "super" layer of Http to avoid having to put the same headers everywhere.
import {Http, ConnectionBackend, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs';
import {LoadingService} from "../../services/loading.service";

export class HttpLoading extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,
        private _ls: LoadingService )
    {
        super(backend, defaultOptions);
    }

    getPostPutHeader() {
        var authHeader = new Headers();
        authHeader.append("Authorization", "Bearer "+ localStorage.getItem('token') );
        authHeader.append('Content-Type', 'application/json');
        return authHeader;
    }

    post(url: string, data:any):Observable<Response> {
        this._ls.isLoading = true; // Exception here: this._ls is undefined
        return super.post(url, data, { headers: this.getPostPutHeader() })
            .map(res => {
                this._ls.isLoading = false;
                return res;
            });
    }
}

And a service to tell when a request is executing; it's injected in the above class HttpLoading.
import {Injectable} from '@angular/core';

@Injectable()
export class LoadingService {
    isLoading: boolean = false;
}

I have a bunch of stuff in my bootstrap, including HttpLoading, LoadingService and ConnectionBackend (for this last one, I get an exception if it's not here).
bootstrap(AppComponent, [
    ConnectionBackend,
    HttpLoading,
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    LoadingService,
    disableDeprecatedForms(),
    provideForms()
])

The problem is that the first time I call HttpLoading's post method (in yet another service), I get an exception at this._ls.isLoading, because this._ls is undefined, and I can't figure why.
Please tell me if you need more information.

Edit
LoadingService is correctly injected in my AppComponent (main component).
//imports
//@Component
export class AppComponent {
    requesting:boolean = false;

    constructor(public authService: AuthService, private router: Router, private _ls: LoadingService) {
    }

    navigate(route:string) {
        this._ls.isLoading = true;
        this.router.navigate([route])
            .then(() => this._ls.isLoading = false);
    }
}

Potential solution
It seems that your public/private parameters must be placed first in the list. I'll let someone more skilled than me explain why, though...
export class HttpLoading extends Http {

    constructor(private _ls: LoadingService, backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
}

Answer: I would configure your HttpLoading class this way in the providers when bootstrapping your application:
bootstrap(AppComponent, [
  (...)
  HTTP_PROVIDERS,
  {
    provide:Http,
    useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, loadingService: LoadingService) => {
      return new HttpLoading(backend, defaultOptions, loadingService);
    },
    deps: [XHRBackend, RequestOptions, LoadingService]
  }
]);

The reason for this is that you want to use your own class for the Http provider. You need to change the class behind the Http provider by your HttpLoading class. Be careful to define it after HTTP_PROVIDERS.
To be able to inject the instance of XHRBackend to your class, you need to use useFactory...
Comment: Could you please explain why, if that's not too much of a hassle? Also I think you're missing a closing curly bracket; I have an error in my IDE
Comment: I added some explanations in my answer... Feel free to tell me if it answers your question... Otherwise, you're right. A `{` needed to be removed ;-) Thanks for pointing this out!
Comment: Thanks a lot. I still don't understand everything, but that's a start! Does that "replace" automatically Http with HttpLoading when I use Http in my components? And should I replace ConnectionBackend with XHRBackend in HttpLoading's constructor?
Answer: Ok , I know that may seem trivial, but try to create a variable and initialize it in the constructor
Comment: Besides I don't see how  it would make it work, this couldn't be a solution at any level. A service injected in the constructor, should always be available inside the underlying context.
Comment: I also recommend this -- the optimization engine may be removing the reference to this dependency.
Answer: To extend @Thierry Templier's answer. I am using Angular v4, and my experience is that you need to provide ALL the dependencies that your extending constructor needs, AND in the right order - I guess it's a legacy way of doing it, from angular 1.x.
My example:
// This is my extended class (relevant part only)
@Injectable()
export class HttpService extends Http {

    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,

        private router: Router,
        private loaderService: LoaderService,
        private modalService: ModalService,
        private localStorageService: LocalStorageService
    )
    {
        super(backend, defaultOptions)
    }

// This is the provider factory defined in app.module.ts:
export function httpClientFactory(
        backend: XHRBackend,
        defaultOptions: RequestOptions,
        router: Router,
        loaderService: LoaderService,
        modalService: ModalService,
        localStorageService: LocalStorageService
    ) : Http
{
    return new HttpService(
        backend,
        defaultOptions,
        router,
        loaderService,
        modalService,
        localStorageService
    );
}

This is the configuration (just left the relevant part) in app.module.ts:
providers: [
    ModalService
    LocalStorageService,
    LoaderService,
    {
        provide: HttpService,
        useFactory: httpClientFactory,
        deps: [XHRBackend, RequestOptions, Router, LoaderService, ModalService, LocalStorageService]
    }

Note: notice the order of declaring the deps in the config compared to the factory constructor .. it is the same


Bind nginx to vpn address only

Question: I am probably unnecessarily paranoid. But still also I think paranoid isn't too bad when it comes to security.
I have a web server running on a VPS. I run zerotier on all my VPS and my home machines. I then use Letsencrypt to run a https webserver.
Therefore, I have a DNS entry pointing to my webserver with the zerotier VPS address:
myzerotier_webserver.mydomain.com   172.29.70.241.
Now, I'd like to restrict access to my webserver to only participants in the zerotier network.
I tried this:
        listen 127.0.0.1:443 ssl http2;
        listen 172.29.0.0:443 ssl http2;

But this doesn't seem to work accessing this server from my connected home laptop entering myzerotier_webserver.mydomain.com in the browser.
I also tried by replacing 172.29.0.0 with the actual IP address of the VPS, e.g. 172.29.70.241.
But it also didn't work.
Is this actually doable in some way? Should I do it differently maybe? Maybe it should work so the issue is some other configuration I got wrong?
Comment: I now know why this wasn't working: I was running nginx in a docker container, and the client IP was appearing as yet another network via `docker compose`: 192.168.80.1. Which means even the accepted solution actually doesn't work. In order to make it work, I had to extract nginx to run on the host, not in a container. Now I can filter by VPN address AND I can use multiple `server` instances of nginx listening to the same ports without interfering.
Comment: Which webserver you are using? Nginx will get it's listeners from the line `listen :`. If this doesn't work as expected, a line from the access log would be helpful.
Answer: If you are using UFW, you can just simply allow port access only for specific ranges. Here is an example:
ufw allow from 172.29.70.0/24 to any port 443 proto tcp comment "HTTPS only zerotier"
Change 172.29.70.0/24 to appropriate range.
Also don't forget to make default traffic rules:
ufw default allow outgoing
ufw default deny incoming
And enable UFW:
ufw enable && ufw reload
Comment: if you are accessing your server through ssh, don't forget to allow it's port: `ufw allow from any to any port 22 proto tcp comment SSH`. Execute this command BEFORE enabling UFW
Answer: There is also an option to make it through NGINX configs, here it is:
location / {
  allow 18.104.22.168/24; # Change this to appropriate range
  deny all;
}

Comment: I like both suggestions, but prefer the ufw approach as I am personally likely to keep an eye on those rather more often. Thank you!

Bind nginx to vpn address only


Weighted sum of Bernoulli distributions

Question: Suppose $$
X_i \sim \text{Bernoulli }(p)
$$
What can be said about the distribution of $Y$, given by
$$
Y = \sum_{i=1}^N w_i X_i
$$
for non-negative weights $w_i$? Note that $N$ here is small, so that no form of the CLT may be applied. I know, from this question, that this is a Poisson Binomial distribution if $w_i=1$, $\forall i$, but my question differs in the fact that I'm taking the same probability $p$ for all $i$.
Comment: "What can be said" is awfully vague and broad.  What do you want to know about this distribution specifically?
Comment: If you post the same question simultaneously on multiple forums, it's good form to mention that in the question. Otherwise, if the answer or instructive comments on one forum aren't known on the other forum, you'll be wasting the time of the experts from which you're asking for help:  https://math.stackexchange.com/questions/4415458/weighted-sum-of-bernoulli-distributions.
Comment: You mention "Poisson Binomial".  Is $N$ given, or is it a random variable?
Comment: @Henry $N$ is given.
Comment: For small $N$, say up to $20$, and knowing $p$ and the $w_i$, and that the $X_i$ are independent, it would be easy enough to calculate the exact distribution
Comment: almost a duplicate?  https://stats.stackexchange.com/questions/270227/what-is-the-cdf-of-the-sum-of-weighted-bernoulli-random-variables/465846#465846
Answer: Because you have access to Mathematica, here are two possible approaches:
n = 4;

t = Tuples[{0, 1}, {n}]
(* {{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 0, 0},
    {0, 1, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 1},
    {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 0, 1}, {1, 1, 1, 0},
    {1, 1, 1, 1}} *)

ss = Table[w[i], {i, n}] . # & /@ t
(* {0, w[4], w[3], w[3] + w[4], w[2], w[2] + w[4], w[2] + w[3],
    w[2] + w[3] + w[4], w[1], w[1] + w[4], w[1] + w[3],
    w[1] + w[3] + w[4], w[1] + w[2], w[1] + w[2] + w[4],
    w[1] + w[2] + w[3], w[1] + w[2] + w[3] + w[4]} *)

prob = p^Total[#] (1 - p)^(n - Total[#]) & /@ t
(* {(1 - p)^4, (1 - p)^3 p, (1 - p)^3 p, (1 - p)^2 p^2, (1 - p)^3 p, (1 - p)^2 p^2,
    (1 - p)^2 p^2, (1 - p) p^3, (1 - p)^3 p, (1 - p)^2 p^2, (1 - p)^2 p^2,
    (1 - p) p^3, (1 - p)^2 p^2, (1 - p) p^3, (1 - p) p^3, p^4} *)

pmf = Transpose[{ss, prob}];
TableForm[pmf, TableHeadings -> {None, {"Y", "Probability"}}]

If the values of $Y$ are not all unique (i.e., w[3]+w[4] == w[1]+w[2] for example), then you'd want to "condense" the above table.  Suppose w[i] = i:
TableForm[
 Sort[{#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[pmf /. w[i_] -> i, First] //
   Simplify, #1[[1]] < #2[[1]] &],
 TableHeadings -> {None, {"Y", "Probability"}}]

An alternative approach with known weights:
n = 4;

dist = TransformedDistribution[Sum[w[i] x[i], {i, n}],
   Table[x[i] \[Distributed] BernoulliDistribution[p], {i, n}],
   Assumptions -> 0 < p < 1];

Table[{k, PDF[dist /. w[i_] -> i, k] // Simplify}, {k, 0, n (n + 1)/2}]
(* {{0, (-1 + p)^4}, {1, -(-1 + p)^3 p}, {2, -(-1 + p)^3 p}, {3, (-1 + p)^2 p},
    {4, (-1 + p)^2 p}, {5, 2 (-1 + p)^2 p^2}, {6, -((-1 + p) p^2)},
    {7, -((-1 + p) p^2)}, {8, -((-1 + p) p^3)}, {9, -((-1 + p) p^3)}, {10, p^4}} *)

This last approach is much, much slower.

Weighted sum of Bernoulli distributions


Comparison between ordinary products and tensor products

Question: My question is quite simple, I didn't understand this comparison, why the first lines in this example implies the red ones:

Thanks
Comment: The red text does not really claim anything, so it is not `implied' in the usual sense. It is a teacher's attempt at a description.
Comment: Just understand that tensor product is multilinear
Answer: As mentioned in the comments, this underlines lines are an attempt at explaining what is going it. Formally, this may correspond to the fact that there is a natural map $R[X] \times R[Y] \to R[T]$ given by $(f(X), g(Y)) \mapsto f(T)g(T)$ and a natural map $R[X] \times R[Y] \to R[X] \otimes_R R[Y] = R[X,Y]$ given by $(f(X), g(Y)) \mapsto f(X)g(Y)$.
Comment: Thank you, now everything is clear.


Removing Special Characters from C++ String (Except ' and - )

Question: I'm trying to remove special characters from a string using an isWordChar() method. However, I need to keep two special characters, " ' " and " - ", such as  the apostrophe in "isn't" and the hyphens in mother-in-law. Here's what I'm trying to implement:
std::string WordCount::stripWord(std::string word) {

   for(unsigned int i = 0; i < wrd.size(); ++i)
   {
      if( !isWordChar(wrd[i]) && (wrd[i]!=39 && wrd[i]!=45))
      {
         wrd.erase(wrd.begin()+i);
         --i;
      }
   }

   return wrd;
}

After adding the special cases in my boolean, I can't get seem to correctly add the exception. Any hints or advice? Thanks!
Comment: The problem isn't clear. Explain what you mean by "I can't get seem to correctly add the exception." The presented code looks like it behaves just as you described, so what is it that's wrong?
Comment: Also, don't use numbers in place of character literals, and standard algorithms from `` should be preferred over manual loops.
Answer: I would use the remove/erase idiom:
word.erase(std::remove_if(word.begin(),
    word.end(),
    [](char c) {
        return !(isWordChar(c) || '-' == c || '\'' == c);
    }), word.end());

The way you're erasing characters has complexity of approximately O(N * M) (where N is the original length of the string and M is the number of characters you remove). This has a complexity of approximately O(N), so if you're removing very many characters (or the string is very long) it's likely to give a substantial speed improvement.
If you care about why it's so much faster, it's because it works somewhat differently. To be specific, when you erase an element from the middle of a string, the erase function immediately copies all the letters after that to fill the hole where you erased the character. If you do this M times, all those characters get copied one for each character you remove.
When you use remove_if, it does something more like this:
template <class Iter, class F>
Iter remove_if(Iter b, iter e, F f)
    auto dest = word.begin();

    for (auto src=word.begin(); src != word.end(); ++src)
        if (!f(*src))
            *dst++ = *src;
        ++src;
    }
    return dst;
}

This way, each character that's retained is only copied once, rather than being copied every time you remove one character from the string. Then when you do the final erase, it just removes characters from the end of the string, so it's basically just adjusting the length of the string downward.
Answer: Your logic is incorrect. It should be: !isWordChar(wrd[i]) && wrd[i] != 39 && wrd[i] != 45. Read as: If the character isn't a word character, and it's not an apostrophe, and it's not a hyphen, do whatever is in the if-statement.
Comment: I tried using the && and the || operators for the second half of the boolean to look like this :
    if(!isWordChar(wrd[i])&&(wrd[i]!=39&&wrd[i]!=45))

all with no luck...

@ AnthonyCalandra
Comment: @ewok896 I don't understand. Did you try what I gave above?
Comment: Sorry for the poor response. Yes, I tried it with the && operator, and it didn't work out
Comment: Thank you for your help, but get ready. I was foolishly working in a duplicate copy of my cpp on my editor and running my tests using the old cpp, not the new edited copy cpp. So, it works. Thanks again, and sorry for kind of wasting your time.
Comment: The recommended condition `!isWordChar(wrd[i]) && wrd[i] != 39 && wrd[i] != 45` is functionally equivalent to the condition `!isWordChar(wrd[i]) && (wrd[i]!=39 && wrd[i]!=45)` in the question. The comments about `erase` are ignoring the fact that there are [several overloads of `erase`](http://en.cppreference.com/w/cpp/string/basic_string/erase), one of which is `erase(iterator itr)` which does exactly the same thing as `erase(i, 1)`.
Comment: @AnthonyCalandra Ah, I see his change. On `erase`, he is passing an iterator, so that part of his code is correct (even in the original version of the question).


Word spacing is insufficient following an  element

Question: I cannot figure out how to make the correct amount of space after an italicised word. My italicised/emphasised word, in an  element, appears too close to the following word.

I tried to add word-spacing with the ::after pseudo-selector, but it has no effect and content: " " doesn't do anything with actual placement of letters. Adding another space in the
 or  tag doesn't work either. Is there a style such as word-spacing-right which can help?
Answer: The problem you are trying to solve occurs when the true italic style of a font is not available to the browser, typically because the website author omitted to reference it. You have not posted any of your code, so I don't know if this applies to your case, but it's my guess that it does. If so, then the solution is simply to reference the true italic style of the font.
The two snippets below demonstrate the problem and the solution.
In this first snippet, the true italic style of the font is not referenced. The browser simulates italic type by simply slanting the letters of the normal type. However, the italicised word is not spaced correctly: the gap before it is too big, and the gap after it too small. Not by much, but enough to be noticeable.

@import url('https://fonts.googleapis.com/css2?family=Amaranth:wght@700&display=swap');

body {
  font-family: Amaranth;
  font-size: 3em;
}
Red Red Red

In this second snippet, the true italic style of the font is referenced (in addition to the normal style). Note that the italic letters are shaped differently; that's because the true italic style has been carefully and thoughtfully crafted by the font designer. The designer also specifies the correct spacing between letters and between words, including the spacing between italic and normal type.

@import url('https://fonts.googleapis.com/css2?family=Amaranth:ital,wght@0,700;1,700&display=swap');

body {
  font-family: Amaranth;
  font-size: 3em;
}
Red Red Red

Here is an excerpt from the CSS @font-face rules imported from the Google link in the second snippet. You should ensure that your code contains something similar.
@font-face {
  font-family: 'Amaranth';
  font-style: normal;
  font-weight: 700;
  src: url(https://example.com/xyz.woff2) format('woff2');
}

@font-face {
  font-family: 'Amaranth';
  font-style: italic;
  font-weight: 700;
  src: url(https://example.com/xyz-italic.woff2) format('woff2');
}

Answer: Another hack is to declare word-spacing for span and wrap it around the em and the following word.
span {word-spacing: .25ch}

You know you want to

However, I think a better hack (when the actual italic font isn't being used) is to define margin-right
em {margin-right: .25ch}

p {
  font: bold xx-large sans-serif;
  line-height: .5em;
}

em {color: firebrick}

span {word-spacing: .25ch}

p:nth-child(3) em {margin-right: .25ch}

You know you want to

You know you want to (span)

You know you want to (margin)

Comment: I quite liked "margin-right" solution. I will remember that for the future use. Thanks
Comment: @Tim R and you can show more than one Example. Great.
Answer: If you want to add a space between words after an  element in HTML, you can achieve that using CSS. You can use the ::after pseudo-element to add content after the  element and apply a margin-left property to create a space between the content and the text that follows the  element. Here's an example:

This is emphasized text. Following text.

Comment: I noticed that `content: " "` doesn't increase the spacing any more than `content: ""` does. I assume this is because the whitespace collapses. The only visual difference is when the text is highlighted. Additionally, the same effect can be created by adding the margin directly to `em` instead of its pseudo-element.
Comment: I confirmed my suspicion of the spaces collapsing by adding the declaration `white-space: pre`. The margin declaration is then unnecessary.