Stuck with a possibly impossible trigonometry question

Question: I need to find the length of the arc between Y1 and Z1 in the image below. If you can even get me to the value of Y, then that will work.
I appreciate the drawing may be crude, but imagine that Y and Y1 are directly above each other, as are C, Z, Z1, and the line with A, X, Y is perfectly horizontal (i.e. perpendicular to the Y and Z lines mentioned before)
I have no idea if this is even possible, and I've been stuck for over an hour so am throwing it out there to anyone who has better than High School level math than I do!
UPDATE: I have been told I should look into using quadratic equations to find the two intersections of a line between a circle, and I think that should be enough to get me there.
In case there's another way, I'll add some more info.
This is actually based on coords of pixels on a screen. I know the coords of A, C, X, Z and Z1. I also know the lengths of R, AZ and AZ1. The only value that can change is X, although the more I look at it, the more I think it's irrelevant to my situation i.e. finding the length of the arc Y1Z1.
Comment: What do you mean by the "value" of $X$ and $Y$, and what distance or distances do you want the answer in terms of? Also how does $X$ relate to other parts of the diagram? At first sight it looks as though $X$ can he anywhere along $AYZ$ without affecting anything.
Comment: @user141288: You're correct that $X$ is irrelevant. I'll note that you can use the [power of point $A$ with respect to the circle](https://en.wikipedia.org/wiki/Power_of_a_point) to get at the distance between $Y_1$ and $Z_1$ as follows: $$|AC|^2-R^2 = |AY_1||AZ_1|$$ This gives you $|AY_1|$, and then $|Y_1Z_1| = |AZ_1|-|AY_1|$. Getting the arc length from that (and $R$) is a simple trig statement.
Comment: so I'm probably confusing things because this is a real world example, of coordinates on a screen. I know the coordinates of A, X, C, Z and Z1, and I know the length of R, AZ, AZ1. I need to know the value of Y1 or Y, and the only input I have that varies each time is X. X may or may not have any value at all.
Comment: @Blue thanks for the answer. I don't actually understand the notation, but if you add it as an answer I'll accept it. I've actually been given the solution in two other ways too, which I'll add as my own answers, but I'll accept yours
Comment: @user141288: If my approach doesn't help you, then I won't bother transferring it to an answer. Add your own answers so that we can upvote them; be sure to accept one, so that the question gets removed from the Unanswered queue.
Answer: User141288 provided the best possible solution. However, it is also possible to solve this problem in a trivial way by using analytical geometry.
You say that you know the coords of $A(x_A,y_A)$, $C(x_C, y_C)$ and $Z1(x_{Z1}, y_{Z1})$.
So you can easily calculate the radius of the circle:
$$R^2=(x_{Z1}-x_C)^2+(y_{Z1}-z_C)^2$$
Equation of straight line passing through points $A,Z_1$ is:
$$y=y_A+\frac{y_{Z1}-y_{A}}{x_{Z1}-x_{A}}(x-x_A)\tag{1}$$
On the other side, the equation of circle is:
$$(x-x_C)^2+(y-y_C)^2=R^2$$
$$(x-x_C)^2+(y-y_C)^2=(x_{Z1}-x_C)^2+(y_{Z1}-y_C)^2\tag{2}$$
The point is: Equations (1) and (2) have two unknowns ($x$,$y$). Replace (1) into (2) and you will get a single quadratic equation that can be solved for $x$. In a general case that equation (like any other quadratic equation) has zero, one or two different real solutions. Assuming that your solutions are both real and different $(x_1, x_2)$, you can now calculate $(y_1,y_2)$ from (1).
The distance between intersection points (and note that one of them has to be $Z_1$ if you calculated everything correctly) is simply:
$$Y_1Z_1=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$$
Answer: I suppose "directly above" means the points have the same $x$ coordinate on the screen
and "perfectly horizontal" means the points have the same $y$ coordinate on the screen.
The triangle $\triangle CY_1Z_1$ is isosceles.
If $M$ is the midpoint of the side $Y_1Z_1$, then the line $CM$ cuts the isosceles triangle into two right triangles, $CMY_1$ and $CMZ_1$.
In these triangles, $\angle MCY_1 = \angle MCZ_1.$
The question implies that the line $CZZ_1$ is perpendicular to the line
$AYZ.$
Because of that and because the line $CM$ is perpendicular to the line $AY_1Z_1,$
the angles $\angle ZAZ_1$ and $\angle MCZ_1$ are congruent.
The length of the arc is simply $R$ times the radian measure of the angle $\angle Z_1CY_1.$ But
$$\angle Z_1CY_1 = 2 \angle MCZ_1 = 2\angle ZAZ_1. $$
So you just need to find $\angle ZAZ_1,$ double it, make sure it's in radians, and multiply by $R.$
There are various choices for computing $\angle ZAZ_1.$
You could take $\angle ZAZ_1 = \arccos(AZ/AZ_1),$ though in the figure as shown,
$\angle ZAZ_1 = \arcsin(ZZ_1/AZ_1)$ would tend to give a more accurate result.
You could also take $\angle ZAZ_1 = \arctan(ZZ_1/AZ).$

In case you need the straight-line distance between $Y_1$ and $Z_1,$ that's even simpler: using similarity of the three right triangles
$\triangle CMZ_1$, $\triangle CMY_1$, and $\triangle AZZ_1$,
$$ Y_1Z_1 = 2R \frac{ZZ_1}{AZ}.$$


How to replace single html element with multiple html elements

Question: Suppose I have a single HTML element that I want to be replaced in the body
i.e. this is the body

 some random element

 some text  //  this element to replace

 some random element

Now I want this element to get replaced by an array of elements
[
   23dfsome text12,
   sdfsome text23,
   somdfse text2
]

the final body after getting replaced will be

 some random element

 23dfsome text12
 sdfsome text23
 somdfse text2

 some random element

How to do that ? I tried with replaceWith but not able to do it.
Comment: Surround the a tag with a div, then target this div and replace it with the contents of your array. Use join on your array to create one big string.
Comment: Please show the [`.replaceWith(...nodes)`](https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith) approach because that would be one suitable solution
Comment: Since you've tagged the question with Jquery, and not with Javascript. Do you require a Jquery only solution?
Comment: @0stone0 No issue with javascript too. Jquery will be better.
Comment: _"it's not possible with replaceWith"_ - Then why did you accept the answer with `.replaceWith()`?
Comment: Although no one is required to explain a down vote, but... From the tooltip: _"This question does not show any research effort; it is unclear or not useful (click again to undo)"_ - This question doesn't show any research effort, hence -> DV. @chaitanyagupta Care to explain what this has to do with reputation?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234626/discussion-between-anuresh-verma-and-andreas).
Answer: You can't insert a NodeList directly, since replaceWith does not accepts an array as parameter.
Luckily there are some ways around this

JavaScript
If we use the spread operator (...) on our array with nodes, replaceWith() will insert the elements as expected:

// Array to replace
const ar = [];
for (var i = 1; i <= 3; i++) {
    let tmp = document.createElement('a');
    tmp.innerHTML = 'Link #' + i;
    ar.push(tmp);
}

// Get element to replace
const el = document.getElementById('dfd32');

// Insert the array nodes
el.replaceWith(...ar);

 some random element

 some text

 some random element

jQuery
jQuerys version of replaceWith does work with a regular array containing DOM elements:

// Array to replace
const ar = [ $('Link #1'), $('Link #2'), $('Link #3') ];

// Get and replace
$('#dfd32').replaceWith(ar);

 some random element

 some text

 some random element

Comment: Can you provide your previous code with an alternate solution? That was better in my case I think.
Comment: Okay, no issues :)
Comment: _"There isn't a Jquery Solution thats cleaner than this"_ - Erm... [`$.replaceWith()`](https://api.jquery.com/replaceWith) -> `$("#dfd32").replaceWith(arr)`
Comment: Mmm, no clue why that didn't work. Added it to my answer.


How to fetch file which drops in QML windows and drags from external?

Question: I have a TableView in a desktop qml app which lists filenames which the user will work on. The files have been selected by the user from a TreeView of a QFileSystemModel. The TableView is basically one column where the file name is shown, but in the model the full path is stored. I use an ApplicationWindow in my main.qml.
In addition to selecting files from the TreeView I would like to be able to drag and drop files from the file explorer/desktop into my application, so that after a drop the filename gets added to the model and is thus shown in the TreeView. How could this be done?
Comment: Can you provide some code for us to fix?
Comment: I would only need the filename and path to be stored
Answer:
I would like to be able to drag and drop files from the file
  explorer/desktop into my application, so that after a drop the
  filename gets...

Simplify the question as:
How to fetch file which drops in QML windows and drags from external?

Answer: DropArea
Window {
    visible: true
    width: 640
    height: 480

    DropArea {
        anchors.fill: parent
        onDropped: {
            console.log(drop.text) // file path
        }
    }
}


Category of categories and anafunctors.

Question: 1)Category of sets is a (1,0)-category, isn't it?
2)Anafunctors are the factorization of class of functors by equivalence
relation(isomorphism) on its values, aren't they?
3)Which kind of category small categories and anafunctors forms? ((2,1)-category?) Let it be $Cat_{ana}$.
4)May I say that $Set$ is "anaisomorphic" to $Set^{op}$ (in $Cat_{ana})$? ( I can not, because of different truthness of proposition "all morphisms to the initial object are isomorphisms". Anafunctors are not related to this statement.)
Is this theory well-developed? What is worth to read about it?
Comment: A $(1,0)$-category is just a groupoid, isn't it? (Which sets aren't).
Comment: To see 'all possible values' of a functor $\mathcal A\to\mathcal B$ (such as a limit functor) at once, we can also use its induced **profunctor** $\mathcal A^{op}\times\mathcal B\to\mathcal{Set}$ with its cograph category which disjointly contain $\mathcal A$ and $\mathcal B$ and '*heteromorphisms*' between their objects. Then, the original assignment is given by *reflection* to $\mathcal B$, so that all target objects are equally presented this way.
Comment: @Berci, I am trying to understand what you want to say and which  question you answer. Limit functor sends functors of type A->B, where A,B-categories to objects of B, am I right? It sends natural transformations to morphisms between limits in B, am I right? (I didn't understand the rest. I also edited my post by adding answer to 4th question, is it ok?)
Comment: Every functor induces two profunctors. (Which are "cocontrabifunctor" and "contracobifunctor" :-) )
Comment: I didn't aim to answer your question, only wanted to reason about why - if not - the theory of anafunctors is not very well developed. Actually, you can choose either profunctor of any given functor. What I meant by cograph is written here: https://ncatlab.org/nlab/show/profunctor#in_terms_of_twosided_codiscrete_cofibrations. In the cograph category,  the image of an object appears as a [co-]reflection of the object, and if we take all [co-]reflection arrows, we get sth very similar to a *saturated anafunctor*.
Answer:
As stated in the comments, $Set$ is not a groupoid (which is what we mean by (1,0)-category) unless we ask it to be.
I'm not sure what this means, but anafunctors are certain spans of functors, $C\xleftarrow{J} C' \xrightarrow{F} D$, and every functor $G$ gives rise to a canonical functor $C\xleftarrow{id} C \xrightarrow{G} D$. The functor $J$ is surjective on objects and fully faithful, and the set of objects $c'$ of $C'$ in the preimage of a given object $x$ of $C$ give rise to a set of objects $F(c')$ in $D$, all of which are isomorphic, and which Makkai calls the possible values of $F$ at $c$ (think of the limit of a diagram for instance: it is not unique, but all such limits are isomorphic, and any of them will do).
Small categories, anafunctors and transformations form a bicategory (not strict!), which is not a (2,1)-category, unless we throw away all the non-invertible 2-arrows. If you take small groupoids, anafunctors and transformations, then it is a (non-strict) (2,1)-category, purely because all natural transformations involving groupoids are invertible.
Even ignoring the size distinctions (which are not important, but you have been specifying small categories until now), $Set$ is not equivalent to $Set^{op}$ in the bicategory of categories, anafunctors and transformations, as (for instance) $Set$ is a(n elementary) topos and $Set^{op}$ is not, and the property of being a topos is invariant under equivalence (even in the anafunctor setting).

One place to read about anafunctors in a slightly more general setting is in my paper Internal categories, anafunctors and localisations, but the construction goes back to Makkai's paper Avoiding the axiom of choice in general category theory, Journal of Pure and Applied Algebra 108 issue 2 (1996) pp 109-173, https://doi.org/10.1016/0022-4049(95)00029-1, in the case of ordinary categories and to Toby Bartel's thesis Higher Gauge Theory I: 2-Bundles https://arxiv.org/abs/math/0410328, for internal categories. There are more references at the nLab page on anafunctors.

Category of categories and anafunctors.


errors when piping a specific find command and creating a zipfile from its output?

Question: I wish to create a program that zips whatever file is created in the directory the find parameters specify, and run it as a background process. I heavily comment it to give a better idea of what I'm trying to achieve. I'm running this from my MacBook Pro terminal, OS X version 10.9
#!/bin/sh

#find file in directory listed below
#type f to  omit  directories or special files
#mtime/ctime is  modified/created  -0 days or less
#name is with the name given in double quotes
#asterik meaning any file name with any file extension
#use xargs to convert find sequence to a command for the line after pipe
find /Users/name/thisdirectory type f -ctime -0 -name "'*'.'*'" | xargs zip -

Answer: Maybe you're looking for this:
find /path/to/dir -type f -ctime -0 -name "*.*" | zip -@ file.zip

If you read zip -h, it explains that -@ is to read the filenames from standard input.
You don't need xargs here, the function to work with a list of files received from standard input is built into zip itself, similar to most compression tools like tar.
Btw, I think you want to change -ctime -0, because I don't think it can match anything this way...


Como me proteger contra "MongoInjection"

Question: Uso MongoDB em uma aplicação front-end que roda no Node.JS através da framework Express.
Gostaria de saber como criar proteções contra MongoDB "Injection" (similar a sql injection).
Comment: O termo correto seria NoSQL injection
Answer: Encontrei o seguinte descritivo na thread do SOen e achei interessante compartilhar nessa sua questão:
O ponto é converter e interpretar os dados de entrada
MongoDB evita potenciais problemas desse tipo por não realizar conversões de dados.
Ele não realiza conversões em estruturas de texto para descobrir o quê fazer, dessa forma não existe a possibilidade de má interpretação dos dados...
Nessa referência possui um link indicativo sobre leitura complementar para ajudar em pontos ao escrever código seguro (caso seja uma preocupação).
Fonte: How does MongoDB avoid the SQL injection mess?


Selecting data based off rolling quarter value

Question: I need to create a condition that will filter for dates in the next 8 quarters worth of data, based on the current quarter. The issue is this needs to be rolling. For example, as I'm writing this, it is 2/2/2023. The data condition would need to be such that it takes the data in the current quarter (i.e., Q1), and subsequently the current quarter +1, + 2, etc. The issue is when I get to a new year, as PostgreSQL does not allow you to do datefield + interval '1 quarter'. So, when I need an automated way of pulling the data for Q1 in 2023, I can't simply use the interval.  This is also an issue when, say, I get to Q4. I can't do datefield + interval '1 quarter', because that gives Q5, which does not exist.
Any tips for getting this taken care of? My current thinking is that i need to create conditional logic where, if current quarter is Q4, filter where data is in Q1 of current year + 1, but am wondering if there are more efficient ways of doing this.
My current (and incomplete) solution is as follows:
select *
from mytable
where extract(quarter from datefield) = extract(quarter from current_date + interval '1 quarter')
    and datefield >= concat(extract(year from current_date), '-01-01')::date
    and datefield <= current_date + interval '2 years'

Thanks!
Answer: After another hour or so of digging, I found another post which answered this question:
see here
The solution relies on date_trunc, which makes lots of sense.


Any good webcrawler besides DRKSpider

Question: I was having a look at DRKSpider to find problems with a website in our production server, but it seems its export feature generates different outputs (with different content).
My goal is to find a good tool that shows every type of status code that might be an error 404, 500, 403, etc.
Could you guys please suggest some open source tools to craw a website in order to list all server codes related to error?
Comment: `man wget` and it's spider option. Or HTTrack or cURL or anything else found on Google. Even Google itself with the Webmaster tools.
Answer: I think the hardest part of this is that most open source tools won't implement a full DOM with a js and css engine.  So you're likely to run into issues where even using wget will not expose broken java script issues on your site.  If you are trying to figure out what errors your site might be generating for users you should look at implementing a spider that does support js/css/etc.  Something like:
http://atomz.com/ (free up to 10,000 pages)
You can also use google webmaster tools like @mailq mentioned, here is more details on their crawl errors section:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=35120&ctx=cb&src=cb&cbid=g2fqlm56h5t&cbrank=0
Lastly, if you aren't already you should be watching your logs for these errors and tracking referrer information so you can hopefully investigate them then as well.

Any good webcrawler besides DRKSpider


Showing that $d\Phi =0$ for $\Phi=\sum_{i=1}^{k} a_{i}(\mathbf{x}) d x_{i}$

Question: I am given
 $\Phi=\sum_{i=1}^{k} a_{i}(\mathbf{x}) d x_{i}$
and want to show that $d\Phi=0$ if and only if
$$\frac{\partial a_{i}(\mathbf{x})}{\partial x_{j}}=\frac{\partial a_{j}(\mathbf{x})}{\partial x_{i}}$$
This is how I started
\begin{aligned}
d \Phi &=\sum_{i=1}^{k} d a_{i}(\mathbf{x}) \wedge d x_{i} \\
&=\sum_{i=1}^{k} \sum_{j=1}^{k} \frac{\partial a_{i}(\mathbf{x})}{\partial x_{j}} d x_{j} \wedge d x_{i}
\end{aligned}
but I don't know how go from there, can someone please guide me? And how would I use the equation given to me above?
Comment: You should watch more of my YouTube lectures :P
Comment: Hint: what do you know about the wedge product $\wedge$?
Comment: @giobrach I tried thinking of their properties but did not really get to an answer. I looked up this question and found that there is an extra step where $\sum_{1 \leq j<i \leq k}\left(\frac{\partial a_{i}(\mathbf{x})}{\partial x_{j}}-\frac{\partial a_{j}(\mathbf{x})}{\partial x_{i}}\right) d x_{j} \wedge d x_{i}$, but I am confused as to why we did this...
Comment: I feel like I am missing something.
Comment: See my answer below.
Comment: @TedShifrin I definitely should :D
Answer: The wedge product $\wedge$ is alternating, meaning that for all $i, j$ with $1 \leq i,j \leq k$ one has
$$ dx_j \wedge dx_i = - dx_i \wedge dx_j. $$
Therefore not all the terms in the double sum are linearly independent, some even vanish (when $i = j$): you are allowed to only sum over pairs $(i,j)$ such that $i < j$.
$$d\Phi = \sum_{i=1}^{k} \sum_{j=1}^{k} \frac{\partial a_{i}(\mathbf{x})}{\partial x_{j}} d x_{j} \wedge d x_{i} = \sum_{i<j} \left(\frac{\partial a_{i}(\mathbf{x})}{\partial x_{j}} - \frac{\partial a_{j}(\mathbf{x})}{\partial x_{i}} \right) d x_{i} \wedge d x_{j}.$$
On the RHS there are now no redundant terms (indeed the set $\{dx_i\wedge dx_j\}_{i<j}$ forms a basis of the space of $2$-forms), and the components that appear in front of $dx_i \wedge dx_j$ are the actual components of $d\Phi$.
Now you may easily see the equivalence between the two conditions.
Comment: This finally made sense to me. Thank you so much!
Comment: Glad I could help


PDO How to pass on the ID Key

Question: I know there is something basic staring me in the face here. I could do this in mysql but in PDO I can't get the Key(id) of a row to pass on to the next page. When a user clicks on "More Details" on a row I want it to open a page with all the details for that row plus the full size photo. It is currently opening the page, putting Key = (the right number) in the address bar and writing "no rows found" in the page. What am I doing wrong and is there a better way I should be doing this?
This page has the rows from the search:
 <?php
  $STM = $dbh->prepare("SELECT * FROM engravers WHERE Country = :Country");
  if(isset($_POST['dropdown'])){
  $Country = $_POST['dropdown'];
  }else{
  $Country = "Australia";
  }

 $STM->bindParam(':Country', $Country, PDO::PARAM_STR);
 $STM->execute();
 $row= $STM->fetchAll();
 $img_url = "http://www.engravedstamps.net/images/";
 if(count($row)){
 echo "
";

 foreach($row as $data){
         $Key = $data['Key'];
         echo "
Key	Country	Year	Description	Image
";
         echo "
".$data['Key']."	";
          echo "".$data['Country']. "	";
          echo "".$data['Year']."	";
           echo "".$data['Description']."	";
           echo ""."

    <a href="more.php?Key=<? echo $data['Key'];?>">More Details
            <?

    echo "
";
     }
     }else {
     echo 'no row found';
     }
     ?>

That page seems to work and should hand the Key to this page which is basically a rejig of the one before. I haven't rebuilt the table at the bottom yet.
 <?php

 $STM = $dbh->prepare("SELECT * FROM engravers WHERE Key = :Key");
 if(isset($_GET['Key'])){
 $Key = $_Get['Key'];
 }else{
 $Key = "Oops";
 }

 $STM->bindParam(':Key', $Key, PDO::PARAM_INT);
 $STM->execute();
 $row= $STM->fetchAll();
 $img_url = "http://www.engravedstamps.net/images/";
 if(count($row)){

 echo "
";

 foreach($row as $data){
                 echo "
Key	Country	Year	Description	Image
";
         echo "
".$data['Key']."	";
          echo "".$data['Country']. "	";
          echo "".$data['Year']."	";
           echo "".$data['Description']."	";
           echo ""."

I've spent all day on this which will teach me a lesson for thinking this was a simple part of the operation. Any help will be greatly appreciated.
Comment: Your code is so messy, i passed whole part of it. Dont know may be help `$Key = $_Get['Key'];` must be `$Key = $_GET['Key'];`
Answer: $_Get should be $_GET when you're copying your Key:
Change
$Key = $_Get['Key'];

To
$Key = $_GET['Key'];

And, to answer is there a better way I should be doing this?:
You're using PDO: Good
You're using prepared statements with bindValue for user input: Good
You're checking if user input exists before attempting to use it: Good
You're using $Key = "Oops"; in replacement of no Key: Not good, this converts to an integer value of 1.
I'd say you're doing things right, the main thing that I would do differently is: I would have my database logic elsewhere (separate file/class), as I do not like to mix display logic with database logic.  However, this is a design decision and not something you're doing wrong.
Comment: I've been staring at that one all day but unfortunately fixing it doesn't change the result. Darn! I thought that was it.
Comment: Try doing a `var_dump($Key);` before using it.  Also try `error_reporting(E_ALL);`
Comment: var_dump gives me a message "string(1) "4" no row found". It could be from the previous page. I've just noticed that the printed table is missing the first entry for every country. As I'm just trying to print one line here and the code is pretty similar the problems look like they are the same. Darned if I can see it though."4" is the Key for the row clicked.
Comment: My reading on other posts is suggesting that I can't bind the Key in this way as it is the $_Get value and is also the name of the column.
Comment: Have you tried casting it to an integer directly?  I was assuming using `PDO::PARAM_INT` would force the cast.  Fe. `$Key = (int)$_GET['Key'];`
Comment: That doesn't seem to change things. The Get is working but I think the problem is that it ends up as $Key but then we try to go back to Key for the param binding which introduces another $Key. I'll work around that for a while.

PDO How to pass on the ID Key


How to splite Trial c#

Question: hi i want to get just the Crm and the number in the line
tenx
string emailsubject = "Email Test 2 CRM:0276002";

public string GetCrmSubjectNum()
{
    string final = //;

    return "";
}

Comment: Do you always have this kind of format? So always "CRM:*" t the end of a string where you want the number after `CRM:`? There are many different ways of how to solve this, so can you please add more examples on how your string could look like?
Comment: yes i have this number after the crm i need the num by function in c# that bring my string answer
Answer: It is a little bit unclear what you want.
If you always have "CRM" in the subject, then you could do it like following:
using System;

   namespace ConsoleApplication1
   {
    class Program
    {

        static void Main(string[] args)
        {
            string emailsubject = "Email Test 2 CRM:0276002";

            emailsubject = GetCrmSubjectNum(emailsubject);

            Console.WriteLine(emailsubject);

            Console.Read();
        }

        public static string GetCrmSubjectNum(string emailsubject)
        {
           emailsubject = emailsubject.Remove(0, emailsubject.IndexOf("CRM"));

            return emailsubject;
        }
    }
}

Comment: If you just need the number you could do: emailsubject = emailsubject.Remove(0, emailsubject.IndexOf("CRM") + 4);
Comment: sorry man but i need the crm to
tenx
Answer: I would go with this, because Substring() is the fastest way:
public string GetCrmSubjectNum(string emailSubject)
{
    return emailSubject.Substring(emailSubject.IndexOf("CRM:", StringComparison.Ordinal) + "CRM:".Length);
}

How to splite Trial c#


Problems on combinatorics

Question: The following comes from questions comes from a recent combinatorics paper I attended :
1.27 people are to travel by a bus which can carry 12 inside and 15 outside. In how many ways can the party be distributed between inside and outside if 5 people refuse to go outside and 6 will not go inside?
The solution given C(16,7), I have no clue how they got it ?!
2.The number of functions f from the set A = {0, 1, 2} into the set B = {1, 2, 3, 4, 5, 6, 7} such that $f(i) \le f(j) $ for $i \lt j $ and $i,j$ belongs to A is
The solution given is C(8,3). I didn't really understood this one.
3.The number of ordered pairs $(m, n) m, n $ is in {1 , 2, … , 100} such that $7^m + 7^n$ is divisible by 5 is
The solution given is 2500, but how ?
4.The coefficient of $x^{20}$in the expansion of $(1 + 3x + 3x^2 + x^3)^{20}$, is ?
How to solve this one elegantly ?
5.An eight digit number divisible by 9 is to be formed by using 8 digits out of the digits 0, 1, …, 9 without replacement. The number of ways in which this can be done is:
Now this one seems impossible for me to solve in 1 mint,or is it ? Given soln is 36(7!)
Comment: Ha, I was wondering for a second what "1.27 people" meant... ;)
Comment: Nice question, but _please_ split such questions up into pieces to be answered individually next time. Also, the title is quite unenlightening.
Comment: @HansLundmark, made my day. +1
Answer:
Five people refuse to go outside, and therefore will go inside. Six people refuse to go inside, so will go outside. That means that you still have $27 - (5+6)=16$ people to accommodate. There are 12 spots for people inside, but five are already "taken" by those who refuse to be outside. That leaves 7 seats inside to assign. So you need to choose which seven people, out of the 16 that are left, will go inside. The number of ways of doing this is precisely $\binom{16}{7}$.
Edit: I misread the question as saying that $f(i)\lt f(j)$ if $i\lt j$. That answer follows: since you require the values of the function to increase (the condition just says that $f(0)\lt f(1)\lt f(2)$), if you know the three values of $f(0)$, $f(1)$, and $f(2)$ you know which one corresponds to which ($f(0)$ is the smallest value, $f(1)$ is the middle value, and $f(2)$ is the largest value). So all you need to do in order to determine a function is to pick three values from $B$. There are $7$ possibilities, you need to pick $3$, so there are $\binom{7}{3}$ ways of doing it.
Now, it seems I misread the question. It actually says that $f(i)\leq f(j)$ if $i\lt j$. I gave the number of functions in which all inequalities are strict. There are $\binom{7}{1}$ functions in which all inequalities are actually equalities (just one value). Now, to count the number of functions in which $f(0)=f(1)\lt f(2)$, you just need to pick two values from the set $B$, which there are $\binom{7}{2}$ ways of doing; the same holds for the case in which you have $f(0)\lt f(1)=f(2)$. So the total is $\binom{7}{3}+2\binom{7}{2} + \binom{7}{1}$. Since $\binom{n}{k}+\binom{n}{k-1} = \binom{n+1}{k}$,  this total is equal to
$$\left(\binom{7}{3} + \binom{7}{2}\right) + \left(\binom{7}{2}+\binom{7}{1}\right) = \binom{8}{3}+\binom{8}{2} = \binom{9}{3}.$$ It seems to me, then, that the answer you give is incorrect, or perhaps you mistyped it.
(If you know the formula for combinations with repetitions, then there is a more direct way of getting this result: simply pick $3$ out of the $7$ possible images, with repetitions allowed; smallest value is $f(0)$, middle value is $f(1)$, largest values $f(3)$ (equality allowed). The total for this is $\binom{7+3-1}{3} = \binom{9}{3}$, as above).
Assume $m\leq n$; then $7^m+7^n = 7^m(1 + 7^{n-m})$. The product is divisible by $5$ if and only if $1 + 7^{n-m}$ is divisible by $5$ (since $5$ is prime and never divides a power of $7$). For $1+7^{n-m}$ to be divisible by $5$, you need $7^{n-m}$ to have a remainder of $4$ when divided by $5$. If you run over the powers of $7$ and see the remainder when divided by $5$, you will notice that they go $2$, $4$, $3$, $1$, and repeat. So basically, you need $n-m$ to be a multiple of $4$ plus $1$. That is, you need $n-m = 4k+1$. Note in particular that if the pair has $n=m$, then it does not satisfy the condition. So count how many pairs there are where the two differ by a multiple of four plus 1.
One possibility is the Multinomial theorem You would need to figure out all the ways in which you can obtain $x^{20}$ as products of powers of $x$, $x^2$, and $x^3$, and add the appropriate coefficients. Edit: But the intended answer is almost certainly the one given by Larry Denenberg.
In order for the number to be divisible by $9$, the digits must add up to a multiple of $9$. The digits $0$ through $9$ add up to $45$, which is a multiple of $9$. So if you omit two of them, they must add up to $9$: thus, if you omit $0$, then you must also omit $9$; if you omit $1$, then you must also omit $8$; etc. So you only have five possible pairs of numbers that you can omit. So pick which of the five pairs you will omit. If you omit $0$ and $9$, then the remaining $8$ digits can be arranged in any order, giving $8!$ possibilities. In all other cases, you cannot place $0$ in the first position, but otherwise can place the rest in any order. That gives $7(7!)$ possible ways of ordering the numbers. Thus, you have one choice that leads to $8!$ numbers, and four choices that lead each to $7(7!)$ numbers. Adding them up gives $8!+(4\times 7)(7!) = 8(7!)+28(7!) = 36(7!)$.
Comment: @Debanjan: There is no need; if you know *exactly* who is inside, then you automatically know who is outside (namely, whoever is not inside). You can do the exact same thing if you instead figure out who is going outside; then whoever is left is going inside.
Comment: +1 but, in (1) why there is no consideration for remaining (vacant) 9 seats which is outside ?
Answer: For number 4, the multinomial theorem is overkill.  The given expression is just $((x+1)^3)^{20} = (x+1)^{60}$. The coefficient of $x^{20}$ is $60\choose 20$.
Answer: For number 4 you would use the multinomial theorem.
Answer: 1.Obeying the stated restrictions now you have 7 places inside and 9 outside so the number of ways to accommodate accordingly is $C (16, 7) = C (16, 9)$.
3.We have $5 | 7^m + 7^n \iff 5 | 2^m + 2^n$ and if $m \equiv k \pmod 4$ we have $n \equiv k + 2 \pmod 4$. So we have for ordered pairs of $(m, n)$ precisely $100^2/4 = 2500$ ways to exist.
4.Notice that we ask for the coefficient of $x^{20}$ in the expansion of $(x + 1) ^ {60}$, which is obviously $C (60, 20)$.

Problems on combinatorics


ReJson - Retrieve all values from matches of 2nd layer of keys

Question: I am trying to get all values whose 2nd level key is same. Does ReJson Support this functionality?
For example:
JSON.SET myKey . '{"book1": {"author":"xyz", "price":100}, "book2": {"author":"abc", "price":200}}'
JSON.GET myKey .book1.author => "\"xyz\""
JSON.GET myKey .book2.author => "\"abc\""
Trying to fetch all author's values
JSON.GET myKey ..author
Getting the following error:

(error) ERR Search path error at offset 2: an identifier can only begin with a letter, a dollar sign or an underscore - use bracket notation for anything else`

JSON.OBJKEYS myKey . => 1) "book1" 2) "book2"
The doc says it does support JSON PATH.
Links:https://oss.redislabs.com/rejson/ https://goessner.net/articles/JsonPath/
Answer: No, ReJSON does not provide that functionality yet.
The docs say:

ReJSON's syntax is a subset of common best practices and resembles JSONPath
Answer: try:
json.mget myKey $..author

https://oss.redis.com/redisjson/commands/#jsonmget
Comment: 127.0.0.1:6379> JSON.SET myKey . '{"book1": {"author":"xyz", "price":100}, "book2": {"author":"abc", "price":200}}'

OK

127.0.0.1:6379> json.mget myKey $..author

1) "[\"xyz\",\"abc\"]"


Ajax jquery on success return different html data in multiple divs:

Question: Is it possible to return different data (html type) to different divs ?
<code> $.ajax({
        url: "file.php",
        type: "POST",
        dataType:"html",
        data: {"id":id}
        }).done(function(data){
         $("#div1").html(data);
         $("#div2").html(data); //how to do with a second div ?
        })
</code>
Comment: Your question in unclear, can you please explain it better?
Answer: You can realize nested ajax requests like this:
<code>$.ajax({
 url: form_url,
 type: form_method,
 data: form_data,
 cache: false,
 success: function(data){
      $.ajax({
      url: form_url,
      type: form_method,
      data: form_data,
      cache: false,
      success: function(data){
        $("#div2").html(data);
      }
     });
 $("#div1").html(data);
 }
});
</code>
I hope this helps :-)
Comment: Hi, did this work? I'm looking for the same thing, data gets returned to the first div I have, but not the second?


How to read the x-axis of this qqplot?

Question: I am new to qqplot and trying to figure out the labels on the x-axis of this plot:

The left plot is the Verbal SAT score of 105 college students majoring in CS. The right plot is the GPA score. Source of the plot
I understand that the qqplot means "quantile vs quantile", the y-axis is each student's test score, but what is the x-axis and why it is from -2 to 2?

Update: For anybody whose looking for a more visual explanation of QQ-plot, check out this video on youtube: https://www.youtube.com/watch?v=X9_ISJ0YpGw
After reading and watching dozens of articles and videos, let me explain what is the x-axis and the y-axis in layman's term.
The y-axis is the values you recorded. Like the verbal SAT score in my example. Because there are 105 of verbal SAT sores, there should be 105 values on the x-axis as well.
There are three steps involved in order to get these 105 values:
Step 1
Sort the 105 values in ascending order and give each one of them an index number starting from 1, 2, 3 .... all the way up to 105. Let's use i to denote each index number.
Step 2
Use this formula to find a list of percentages (I will explain what are they later, just keep on reading):
$\left(\dfrac{i-0.5}{n}\right)$
So you will get 105 values that looks like this:
$\left(\dfrac{1-0.5}{105}\right)$, $\left(\dfrac{2-0.5}{105}\right)$, $\left(\dfrac{3-0.5}{105}\right)$ ... $\left(\dfrac{105-0.5}{105}\right)$
Step 3
Find the z-score of the values we just calculated in step 2. These z-scores are the x-axis of the qq-plot
Now, plot the verbal SAT scores as the y-axis and the z-scores as the x-axis, you will get a qq-plot.

Ok, now it is the time to explain the meaning of step 2 & 3. Let's start with the definition of cumulative distribution function.
Let's say we have a test and the maximum score a participant can get is 100 points. After taking the test, 50% of the participants scored 60 points or less, 40% of the participants scored 50 points or less, 30% of the participants scored 40 points or less, and so on.
The cumulative distribution function (aka. CDF) takes one input, a test score, and it outputs a percentage which tells you the percentage of people who scored less than or equal to that test score. With the example case above, If I put 60 points into the CDF function, I should get 50% back. If I put 50 points I get 40%.
The inverse of the cumulative distribution function takes one input, a percentage and it outputs the corresponding test score. If I put in 50%, it should give me 60 points. It does nothing fancy other than reverse the function of CDF.
Step 2 basically calculated a list of percentages and when we feed that list of percentages into Step 3  and get back a list of z-scores. So Step 2 + Step 3 = calculating the inverse of the cumulative distribution function.
The list of percentages calculated in Step 2 looks like this: 0.005, 0.014, ... 0.995. The list of z-scores in Step 3 looks like this: -2.575829304, -2.197286377, ... 2.575829304. It means for participants who scored less than or equal to 0.5% (0.005 x 100) of the total participants, the corresponding z-score is -2.57.
So what does the qq-plot tell us in our example: If the verbal SAT score indeed follows a standard normal distribution (mean=0, variance=1), then the outline of the histogram of the test scores should resemble the bell curve of the standard normal distribution.
But it is really hard to judge if a histogram matches the shape of a bell curve, a straight line is probably a better choice for the naked eyes. Let's match the observed values against the z-scores.
Answer: This seems to be a qqplot of the data compared with a standard normal distribution, so I would have thought the $x$ values should the typical values of the population quantiles of a standard normal distribution
So with $105$ observations I would have thought the extreme left $x$ value should be not far away from $\Phi^{-1}\left(\dfrac{0.5}{105}\right) \approx -2.59$ and the one next to it near $\Phi^{-1}\left(\dfrac{1.5}{105}\right) \approx -2.19$, with the extreme right values being the corresponding $\Phi^{-1}\left(\dfrac{104.5}{105}\right) \approx +2.59$ and $\Phi^{-1}\left(\dfrac{103.5}{105}\right) \approx +2.19$. Visually, this seems to be close to what you have in the charts
Comment: Just a note: R seems to use [slightly different quantiles for plotting](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/ppoints.html)  when the sample size is $10$ or less
Comment: $\Phi^{-1}(y)$ with $0 \lt y \lt 1$ is the inverse cumulative distribution function of a standard normal distribution function with mean $0$ and variance $1$.  You may have come across it with $95\%$ confidence intervals where $\Phi^{-1}(0.025)=-1.96$ and  $\Phi^{-1}(0.975)=+1.96$ so there is a probability of $0.975-0.025=0.95$ of being up to $\pm 1.96$ standard deviations from the mean.
Comment: If I want the probabilities of $105$ values to be equally spread out between $0,$ and $1$, I could take $\dfrac{0.5}{105},\dfrac{1.5}{105},\dfrac{2.5}{105},\ldots,\dfrac{104.5}{105}$ and find what values these correspond to using the inverse cumulative distribution function of my theoretical distribution
Comment: Thanks for your explanation. From what I read, the x-axis represents the `quantiles from a theoretical distribution`. Could you expand a little on what that means? and what is the formula you used for calculating phi?
Comment: In qq-plot, why the y-axis is not the quantiles of the observed values? (from what I read, it is the observed values themselves)
Comment: The $y$-values are the *sorted* observed values, which can be taken as being the empirical quantile values
Comment: Hmmmm,that doesn't make much sense logically don't you think?

How to read the x-axis of this qqplot?


RVM can not change gemset

Question: Before I installed MySQL and restart my computer, my RVM works well.
If I type
rvm gemset use rails

It will show:
Using ruby-1.9.3-p194 with gemset rails

and then I type:
rvm gemset name

It shows:
rails

which is correct.
However, after I restart my computer, something strange happens.
Firstly, the system cannot find the command 'rvm', so I modified by ~/.bash_profile:
export PATH=/usr/local/mysql/bin:/Users/hanxu/.rvm/bin/:$PATH

Above is the content of my .bash_profile
Then rvm works.
Then I type:
rvm gemset use rails

It seems running well and shows:
Using ruby-1.9.3-p194 with gemset rails

However, when I examine it by asking rvm gemset name, it turns to be:
/Users/hanxu/.rvm/gems/ruby-1.9.3-p194

which is my default gemset, rather than "rails".
No matter how I set gemset, it always change to the default setting.
Can anyone tell me what's the problam?
Comment: Did you follow instructions during RVM installation? It requires a command added to your `.profile`/`.bashrc`/whatever.
Comment: Do you have this string anywhere `[[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm`? This is what loads RVM in your session.
Comment: Also, I'd remove that rvm entry from the PATH.
Comment: @SergioTulentsev, my RVM installation is automatically completed and I don't remember I have to set anything...
Comment: Sometimes it adds it for you. Just checking.
Comment: @SergioTulentsev.Problem solved! I add this code to my .bash_profile..thank you...BTW..can you explain what this code mean?
Comment: Posted as an answer, with a little explanation :)
Comment: the PATH entry should be in `.bashrc` - so rvm is available also from non login shell, it's called binary or non interactive mode - when `rvm use` does not work, but also rvm does not do any interactions like displaying `rvm requirements` when first ruby is installed
Answer: Are you using an .rvmrc file?
https://rvm.io/workflow/rvmrc/
Comment: solved. add [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" to my bash_profile...
Answer: Your RVM installation is most likely incomplete. Look for this string in your .profile / .bashrc / .zshrc or whatever else you might be using
[[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm

This command checks for existence of $HOME/.rvm/scripts/rvm and, if found, loads it into the shell. This effectively loads the RVM. So, if you don't find this command, add it and open a new terminal window, RVM should be there.
Comment: for long time rvm was giving you information where to put it, then we have started adding sourcing to different *rc/*profile files, right now we got to the final version which is ~/.bash_profile ... and rest like stated above
Comment: files you mention should not include that line, it can break a lot of things like X serer or ssh, this line should be in `~/.bash_profile` or/and `~/.zprofile` alternatively   `~/.bash_login` or/and `~/.zlogin` - but the *login files are less preferred.
Comment: I am pretty sure that RVM was always putting it into `.profile`.  :)
Answer: rvm has a command to fix sourcing:
rvm get stable --auto

the auto switch will update your *rc files, then it should be enough to open new terminal and it should be all fine.
Answer: Use this command to switch gemset.
rvm use <ruby version>@<gemset name> --create

This command will switch rvm to given gemset and create it, if it does not exist.
Answer: In my case, I needed to add the user to the rvm group before I could use rvm.

RVM can not change gemset


Compare conditional effects (simple slope) from regression model

Question: I have the following regression outputs from a model that includes both quadratic and cubic interaction terms. I calculated the simple slopes using the simle_slope from reghelper.
x1 <- rnorm(100)
x2 <- rnorm(100)
x3 <- rnorm(100)
x4 <- rnorm(100)

y   <- x1 + x2 + x2**2 + x1*x2 + x3 + x4 + rnorm(100)
fit <- lm(y ~ x1 + x2 + I(x2^2) + I(x2^3) + x1:x2 + x1:I(x2^2) +
    x1:I(x2^3) + x3 + x4)

summary(fit)

library(reghelper)
test2 <- simple_slopes(fit, level = list(x2 = c(0,1,2,3), confint = T))
test2$L95 <- test2$`Test Estimate`-1.96*test2$`Std. Error`
test2$U95 <- test2$`Test Estimate`+1.96*test2$`Std. Error`
test2

test2
      x1 x2 Test Estimate Std. Error t value df  Pr(>|t|)        L95      U95 Sig.
1 sstest  0        1.1733     0.1642  7.1437 92 2.085e-10  0.8514158 1.495274  ***
2 sstest  1        2.0379     0.1895 10.7562 92 < 2.2e-16  1.6665505 2.409244  ***
3 sstest  2        2.7164     0.8014  3.3896 92  0.001033  1.1456684 4.287227   **
4 sstest  3        3.2395     2.6804  1.2086 92  0.229911 -2.0140209 8.493070

I understand simple slope can tell us whether or not a conditional effect based on a specific value of moderator is statistically different from zero.
My question is, the confidence interval (L95, U95) of the simple slope of x1 when x2 = 0,1 is not overlapped. Can I say there is a statistically significant difference in the simple slopes of x1 when x2 = (0,1)? In other words, can I tell the simple slopes of x1 when x2 = 0,1 are significantly different from each other?
Answer: Non-overlap of confidence intervals is too stringent for determining "statistically significant" differences between estimates. This page has a superb illustration.
If your interest is in differences between "simple-slope"* estimates, then evaluate those differences directly. For example, the emmeans package provides ways to examine all pairwise differences among a set of "simple slopes" evaluated as emtrends:
library(emmeans)
emtrends(fit,pairwise~x2,at=list(x2=c(0,1,2)),var="x1")
# $emtrends
#  x2 x1.trend    SE df lower.CL upper.CL
#   0     1.02 0.134 90    0.755     1.29
#   1     2.39 0.176 90    2.040     2.74
#   2     2.80 0.365 90    2.069     3.52
#
# Confidence level used: 0.95
#
# $contrasts
#  contrast  estimate    SE df t.ratio p.value
#  x20 - x21   -1.371 0.160 90  -8.542  <.0001
#  x20 - x22   -1.776 0.417 90  -4.255  0.0002
#  x21 - x22   -0.405 0.381 90  -1.063  0.5393

The "simple slopes" at each value of x2 are indicated by x1.trend in the $emtrends output, along with standard errors and confidence levels. They differ somewhat from yours as you didn't specify a random seed, and I limited the range of x2 as there weren't any values as high as 3 in the data. (I used set.seed(101) before running your code.) Your example shows a much higher standard error for the slope when x2=2, which I also assume is because of the difference in random seeds.
The differences in slopes among the pairs of x2 values are in the $contrasts output. x20 means the situation in which x2=0, etc., so the first line for the contrast x20-x21 is the particular comparison you note in the question.

*I personally find "simple slopes" to be not so simple, so I put quotes around the phrase.


pass untruncated string in AJAX parameter

Question: I am passing and argument of type string to an AJAX call. The value i am passing reads as 01007 but when i handle the call at server side, it passes 1007.
Is there a way i can pass the argument as String and get 01007 in the service call? I tried data:"{someKey:" + passedKey.toString() + "}" but it didnt work. Here passedKey is 01007.
Argument type in the service call is string.
Comment: toString() converts boolean values, string(passedKey) is what you want.
Comment: @Ohgodwhy what the heck is `string(passedKey)`?? I never saw this in javascript...
Comment: @Christoph: He means `String()`.
Comment: @Ohgodwhy: Neither one will make any difference.
Comment: @SLaks well, the difference between `string()` and `String()` is tiny, but yet extremely huge, since the first one will most likey throw a Reference Error...
Answer: Your concatenated JSON string reads {someKey:01007}.
Do you see the problem?
You should pass an object literal, not a JSON string.
jQuery will then serialize it correctly.


Asp.net-mvc PlaceHolder, how to use it?

Question: I have my Master Page with some Html.RenderPartial and a random ContentPlaceHolder inside it, more or less like this:

<% Html.RenderPartial("Controls/Menu"); %>
<% Html.RenderPartial("Controls/GenericControl"); %>
<asp:ContentPlaceHolder ID="MyContent" runat="server" />

At the moment in the Menu.ascx file I have a list of buttons. In the GenericControl.ascx file there are some buttons to manage the content.
And I have as many views as buttons in my Menu and the content is so described:
<asp:Content ID="Content1" ContentPlaceHolderID="MyContent" runat="server">

Some divs here

<asp:Content>

And here's my problem.
I would like to put another asp:Content in my views, I don't want to link it in the Master Page but in the GenericControl.
Obviously I can't use the ContentPlaceHolder. I'm trying to use the PlaceHolder instead but I'm having some problems to find how to use it.
Answer: If you are using Asp.net MVC, you should not use server controls (the ones which starts with <asp: />).
Do define Placeholders in asp.net mvc using Razor engine, you can do this:
In _Layout
@RenderSection("header", required: false)

In view
@section header {

Hello World

}

To make it work in web forms view engine, probably you have to replace @ with <% %>
Comment: My problem, in few words, is that they gave me that files and they said "Make this site work and make it good looking!"
And I'm still learning how this _logic_ works.

Anyway thanks for the answers and I'll try what you suggested.

Asp.net-mvc PlaceHolder, how to use it?


The Amalgamation Property in AECs

Question: I am new to abstract elementary classes (AEC) and am reading the early chapters of Baldwin's Categoricity text. I have shown that the disjoint amalgamation property holds for an AEC obtained by looking at the models of a first order theory (this is a straight forward compactness argument). However I have not been able to come up with an AEC for which the disjoint amalgamation property fails. I was hoping to have an example in $L_{\omega_1 \omega}$. Does anyone know of such an example?
Also, it is straightforward to come up with classes for which the joint embedding property (JEP) fails but the amalgamation property (AP) holds (For example: models of ACF will have this property). However what about AEC in which you have the JEP but not AP? The only example for a class of structures where this is true, that I know of, involves finite structures, so I would like to know of an example where all the structures are infinite.
Comment: Exercise 12, p. 332 of Hodges's *Model Theory* asks you to show that a certain class (the description is there) has the JEP property, but not AP. Perhaps it's worth a look?
Comment: For what it's worth, I can't make sense of Hodges Exercise 12. It seems to me that the theory described there has only the empty model; there must be a typo. Also, as noted in the question, it's easy to come up with classes of finite structures which have HP and JEP but not AP, e.g. the class of acyclic graphs together with a unary predicate. kav11 wanted an example in the setting of infinite models of a sentence in $L_{\omega_1,\omega}$.
Comment: @AlexKruckman - I suppose the third axiom should state that the relation is not transitive?
Answer: Here's an example in $L_{\omega_1,\omega}$ for your first question. Let $L$ be the vocabulary with countably many unary predicates, $\{P_i\mid i\in \omega\}$. Let $T$ be the first-order theory asserting that the predicates interact generically (so for all $n$ and all $f\colon n\to 2$, there is an element $x$ such that for all $0\leq i < n$, $P_i(x)$ iff $f(i) = 1$.) Let $\varphi$ be the conjunction of the sentences in $T$, together with the following infinitary sentence: $$\forall x\, \forall y\, \left(\bigwedge_{i\in \omega}P_i(x) \leftrightarrow P_i(y)\right)\rightarrow (x = y).$$
Now models of $T$ are in bijection with dense subsets of $2^\omega$, and all embeddings are elementary for the fragment of $L_{\omega_1,\omega}$ generated by $\varphi$. The corresponding AEC clearly has JEP and AP (just take unions of dense subsets), but it fails to have the disjoint AP, since if $a\in A$ and $b\in B$ satisfy the same predicates, they must be identified in any amalgamation.

For your second question, it's easy to come up with combinatorial examples, and not just dealing with finite structures (e.g. take infinite graphs with no cycles, plus a unary predicate picking out a subset of the vertices, together with all embeddings). So you probably want another example in $L_{\omega_1,\omega}$.
Let's take the above example, but break amalgamation entirely. So add an additional predicate $Q$, and adjust $T$ to say that $Q$ is dense/co-dense. Now when you extend a structure by a new element $a$, you can choose whether to set $Q(a)$ or $\lnot Q(a)$, and structures in which you make different choices can't be amalgamated.
But we want JEP. To do this, add an equivalence relation $E$ and say that each equivalence class is a model of the theory described so far. Explicitly, this changes the infinitary sentence to: $$\forall x\, \forall y\,  \left((xEy) \land\bigwedge_{i\in \omega}P_i(x) \leftrightarrow P_i(y)\right)\rightarrow (x = y).$$
Now given two models $A$ and $B$, we can put them together (JEP) by just making everything in $B$ inequivalent to everything in $A$, and there's no need to identify any elements. But AP fails, since we can take two extensions $A$ and $B$ of a model $C$ which both add an element to an existing equivalence class but color it differently by $Q$.

The Amalgamation Property in AECs


Piano Trill Question?

Question: This may be a redundant question but I was not sure how to google or search the answer (when I did I did not get proper results).
On a whole note trill on the piano, how many times do I go back and forth from note to note? I read that it was sixteen. But for example in Chopin's Nocturne in C Sharp Minor, the first trill can be heard going back and forth (for lack of a better word) about 21-23 times.
Also, does the time signature effect how many time you will alternate? The piece is in common time
Answer: Trills can vary in their speed.
They may also be played in or out of the time of the piece, depending on the performer's skill level and intent. In some cases the performer may start the trill slowly, then speed up the trill. In other cases the performer may want the trill to maintain a strict tempo match. There are also some stylistic choices to trilling depending on style and time period of the piece.
Trill speed range can be practiced until the musician has a range of expression available.  A well played slower trill will usually sound better than a badly played fast trill.
Comment: @Dolores Trills are unmeasured. There is no set number of times that you must alternate. You get to choose, depending on your interpretation.
Comment: Well I do know that they vary on speed and skill. My question is that if there is a set number of times one must alternate on a whole note trill or even a half note trill. Maybe I'm thinking about it too much? Does it just depend on how one wants to interpret the song?

Piano Trill Question?


Twists and adjunction formula

Question: Let $\pi:X\to S$ be a morphism of relative dimension one, where $X$ is a regular surface over a regular scheme $S$ of dimension one (everything over $\mathbb C$). We denote by $\omega_\pi$ the relative dualizing sheaf $\omega_X-\pi^\ast \omega_S$. Let $D$ be any divisor in $X$ and $C\subset X$ a nonsingular curve (Edit:) contained in a fiber. I am interested in understanding why $$\omega_\pi(D)|_C\cong \omega_C(D.C).\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,(1)$$
I know that adjunction formula, in this situation, says $\omega_C=\omega_\pi(C)|_C$.
I would start by saying:
$$\omega_\pi(D)|_C\cong \omega_\pi|_C(D.C),$$ but I cannot conclude because I do not know whether the latter is isomorphic to $$\omega_\pi(C)|_C(D.C).$$
If this were true, adjunction formula would give the result $(1)$.

Could you please help me to understand why
  $\omega_\pi|_C(D.C)\cong\omega_\pi(C)|_C(D.C)$?
Comment: Dear Brenin, what is $\omega_\pi$? Is it the top exterior power of $\Omega_{X/S}$?
Comment: I added the definition I am using. Since everything is regular, I believe it agrees with what you said.
Comment: Dear Brenin, I don't understand how your claimed formula can be correct, since the left-hand side depends on $\pi$ but the right-hand side doesn't. Your statement of the adjunction formula is incorrect also: it should say that $\omega_C=\omega_X(C)_{|C}$. Did you mistype, or are you leaving out some hypotheses?
Comment: @AsalBeagDubh: Now that you wrote your comment, I realize I should have added that $C$ is contained in a fiber. In that case, I believe my "strong" adjunction formula does hold (as $(\pi^\ast\omega_S)(C)|_C=0$).
Comment: Dear Brenin: yes, if C is contained in a fibre, then your formula is correct. Please add that hypothesis to the question.
Answer: As written the claimed formula seems to be incorrect. To see this take $D=0$: then the formula would say that $\omega_\pi \vert_C = \omega_C$. But that contradicts what the adjunction formula says in this case, namely $\omega_\pi \vert_C = \omega_C(-C)$.
Suppose $\pi$ has connected fibres. Then the line bundles $\omega_C$ and $\omega_C(-C)$ differ, and hence formula (1) is incorrect, precisely when $C$ is either a component of a reducible fibre of $\pi$ (in which case $C^2<0$) or a multiple fibre of $\pi$ (in which case $O_C(C)$ is torsion but nontrivial in $Pic^0(C)$) – that is, whenever $C$ is not a  whole (scheme-theoretic) fibre of $\pi$.
Comment: So in the case when $C$ is a component of a reducible fiber, does $(1)$ hold or not?
Comment: @Brenin: let me edit my answer to make that point clearer.
Comment: Now I see, thanks for your clarity. I now believe that, instead, one has $\omega_\pi(D)|_C=\omega_C(-C.C+D.C)$.
Comment: @Brenin: yes, that's right, just twisting the adjunction formula by $O_C(D)$.

Twists and adjunction formula


How to make user picture editable without opening edit profile page?

Question: I wanted to allow users to edit profile without going to edit profile page. I found few useful modules like Editable field and Editable fields as link. These modules provide field formatter which make the field editable without leaving the page except the user picture. I am not able to use this technique with user pictures because It is not a normal field as other fields.
How can I make user picture an editable field without going to edit profile page?
Note: I have created a custom profile page using panels. There is a module Picture Changer which allows users to change picture in a modal, but it does not work with panels.
Comment: I guess if there is something which makes/converts the user picture field act as other normal field, will do the trick. But the question is, what? I have found this [post](http://drupal.stackexchange.com/questions/23564/change-user-profile-image-on-profile-page-to-activate-colorbox), but not sure how it can be helpful.
Comment: anybody home?...
Answer: You would have to write your own form where a user can upload the picture and save it as profile picture.
Comment: How would such form look like?
Comment: Hi Bram, your answer is really short. Could you provide an example of such a form?


A chain 64 meters long whose mass is 20 kilograms is hanging over the edge of a tall building...

Question: A chain 64 meters long whose mass is 20 kilograms is hanging over the edge of a tall building and does not touch the ground. How much work is required to lift the top 3 meters of the chain to the top of the building? Use that the acceleration due to gravity is 9.8 meters per second squared. Your answer must include the correct units.
Comment: More appropriate for physics.SE? Anyway a simple difference of potential should give the answer.
Comment: This is a common sort of problem in a calculus course on integral applications, so it doesn't seem out of place to me.
Comment: Is all the 64 meters hanging over? It makes no sense how it is worded. If you list the top 3 meters you are just lifting the end of the chain. Also, are you pulling the entire chain up or just the end up? (they are different problems)
Comment: If the chain is uniform (mass is uniformly distributed), and is at rest at the beginning and the end of the operation, and there is no friction, then a simple computation of the potential energy before and after will do the trick, not forgetting the 3m at the top of the tower at the end.
Comment: The below answer is NOT right. Can anyone else help me?
Answer: Let $x$ denote the position along the chain in meters, with $x=0$ corresponding to the top of the chain at the top of the building. Let $\delta x$ denote a small length of chain. To figure out the total work, we break up the chain into small pieces of equal length $\delta x,$ compute the work to move each piece, and add it all together.
The top piece does not need to be lifted further. A piece at approximately $x$ meters down the chain needs to move $x$ meters if $x\le 3,$ or simply moves $3$ meters if $x\ge 3.$
The work required to lift a piece is $xF$ if $x\le 3,$ or $3F$ otherwise, where $F$ is the force due to gravity. Assuming the chain has constant density, the force acting on a small $\delta x$ of chain is $F=mg=(\frac{20}{64}\delta x)(9.8) = 3.0625 \delta x.$
So to move a small $\delta x$-length of chain takes $3.0625x\delta x$ Joules of work if $0\le x\le 3.$ Summing up the work over these small lengths corresponds to integrating $\int_0^3 3.0625xdx.$
The work required to move the rest of the chain is easier, since all the remaining $\delta x$-lengths move the same distance: $3$ meters. So we can compte this all at once as $3F=3mg=3(\frac{20}{64}61)(9.8)=560.4375$ Joules of work.
Comment: Andrew, your answer is not right. I checked it with the online WebWork my homework is in.
Comment: I haven't computed the final answer yet, I left that for you to do.
Comment: Ryan: Simple correction would suggest to include in your question the indications and/or full answer you received from the online WebWork.


Como alterar web.config ao executar o Deploy?

Question: Tenho um ambiente de homologação e outro de produção na nuvem mas efetuo o Deploy em File System.
Tenho que inserir alguns parâmetros e alterar a connectionString para cada um desses ambientes.
Exemplos de parâmetros:

Informação para saber quando é ambiente de homologação e nesse não enviar e-mails para clientes, somente para as caixas de entrada de teste;
Informar o diretório onde os arquivos deverão ser salvos.

Existe alguma forma de mudar o web.config, acrescentando ou alteração parâmetros dependendo da opção de Deploy que eu escolher?
Answer: Você pode usar o Web.Release.config onde as alterações podem ser feitas no momento da publicação.
No link acima ele tem um exemplo de como funciona, vale uma lida, é bem legal.
Um exemplo pratico dele que eu uso que é para subir um servidor apenas em produção é assim:
  <appSettings>
    <add key="RodaServ" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" value="true"/>

Onde ele muda a key RodaServ para true quando é publicado.
Comment: Vê se o segundo parágrafo do passo 2 no link te atenderia, fiquei meio sem entender o que exatamente você quer fazer, talvez o que ele fala lá ajude.
Comment: Sou péssimo em inglês (aliás, não tenho inglês), mas se essa página estivesse em inglês seria melhor do que essa tradução (rs). Mas segui os passos. Adicionei uma nova ***Solution Configuration*** em ***Solution Manager*** e dei o nome de **Homologacao**. Cliquei com o direito em cima do ***web.Config*** e cliquei em ***Add Config Transform*** e então foi criado o ***web.homologacao.config***. Depois foi só adicionar uma nova configuração de Deploy selecionando essa nova configuração. Adicionei seu exemplo de alteração de parâmetro e funcionou. Muitíssimo obrigado!!
Comment: +1 @Ricardo, obrigado pela dica. Mas para os dois eu preciso efetuar o Deploy em padrão Release.


spline derivation

Question: Assume the following representation for cubic splines with $T$ interior knots is given. Let
$g(Y)=\sum_{j=0}^3 \alpha_j Y_j+\sum_{t=1}^T \gamma_t (Y-\zeta_t)_{+}^{3}$
where $(Y-\zeta_t)_{+}:= max\{0,Y-\zeta_t\}$
1) How can we show that the natural boundary conditions for natural cubic splines results in the following linear constraints on the
coefficients:
$\alpha_2 = 0, \sum_{t=1}^T \gamma_t=0$
$\alpha_3 = 0, \sum_{t=1}^T \zeta_t\gamma_t=0$
2) How can we use result of part (1) to derive the basis
$V_1(Y) = 1, V_2(Y) = Y, V_{t+2}(Y) = g_t(Y) − g_{t-1}(Y), t = \{1, ..., T − 2\}$
where
$g_t(Y)=\frac{(Y-\zeta_t)_{+}^{3}-(Y-\zeta_T)_{+}^{3}}{\zeta_T-\zeta_t}$
Thanks!
Answer: I'm going to prove 1) using a slightly different notation. As for 2) it's my first time seeing people use such a basis, I need some time. Could you give the source where this is from?
A natural spline of degree $2m+1$ is a function $s\in C^{2m}(\mathbb{R})$
that reduces to a polynomial of degree $\leq2m+1$ in each inner interval
and to a polynomial of degree at most $m$ in $(-\infty,t_{1})$ and
$(t_{n},\infty)$.
Theorem Every natural spline can be represented using truncated power functions
as follows
$$
s(x)=\sum_{k=0}^{m}\alpha_{k}x^{k}+\sum_{i=1}^{n}\beta_{i}(x-x_{i})_{+}^{2m+1}
$$
with the coefficient conditions,
$$
\sum_{i=1}^{n}\beta_{i}x_{i}^{k}=0,\qquad k=0,1,\ldots m
$$
The coefficient conditions follow from the natural spline condition,
$$
0=s^{(m+1)}(x)\bigg|_{x\geq x_{n}}=\sum_{i=1}^{n}\beta_{i}(2m+1)(2m)\dots(m+1)(x-x_{i})^{m},
$$
the Binomial Theorem, $(x-x_{i})^{m}=\sum_{k=0}^{m}\binom{m}{k}x_{i}^{m-k}(-x_{i})^{k}$,
and demanding that coefficients for each $k$ of this zero-polynomial vanish.
For cubic spline, $m=1$, note that the front low-degree poly is linear
and the conditions are $\sum\beta_{i}=0$ and $\sum\beta_{i}x_{i}=0$.
Comment: Elements of Statistical Learning written by Tibshirani et al.
Comment: Thanks! And where can I find the proof of this theorem?
Comment: @Star Kincaid D., Cheney W. Numerical analysis, Chapter 6. Could you also share the source of your problem if allowed.
Answer: Since part (1) has been solved, I just answer the part (2). The notation may be a little different.
Based on the definition,
$$f(x)=\beta_0+\beta_1x+\beta_2x^2+\beta_3x^3+\sum\limits_{i=1}^K\theta_i(x-\xi_i)^3_{+}$$
Using the conclusion in (1).
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^K\theta_i(x-\xi_i)^3_{+}$$
Extract the last two elements from the summation
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(x-\xi_i)^3_{+}+\theta_{K-1}(x-\xi_{K-1})_{+}^3+\theta_{K}(x-\xi_{K})_{+}^3$$
Using the results in (1) to solve $\theta_K$ and $\theta_{K-1}$,
$$\theta_K+\theta_{K-1}=-\sum\limits_{i=1}^{K-2}\theta_i=a$$
$$\theta_K\xi_K+\theta_{K-1}\xi_{K-1}=-\sum\limits_{i=1}^{K-2}\theta_i\xi_i=b$$
then
$$\theta_K=\frac{b-a\xi_{K-1}}{\xi_K-\xi_{K-1}}$$
$$\theta_{K-1}=\frac{-b+a\xi_{K}}{\xi_K-\xi_{K-1}}$$
Apply this results to $f(x)$
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(x-\xi_i)^3_{+}+\frac{-b+a\xi_{K}}{\xi_K-\xi_{K-1}}(x-\xi_{K-1})_{+}^3+\frac{b-a\xi_{K-1}}{\xi_K-\xi_{K-1}}(x-\xi_{K})_{+}^3$$
Since $d_{K-1}(X)=\frac{(x-\xi_{K-1})_{+}^3-(x-\xi_{K})_{+}^3}{\xi_K-\xi_{K-1}}$
Using this condition,
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(x-\xi_i)^3_{+}-b\cdot d_{K-1}(X)+\frac{a\xi_{K}}{\xi_K-\xi_{K-1}}(x-\xi_{K-1})_{+}^3+\frac{-a\xi_{K-1}}{\xi_K-\xi_{K-1}}(x-\xi_{K})_{+}^3$$
then
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(x-\xi_i)^3_{+}-b\cdot d_{K-1}(x)+\frac{a\xi_{K}}{\xi_K-\xi_{K-1}}(x-\xi_{K-1})_{+}^3+\frac{-a\xi_{K-1}+a\xi_{K}-a\xi_{K}}{\xi_K-\xi_{K-1}}(x-\xi_{K})_{+}^3$$
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(x-\xi_i)^3_{+}-b\cdot d_{K-1}(x)+a\xi_Kd_{K-1}(x)+a(x-\xi_K)^3_{+}$$
Extract $\theta_i$
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i[(x-\xi_i)^3_{+}-(x-\xi_K)^3_{+}+(\xi_i-\xi_K)d_{K-1}(x)]$$
Extract $(\xi_K-\xi_i)$
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(\xi_K-\xi_i)[\frac{(x-\xi_i)^3_{+}-(x-\xi_K)^3_{+}}{\xi_K-\xi_i}-d_{K-1}(x)]$$
Then get the result,
$$f(x)=\beta_0+\beta_1x+\sum\limits_{i=1}^{K-2}\theta_i(\xi_K-\xi_i)[d_i(x)-d_{K-1}(x)]$$
Done.

spline derivation


Estimating credit card default probabilities

Question: Folks,
I am working on a credit card defaults and transition probabilities. For example a single credit card account could be in a number of states: up-to-date, 30, 60, 90 days in arrears or in default.

Are there packages in R that do estimation of the transition probabilities given historical monthly cohort defaults?
Any pointers to papers specific to this type of estimation?
Simulation of future "paths" of defaults.

Note that transitions occur discretely on a monthly basis.
Thanks much for your time,
KW
Comment: Are you *only* interested in packages for this in R? (Because if so, this question is off-topic for CV; you may want to read our [FAQ](http://stats.stackexchange.com/faq).) Or are you also interested in issues related to predicting probabilities in general? Do you have archival data on cases where there is valid info on your predictors & whether or not they ended up defaulting? Are you mostly interested in the probability of defaulting yes or no (a logistic reg type problem), or the time until default (a survival analysis type problem)?
Comment: I am not only interested in R packages. I am also interested in papers and/or books that might give guidance and/or examples.As I mentioned in my original note there are multiple transition states. I have monthly data for transitions on thousands of accounts.I need to be able to create a model and then simulate future paths of credit-card collateral.
Comment: so you are looking for an HMM?
Comment: Are you particularly interested in discrete states (i.e. multiples of 30s)? It could be more natural modeling continuous default rates e.g. as a Gamma.
Answer: Look at the msm package for R.  It will estimate transition probabilities between different states and you can specify which states it is possible to transition between.  There are probably other tools as well, msm might be overkill for what you are doing (depending on your questions and the level of detail in your data).
Answer: These are "phase type distributions" and great fun!  David Lando goes into a lot of detail in "Credit Risk Modeling: Theory and Applications"Credit Risk Modelling: Theory and Applications.  Lando details how to model these based on the individual transactions rather than the more crude counts at the end of a month. I'm afraid I don't have my copy here.
How you implement will depend a lot on your exact rules for transitions.  What happens for partial payments?


Quick Scroll Bar por ordem alfabética

Question: Eu já encontrei alguns exemplos com uma custom view de uma lista com uma barra de rolagem rápida alfabética, mas eu realmente não encontrei uma barra de rolagem que realmente se pareça com a da lista de contatos do meu kitkat.
Eu não entendo por que isso não é um elemento nativo, já que é usado em qualquer android desde a versão 4.0.
Eu tenho um exemplo usando SectionIndexer para ordenar e dividir por ordem alfabética - que fiz na época para ser como o do iOS - mas é velho e muito feio:

Eu quero um scrollbar como este:

Alguém tem algum exemplo ou dica para me passar?
=========================================================================
UPDATE - RESOLVIDO
Encontrei esse exemplo na página de Developers Android, e no sidebar direito você poder fazer o download do source de um exemplo perfeito!
Segue o link
Comment: Considere a possibilidade de elaborar a solução no campo de respostas, para ajudar outros com o mesmo problema.
Comment: não sabia o que seria melhor, farei então
Answer: XML dentro de um layout:
<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fastScrollEnabled="true"
    android:fastScrollAlwaysVisible="true"
    android:cacheColorHint="@android:color/transparent" />

Activity você precisa de um List de Strings então caso você tenha uma lista complexa deve pegar o item que necessita conforme no exemplo:
public class Activity extends Activity {

ListView list_view;

private List<MeuItem> items;
private List<String> nomes;
private SimpleAdapter indexAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myview);
    items = new ArrayList<MeuItem>();
    nomes = new ArrayList<String>();

    for (Item i : items) {
        nomes.add(i.getNomeQueEuQueroQueApareca());
    }

    Collections.sort(nomes);
    adapter = new SimpleAdapter(this, nomes);
    list_view.setAdapter(adapter);

  }
}

Comment: Isso eh uma lista simples, eu quero uma com divisao alfabetica como a lista de contatos, mas eu já consegui um exemplo. Depois posto aqui
Comment: Uma pena você não ter testado o código que demorei alguns minutos para reescrever.
O que você quer é nativo e o que faz funcionar são as linhas:
        android:fastScrollEnabled="true"
        android:fastScrollAlwaysVisible="true"
Teste e não precisará de nenhuma library.
Comment: Na vdd eu conheço esses atributos, foram inclusive os que eu usei no primeiro exemplo, mas de longe isso resolve oq eu preciso. Tenho q utilizar sectionIndexer e AlphabetIndexer. Mas obrigado mesmo assim
Answer: Encontrei esse exemplo na página de Developers Android, e no sidebar direito você poder fazer o download do source de um exemplo perfeito!

Retrieving a List of Contacts
This lesson shows you how to retrieve a list of contacts whose data matches all or part of a search string, using the following techniques:
Match contact names
Retrieve a list of contacts by matching the search string to all or part of the contact name data. The Contacts Provider allows multiple instances of the same name, so this technique can return a list of matches.
Match a specific type of data, such as a phone number
Retrieve a list of contacts by matching the search string to a particular type of detail data such as an email address. For example, this technique allows you to list all of the contacts whose email address matches the search string.
Match any type of data
Retrieve a list of contacts by matching the search string to any type of detail data, including name, phone number, street address, email address, and so forth. For example, this technique allows you to accept any type of data for a search string and then list the contacts for which the data matches the string.
Note: All the examples in this lesson use a CursorLoader to retrieve data from the Contacts Provider. A CursorLoader runs its query on a thread that's separate from the UI thread. This ensures that the query doesn't slow down UI response times and cause a poor user experience. For more information, see the Android training class Loading Data in the Background.

Quick Scroll Bar por ordem alfabética


How to suppress one specific warning?

Question: I have one specific warning in Drupal 7 from the workbench module which I do not want to display. All other warnings should not be changed.
For now I edit the workbench module by comment the specific line which is not the way it should be solved for final.
I tried to use disables messages wit a specific regex but this is not working. I think because it is a warning and not a message.
I prefer to use hook_page_alter but cannot find the specific warning in the $vars array.
Any suggestion for this or what approach and possibility is there to solve this?
Answer: Solved it in Hook_preprocess_page(&$vars) {
<code>  $all_warnings = $_SESSION['messages']['warning'];
  foreach ($all_warnings as $nr => $messageinfo) {
      if (strpos($messageinfo,"do not have permission to moderate") != false){
        unset ($_SESSION['messages']['warning']);
      }
  }
</code>

How to suppress one specific warning?


Moving/migrating VDO disk to another server

Question: Following…
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/storage_administration_guide/vdo-quick-start
I'm able to setup/configure VDO.
I'm unable to find any documentation for moving the physical disk (created/configured through VDO on a server) to another server.
Basically I used LVM to create volumes on top of VDO disk. Now I have moved the physical disk to another server (which has VDO as a package installed), but it doesn't scans/detects the VDO volume.
Any ideas?
Answer: I was able to resolve this issue by copying the /etc/vdoconf.yml to the other host.


Creating a text file via SSH shell

Question: I am trying to create a BASH shell script that runs through SSH on my shared hosting account to automate the git website control system detailed in:
http://danielmiessler.com/study/git/#website.

So far my bash script is right out of the above article:
cd ~/mydomains; mkdir $name.git;
cd ~/mydomains/$name.git; git init --bare;
/bin/vi ~/domains/$name.git/hooks/post-update

The first 2 lines work as expected.
when I add the third line the script seems to freeze up. the path to vi is /bin/vi in my environment.
Directly from the article I want the to perform the following:
vi /path/website.git/hooks/post-update

then insert:
GIT_WORK_TREE=/path/htdocs git checkout -f

Then close the file.
Could anyone offer me some advice on what to do now?
Comment: Why do you want to use `vi`? Does `echo 'GIT_WORK_TREE=/path/htdocs git checkout -f' >> /path/website.git/hooks/post-update` not suffice?
Comment: Thanks for looking, I'm not experienced with Bash so just following article step by step
Answer: Why are you try to use vi in script just to add line into file?
Problem is that vi is interactive, but you're looking how to automate this ;-)
You should use
echo "GIT_WORK_TREE=/path/htdocs git checkout -f" >> ~/domains/$name.git/hooks/post-update

Comment: -1, this is not an answer to his question, and there is no reason not to use vim.
Comment: What this minus is for? His problem isn't with hook, but with script, which makes this hook!
Comment: Sorry, my bad. I can't undo my vote, but I will if you make a minor edit to your post.
Answer: I believe you need to make the hook script executable before git will use it.
chmod +x /path/website.git/hooks/post-update

After that, after pushing, the script ought to be executed.
Comment: will do, I believe thats the next line in the article, Regards, Bill

Creating a text file via SSH shell


R: Could malicious code be injected into an RDS object?

Question: We have a setup where we allow external users to run analysis tools through a UI. In this interface, some of the tools receive R objects as RDS as inputs. Is this safe or could someone inject malicious code calls (or other exploits) inside a provided RDS? We only use loadRDS and saveRDS, not the more general load and save that deal with the entire workspace.
Answer: Technically speaking, and RDS object is a single object of "anything". and in this function there would be a hidden system call, one you think of a possibility to introduce an exploit. The system() function will execute a command on the console as the user. This could be used to exploit the host system as long as the process running R has the access right doing so.
Example:
<code>x <- function() {
     system("echo EXPLOIT")
}
saveRDS(x, "x.RDS")

y <- readRDS("x.RDS")
y()
</code>
Of course y would needed to be executed in the code after the readRDS.
Let's say that you are reading in an S3 or S4 object with a function stored in the object. When the code would execute this function, the code could be run.
As in many programming languages, the input would need to be checked and checking if the object is of a certain class must be very tight (e.g. if you ask a tibble if it is a data.frame, it will respond TRUE). You might probably extract the values of the read in object and create a new one with the values OR you are really sure that there is no way possible that this is executed.
One could think of more creative exploits when eval is used.
Hope that helps.


Write the following tones in the musical notation

Question: I am currently learning music theory so I found some assignments related to writing down tones in sheet.
However I am a bit confused when it comes to different note names.
For example I have to write down "H" and "h1" note.
Are they the same note, on the same place inside sheet (the third line)?
Also is F sharp 1 between first two lines and F sharp 2 on the fifth line?
And what's the difference between capital D and d note? For example D2 and d.
Comment: H sounds like a German note name, not used all over the world. Where are you? Also, which *stave* are you asking about. We need more info.
Comment: There are several conventions for labelling letter names with which octave they're in. All I can really suggest is that you find the textbook or worksheet where the convention YOUR course uses is described.
Comment: @Tim it is evidently the treble clef.
Comment: "I found some assignments" Where? What sources? Your post seems to combine both Scientific notation octave numbers with Helmholtz letter case, also is the source using German `H` for pitch `B`? Are you mixing together assignments from various sources?
Answer: There are two frequently used systems

Scientific notation: https://en.wikipedia.org/wiki/Scientific_pitch_notation
Helmholtz notation: https://en.wikipedia.org/wiki/Helmholtz_pitch_notation

In both of them the octave starts with C note, and all notes with higher pitch belong to the same octave, up to the next C.
However the octave numbering differs between the two notations.

In Scientific notation middle C (the note on the first added line below the staff in violin key) is called C₄. The octave above is C₅, next is C₆ and so on. Similarly the octaves below use descending numbers: C₃, C₂, C₁...
In Helmholtz notation middle C is called c' (called: one-line C), the one octave above is c'' (two-line C), another octave up is c''' (three-line C) and so on. C one octave below  middle C is c (small C, small letter), then one octave below is C (Great C, capital letter), and then octaves below are C, (C contra) C,, (C sub-contra), C,,, (C sub-sub-contra)... Sometimes the , and ' marks are replaced with lines drawn above the letter, there are also other variations, e.g. c¹ might be used instead of c', which is perhaps what happens in your score?

The literature often leaves it up to the reader to find out which of the notation system is being used.
Since you mention H note, please also be aware of another conflict: H in German notation corresponds to B in English notation, and B in German notation is B♭ (B-flat) in English notation.
Comment: @MichaelCurtis yes, though a superscript should be used to distinguish `c¹` (which is `c'`) from `C₁` (which is `C,`). But I can believe some people may omit superscripts as well...
Comment: But the OP's example use letter case and numbers, so it looks like a jumble of Scientific and Helmholtz.
Comment: @MichaelCurtis As I wrote, sometimes numbers are also used in Helmholtz notation, making you having to guess.
Comment: So, `C4` scientific would be `c'` or `C1` Helmholtz?
Comment: Helmholtz notation is derived from the Guidonian gamut, although that system counts octaves starting from A and uses double small letters instead of `'` for the high octave and Greek letters instead of `,` for the low octave (but its compass is so limited that there is only one note in the low octave, `Γ`).  Until I realized that, I could never keep straight which octave was which in Helmholtz notation.


Understanding integrals with spherical coordinates

Question:
Hi! I am studying for an exam and working on understanding spherical coordinate integrals. For the integral below there is a cone and a sphere. I saw a solution to this problem which involved translating to spherical coordinates to get a triple integral. The integral solved was(p^2)*sin(phi). How does one go about obtaining this? I understand how to calculate the bounds. Thanks!
Answer: $\rho^2\sin\phi$ is the "fudge factor" in spherical coordinates; i.e., $dV = \rho^2\sin\phi\,d\rho\,d\phi\,d\theta$.
Answer: the Jacobian.
$dx \ dy \ dz = \left|\det\begin{bmatrix} \frac {\partial x}{\partial \rho} &\frac {\partial x}{\partial \theta}&\frac {\partial x}{\partial \phi}\\
\frac {\partial y}{\partial \rho} &\frac {\partial y}{\partial \theta}&\frac {\partial y}{\partial \phi}\\
\frac {\partial z}{\partial \rho} &\frac {\partial z}{\partial \theta}&\frac {\partial z}{\partial \phi}\end{bmatrix}\right| \ d\rho\ d\phi \ d\theta = \rho^2\sin\phi \ d\rho\ d\phi \ d\theta$
What does it mean?  Starting at some $(\rho, \phi, \theta)$, nudge each of the variables.  $(\rho + d\rho,\phi, \theta), (\rho,\phi+d\phi, \theta)$, etc.  Nudging each of these, creates a "box" of some volume.  What is the volume?


How can I post a link to Facebook without thumbnail preview?

Question: I am trying to post on Facebook without thumbnail, but even if I set $link_img to null Facebook takes the default image.
$facebookReturn = $fb->add_post
                     ->set_message($message)
                     ->set_link_uri($link_url)
                     ->set_link_name($link_title)
                     ->set_link_description($link_desc)
                     ->set_picture_uri($link_img)
                     ->publish;

How can I tell Facebook not to post the thumbnail?
I am using Facebook's Perl API.
Comment: possible duplicate of [How do I post a Link to Facebook without a thumbnail?](http://stackoverflow.com/questions/4246170/how-do-i-post-a-link-to-facebook-without-a-thumbnail)
Answer: If you're creating a post containing an image, Facebook will display a thumbnail. This is just how Facebook currently works.
There is no way to change or alter Facebook's behavior with regard to how they display posts containing images.
If you don't want a thumbnail, then you shouldn't post an image with the post. Just have the link. That being said, with only a link, Facebook will attempt to extract a thumbnail image from the provided link - so you might have to deal with that as well.


Add or extend Vuex action types using Typescript

Question: I'm somewhat new to Typescript. I'm trying to add specific type structure to every single Actions I declare in Vue store without repeating them in every single Vuex module files.
For example, I can do this in every action in every store files like below:
// This will be declared as global interface.
interface ReturnObject {
   status: boolean;
   msg: string;
}

export default new Vuex.Store({
   actions: {
      // I'd need to write every single action this way..
      exampleAction: async (context, payload): Promise<ReturnObject> => {
         return { status: true, msg: 'Hello World!' }
      },
   },
   modules: {
      // Appling to all module file's actions as well.
   }
})

But I want to do this:
export default new Vuex.Store({
   actions: {
      // Types are automatically applied.
      async exampleAction(context, payload) {
         return {status: true, msg: 'Hello World!'}
      }
   },
   modules: {
      // Appling to all module file's actions as well.
   }
})

Comment: I don't understand the problem. Do you want every action to return `ReturnObject`?
Comment: @caTS I wanted all actions to return in specific structure.
Comment: Which types? Return type? Actions can't return anything but `Promise`
Comment: @EstusFlask I want to set return type to maybe `Promise` or in my case `Promise` as indicated above.
Comment: You can't. Check how Vuex works. Actions don't return data
Comment: @EstusFlask ..? What do you mean..? I always return values in actions.. [Check this](https://vuex.vuejs.org/guide/actions.html#composing-actions)
Comment: It's already stated above, it's `Promise`. You can return a promise of `undefined`, not arbitrary value like you're trying. You can notice that in examples it's `dispatch('actionA').then(() =>` You can't read a value from an action in `then`
Comment: @EstusFlask No you are wrong. Using `async await` you are able wait for the return value after triggering dispatch. Even in Vue typescript the action's return type is `any`.
Comment: Yes, I stand corrected, I remember it was possible at some point, not sure if it still is. Any way, this is not a common use for a store. Actions are primarily needed to operate on a state, not return a result. I don't think it's possible without modifying Vuex typings globally, which is a bad thing. You can always use your own helper like createActions that will do any modifications to action functions - either type or runtime
Comment: @EstusFlask I definitely don't want to touch `node_modules` folder at all. I just want to find a way to declare global type for Vue actions. The reason why I'm posting this question is because I'm lacking on TypeScript so I might be missing a way to fully utilize it with Vue. I understand about JS and Vue well so those are not the issues for me.
Comment: This isn't about modifying source files, it's about extending types like that, https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation . Can't say how it will be in case of Vuex. I meant that modifying original global behaviour for local purposes is universally a bad practice, not only in TS. I'd definitely use custom helpers like createStore or createActions that enforce types for `actions`.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248814/discussion-between-passionatelearner-and-estus-flask).
Comment: @EstusFlask So can you post an answer on those? Would like to see example code.
Comment: I posted an example. Cannot confirm if it works but I'd expect it to.
Answer: Modifying original global behaviour for local purposes is universally a bad practice.  A possible solution is to use custom helpers to extend it instead of modifying it. In this case it's a simple wrapper that extends original store types:
type CustomActionHandler<S, R> = (this: Store<R>, injectee: ActionContext<S, R>, payload?: any) => ReturnObject | Promise<ReturnObject>;

interface CustomActionTree<S, R> {
  [key: string]: CustomActionHandler;
}

interface CustomModule<S, R> extends Module<S, R> {
  actions?: CustomActionTree<S, R>;
}

export interface CustomModuleTree<R> {
  [key: string]: CustomModule<any, R>;
}

interface CustomStoreOptions<S> extends StoreOptions<S> {
  actions?: CustomActionTree<S, S>;
  modules?: CustomModuleTree<S>;
}

function createCustomStore<S>(options: CustomStoreOptions<S>) {
  return new Store(options);
}


Develop in python on Linux, test on Windows

Question: I'm trying to develop a cross-platform library and want to be able to develop code and then quickly test it on both Windows and Linux. I'm not sure if it's even an option or worthwhile testing under Wine (it uses the multiprocessing module, and COM on Windows) but I do have a VM I've been running it under. It's just been cumbersome getting the code copied over to the Windows machine running on a remote server using the Windows GUI (which is slow enough over the network as it is) after every change, then bringing up the command prompt and running the tests, then troubleshooting on Windows and getting the fixes back to the development environment.
Is there any way I can remove some steps from the testing process?
Answer: Using a DVCS to push the local changes to the server will take you far. You will need a SSH server on the Windows machine, but there are several of those around. You can also use a makefile to direct the pushing and testing, possibly even running the tests remotely depending on what they consist of.
Answer: Windows does have the Server Core variant which provides a command shell without the "GUI" ( http://www.microsoft.com/windowsserver2008/en/us/r2-compare-core-installation.aspx )
I would say you also automate the process. Have a personal (?) build server, have powershell scripts or chef recipes ( http://www.opscode.com/blog/2011/05/24/chef-hearts-windows/ ). Push the changes ( ideally Git), have the build server pick it up, spin up the VM if needed, do the stuff, get the result
Answer: Whatever happens, if you're developing for multiple platforms you're going to have to copy from whichever you're developing on to the secondary platform(s), build it and instigate your tests.
Your best bet is to automate as much of it as possible (for both environments) and make a build bot which watches for new code on a central repository (you are using version control aren't you?).
If the Windows version is giving you most hassle then why not develop on Windows and set up the build bot on your linux machine?


parsing json string to angular object from http get

Question: I want to parsing this response from http get and display the value into a detail modal but I dont know how to parse it. I have using arc to show me the response of my http get,here is my image of my response using arc.

here is my.js file
$http.get('.....a='+$scope.month).then(function(response){
        $scope.coba = response.data;

Comment: First, there is no "angular object", angular is a framework and uses javascript objects, in response.data you have a javascript object, you don't need to parse anything
Answer: Use JSON.stringify(response.data) or angular.toJson(response.data), it will parse the http response into JSON.
If it is failing, means your response is not exact JSON


Use the well ordering principle to show that each nonempty set S consisting of negative integers has a largest element.

Question: I have question

Q
  Use the well ordering principle to show that each nonempty set S consisting of negative integers has a largest element.

I hope someone can answer
Thanks
please explain more not clear this answer
Answer: Hint: Let $T$ be the set of all numbers $-s$, where $s$ ranges over $S$. Then $T$ is a non-empty set of positive integers, so has a smallest element.
Note that $x\le y$ if and only if $-y\le -x$.


Como fazer a detecção automática de um Captive Portal

Question: Eu estou fazendo um hotspot em um servidor com CentOS 6 e gostaria de fazer com que os celulares (android e iOS) reconhecessem automaticamente que precisam de autenticação assim que conectar na rede, para redirecionarem ao login.
No meu firewall eu tenho a regra:
iptables -t nat -A NET_DHCP -i eth1 -s 172.16.0.0/16 -p tcp --dport 80 -j DNAT --to 172.16.0.1:80

No apache (httpd.conf):
<VirtualHost *:80>
        ErrorDocument 400 /var/www/dhcpauth/index.php
        ErrorDocument 404 /var/www/dhcpauth/index.php
        ServerPath /var/www/dhcpauth
        DocumentRoot /var/www/dhcpauth/
        <Directory /var/www/dhcpauth>
            AllowOverride All
            DirectoryIndex index.html index.html
            Options Indexes FollowSymLinks
            Order allow,deny
            Allow from all
        </Directory>
</VirtualHost>

Em outras respostas à perguntas similares eu encontrei o seguinte código, mas não funcionou da forma que usei:

O hostpot (login e liberação de acesso) funciona normalmente quando acessamos a página de login diretamente pelo dns ou ip, mas eu precisava que aparecesse aquela mensagem "Essa rede precisa de autenticação". Alguém tem ideia de como posso fazer isso?
Answer: Até onde sei os SO's (Android, IOS, Windows, etc), possuem mecanismos que verificam se um determinado acesso está sendo redirecionado para um IP que não deveria, caso isso for verdade o SO apresenta um alerta recomendando Login na Rede, eu fiz isso em FreeBSD utilizando Packet Filter(pf), mas a lógica deve ser a mesma com iptables
rdr  on {$int_wireless} inet proto {tcp} from !<logados> to any port 443 -> 192.168.99.1 port 443
rdr  on {$int_wireless} inet proto {tcp} from !<logados> to any port 80 -> 192.168.99.1 port 80

Quando um equipamento ganha IP via DHCP na rede Wifi as duas regras acima entram em ação, se o IP não estiver cadastrado na tabela logados ele redireciona qualquer tentativa de acesso para qualquer IP/Endereço do planeta para a minha página de Login (192.168.99.1), quando o cliente se Loga na rede etas duas regras se tornam inválida para o cliente logado, portando estas duas regras são as responsáveis para que os SO's sejam capazes de mostrar uma mensagem de Login.
Comment: É apenas o redirecionamento? Por que eu fiz isso já é aparentemente tinha funcionado, por que quando do celular eu tentava abrir uma página qualquer no chorme ela era redirecionada para a página de login. Só que a mensagem em si nunca apareceu. Eu vou tentar novamente convertendo essas regras que você pôs para iptables. Obrigado
Comment: Sim é o firewall redirecionando tudo para porta 443 e 80 que faz com que a mensagem de login aparece no SO, o apache não tem nada haver com a história
Comment: Eu testei exatamente como você mencionou:
```iptables -t nat -I PREROUTING_DHCP -p tcp --dport 80 -j REDIRECT --to-port 80```
```iptables -t nat -I PREROUTING_DHCP -p tcp --dport 443 -j REDIRECT --to-port 443```
Só que em vez de aparecer que a rede precisa de login. Aparece a mesagem que a rede parece estar indisponível. Embora o redirect tenha funcionado por que quando tento abrir uma página no navegar ele redireciona para a pagina de login.
Comment: Todo o resto está bloqueado correto? não pode ter nenhuma outra porta de saída aberta no firewall, tudo na rede wifi deve estar em block, só deve estar liberado o ip do seu apache e o redirecionamento da porta 80 e 443
Comment: Está sim, A politica padrão do meu firewall é DROP. Mesmo assim por garantia agora eu inclui um DROP no FORWARD para a rede do wifi. O único ACCEPT que tem é para o próprio servidor onde está o apache
Comment: Os clientes que se conectam no Wifi, estão se conectando em AP's ou Routers ? eu acho que só funciona direito em AP's...
Comment: Eu consegui resolver mas tem a ver com o Apache sim. Para resolução eu precisei por um redirect do apache com o código 302 para a tela de login. Apenas esse redirect indica aos aparelhos que é preciso fazer login. Mas obrigado pela ajuda