RAID-5 or RAID-10 recommended for Autonomy IDOL Indexes?

Question: I'm well aware of the widespread recommendation that any disk system that is holding a database should not be RAID-5 because of the poor write performance on RAID-5.  You can look at BAARF's website to see the arguments over RAID-5 and the problems with it for databases.
I'm building an IDOL indexing server - our first - and I was wondering if people who have experience with IDOL know what the read/write balance is.  RAID-5 is faster for read-heavy systems; RAID-10 for write-heavy systems (if more than about 5-10% of your disk accesses are writes, you're better off with RAID-10).  I would expect that IDOL does enough writes to justify RAID-10, but I don't actually know and I was hoping someone else here does.
... so the question is: Is an IDOL indexing server likely to perform enough writes to justify RAID-10 over RAID-5?
Answer: I do not know about IDOL specifically, but during day to day operations I would not expect an indexing service to generate many write requests unless the content being indexed changes a lot regularly.
The initial indexing of blocks of new content will produce a lot of writing though, as will any re-index operations that are started for any reason. For either of these operations you will notice a significant performance difference between RAID10 and RAID5/6.
The other operation that will produce write is logging, but is is only going to be an issue if the service is configured to record copious amounts of information as the index is accessed and if that is the case then you are likely to have your logs on another volume anyway.
Comment: There will be about 20,000 new files being indexed per day - the initial load is about 10,000,000, just to give you a sense of the system scale.
Answer: RAID-10 is the preferred option in most circumstances, particularly if you are using large disks.
RAID-5/6 leaves you:

More vulnerable to data loss in certain circumstances
A long period of compromised performance in the event of disk failure
Less redundancy than RAID-10
Significantly more free disk space than RAID-10
Less architectural flexibility than RAID-10

Additionally, RAID-5 is not faster RAID-10 for most read purposes.
Edit: Changed marginally more disk space to significantly more disk space.
Comment: Marginally more free disk space than RAID10? That is not correct at all, except two-disk RAID1 (not 10) vs 3disk RAID5.
Comment: Actually RAID-6 is more reliable than RAID-10. You can lose any 2 drives, while RAID-10 allows you to lose one drive for each pair. Unfortunately rebuilding a drive stresses the remaining member and is particularly dangerous in RAID-10, while rebuilding a failed drive in a RAID-6 stresses equally all remaining drives and keep you protected in case of a second failure.
Comment: RAID-5 will have more free disk than RAID-10.  If you have, say, eight disks, then your useable space is 4*disk size in RAID-10, but 7*disk size in RAID-5.
Comment: RAID is not backup. The whole point to is to provide redundancy and keep the service up. Rebuilding a mirror is just moving blocks around -- a much quicker option than does not completely compromise your application. I don't worry about stress out disks, I worry about stressed out users. A long-duration outage for a RAID-6 rebuild is going to stress them out.
Answer: I agree with the other posters about the particular details around RAID 5/6/10 and such so I won't add much on those points. But you didn't specify what kind of hardware was being used, so I remind you that using a solid hardware RAID controller should also be kept in mind.
I've done software RAID before and after several failures, I've sworn them off. After using hardware RAID (such as Adaptec and 3Ware), the difference is substantial. Not only do they perform better then software RAID but I have yet to run into a failure with any disks. I'm not saying it will never happen, but hardware while being more costly will definitely help you with performance and availability. Don't neglect the RAID controller!
Comment: Good advice - I'm going to use a DELL PERC controller, which I think is a rebadged LSI MegaRAID card.
Answer: Many setups include two arrays; one RAID-5 for data and one RAID-1 (or 10) for logs. I've never worked with any database wich required RAID10 for data storage, but maybe others have..
Comment: Using RAID 10 here for the storage. Logs are not important - sorry. Logs are continous write, a LOT less stress than what goes on on my data.


Relation between the braid group and the mapping class group of the plane

Question: According to the following link, page 248, the braid group modulo its center is isomorphic to the mapping class group of the $N$-times punctured plane, i.e. $B_N/Z(B_N)\cong M_N(\mathcal(R)^2)$. Could anybody explain to me, how it is related to the mapping class group of the punctured $2$-sphere, please?
Answer: The key theorem is the following.

The braid group $B_n$ is isomorphic to the mapping class group
  $$
M_n(D^2) \;=\; \mathrm{MCG}\bigl(D^2 - \{p_1,\ldots,p_n\},\partial D^2\bigr)
$$
  of a disk with $n$ punctures rel the boundary.

Here "rel the boundary" means that all homeomorphisms and isotopies must fix the boundary of the disk pointwise.
The idea of this theorem is that a homeomorphism of the disk "moves" the $n$ punctures, and you can keep track of this motion using a braid.
More precisely, given a homeomorphism $h$ of $D^2 - \{p_1,\ldots,p_n\}$ that fixes $\partial D^2$ pointwise, we can extend $h$ to all of $D^2$ by filling in the punctures.  Now, every homeomorphism of $D^2$ that fixes $\partial D^2$ pointwise is isotopic rel $\partial D^2$  to the identity.  Therefore, there exists some isotopy $h_t\,$ rel $\partial D^2$ for which $h_0$ is the identity map on $D^2$ and $h_1=h$.  Then each puncture $p_i$ follows a path $h_t(p_i)$ under this isotopy, and the union of the graphs
$$
\bigcup_{i=1}^n \{(h_t(p_i),t) \mid t\in[0,1]\}
$$
is a braid embedded in the solid cylinder $D^2 \times [0,1]$.
In more concrete terms, the mapping class group $M_n(D^2)$ is generated by half Dehn twists around pairs $\{p_i,p_{i+1}\}$ of punctures, and these correspond to half-twists of adjacent pairs of strands in the braid group.
In any case, the theorem about a punctured sphere is the following.

Let $M$ be the mapping class group of an $(n+1)$-punctured sphere.  Let $p$ be one of the punctures, and let $M_p$ be the subgroup of $M$ consisting of mapping classes that fix $p$.  Then $M_p$ is isomorphic to $B_n / Z(B_n)$, where $Z(B_n)$ is the center of $B_n$.

Before explaining this theorem, I should mention that the center $Z(B_n)$ of $B_n$ is infinite cyclic, and is generated by a full $360^\circ$ twist of the $n$ strands.  As an element of $M_n(D^2)$, this corresponds to a Dehn twist around a curve that lies close to the boundary of the disk.
Now, there is an obvious homomorphism $M_n(D^2) \to M_p$, obtained by mapping the boundary of the disk to a small circle around the puncture $p$.  Since $M_n(D^2)$ is isomorphic to $B_n$, this gives a homomorphism $B_n \to M_p$.  Now, it should not be too hard to see that:

This homomorphism is onto, and
The center $Z(B_n)$ lies in the kernel of this homomorphism.

The explanation for (2) is that the generator for the center is mapping to a Dehn twist along a small circle surrounding $p$, which is clearly isotopic to the identity.
It should also make sense intuitively that $Z(B_n)$ would be the entire kernel of this homeomorphism, and thus $M_p$ is isomorphic to $B_n / Z(B_n)$.
Comment: Thank you Jim! Just one tiny additional question: The braid group that you use here is the one defined one the plane/disc, right? I ask, since there is also the spherical braid group and $M_N(S^2)\cong B_N(S^2)/\mathbb(Z)_2$.
Comment: Right.  I'm using $B_n$ to mean the usual braid group on $n$ strands, i.e. the fundamental group of the configuration space of $n$ unlabeled points in the plane.
Comment: Jim, could you also comment on the relation of all that to the mcg of the plane? How do I use Birman's exact sequence here? Thank you!
Comment: I came across this answer from a Google search, and found it to be very helpful. Just one quick question: you say that the center of $Z(B_n)$ is generated by a full twist of the $n$ strands,  which is also the Dehn twist about a curve that lies close to the boundary the disk. What curve satisfies the property that the Dehn twist about it is the half twist of the $n$ strands?
Comment: @user8253417 The half twist of the $n$ strands is not a Dehn twist around any curve.
Comment: Thank you for your answer! I think I understand, but I just wanted to check one more think with you to make sure I have corrected my misunderstanding. Would the Dehn twist about a curve that goes around the boundary twice be the square of the generator of $Z(B_n)$?
Comment: @user8253417 You can't do a Dehn twist around a curve that isn't simple, so it isn't possible to do a Dehn twist around a curve that "goes around the boundary twice".
Comment: Is the square of the generator of $Z(B_n)$ the Dehn twist about any curve?
Comment: @user8253417 No, it isn't.  Perhaps you should post a new question about Dehn twists?


how to insert an array in another one?

Question: This is an index (of module services) I created a resource that index books on a home page of a mobile app( this is not the most important in my question) I want to get books that have same tid (from table taxonomy) and put them on an array ($livres) at this time when I return $livres it's ok, books are grouped well and no duplications, but after putting them on array $livres, i want to put the $livres on the array $sections, sections contain the "header" that is the name of the section, and the array $livres of every section : the result i want is : [ { 'section' : 'A', 'livres':[{'id_book' : '1','title':'great book'},{'id_book' : '2','title':'great book too'}]},{'section':'B','livres':[{...ect
function my_module_home_index(){
$sections = array();
$livres = array();

$home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

foreach($home_livre as $book){
    if(!isset($livres[$book-> tid]))
    $livres[$book-> tid] = array();

    $livres[$book->tid][]= array(
        'id_livre'=>$book-> entity_id,
        'titre' => $book-> titre,
        'prix'=> $book-> prix
    );
    $sections[]= array(
        'categorie'=> $book-> section
        'livre'=> $livres[$book->tid]
    );
}
return $sections;
  }

This is a part of what postman returns :
{
"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  }
]
  },
{
  "categorie": "A",
  "livre": [
    {
     "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  }
 ]
},
{

"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  },
  {
    "id_livre": "111",
    "titre": "H",
    "prix": "6"
  }
  ]
 },

As you can see; Book number 109 appears every iteration of foreach, how to avoid that ?
This is what return $livres shows (just a part, whent tid : 41, array is grouping all books with this tid so it's ok):
"41": [
{
  "id_livre": "109",
  "titre": "F",
  "prix": "4"
},
{
  "id_livre": "110",
  "titre": "G",
  "prix": "43"
},
{
  "id_livre": "111",
  "titre": "H",
  "prix": "6"
},
{
  "id_livre": "115",
  "titre": "L",
  "prix": "4"
},
{
  "id_livre": "118",
  "titre": "O",
  "prix": "5"
}
  ]
  }

Thank you
EDIT : this is the result postman returns when i "range" the query with 0,5 : i want 5 books (livres) in every sections, did anyone knows how to range the first array (not the second one that contains livres)
"response": [
{
  "section": "roman policier",
  "id_section": "31",
  "livres": [
    {
      "couverture": "http://localhost/drupal/sites/default/files/Etude_en_rouge.jpg",
      "id_livre": "113",
      "titre": "Une étude en rouge",
      "auteur": "Arthur Conan Doyle",
      "prix": "8",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/fables.jpg",
      "id_livre": "119",
      "titre": "Fables",
      "auteur": "Jean de La Fontaine",
      "prix": "0",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/couverture-livre_2.png",
      "id_livre": "120",
      "titre": "lire_latin",
      "auteur": "ecri_latin",
      "prix": "33",
      "categorie": "30",
      "section": "31"
    }
  ]
},
{
  "section": "roman drole",
  "id_section": "32",
  "livres": [
    {
      "couverture": "",
      "id_livre": "114",
      "titre": null,
      "auteur": null,
      "prix": "444",
      "categorie": "30",
      "section": "32"
    }
  ]
}

Answer: You could try this:
function my_module_home_index(){
  $sections = array();

  $home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

  foreach($home_livre as $book){
    if (!isset($sections[$book->section])) {
      $sections[$book->section] = array(
        'categorie' => $book->section,
      );
    }

    $sections[$book->section]['livre'][] = array(
      'id_livre' => $book->entity_id,
      'titre' => $book->titre,
      'prix' => $book->prix,
    );
  }

  // The above will set up $sections as an associative array, but you need
  // to return an indexed array, so run it though array_values()
  return array_values($sections);
}

Basically, The first book that comes along with category "A" will create a new child the in $sections array with a key of "A". The book will then be nested in that child. If another book is found with category "A" then instead of creating a new category child, the book is nested inside of the same "A" category.
Note that I've not tested this code live so might need some tweaking
Comment: Hi Paul, Great answer it works Thank you very much
Comment: Hi Paul, i'm facing a new "issue" with this same query, now i have a query that returns an array into another one, imagine i want to range result between 0 and 10 (i used db_query_range) and when i add 0,10 i want every section contains 10 books (livre) but now in my result i've got : 10 books for ALL of the sections (see what i've edited in my question please paul)
Comment: I think you'll have trouble doing this with a single query, unless you don't limit the number of results at all in the query and limit them in PHP in your loop, but if the data set gets large then that would have significant performance implications.  There are some approaches you could try at http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ but I think I'd recommend having two queries; In the first you'd get the sections and loop through the results. For each section run a separate query to get the books (with the limit clause).
Comment: Yes Paul it's more logical to make two queries that's right, i'm working on it. Thank you

how to insert an array in another one?


Natural Cubic Spline Problem - what do I do next?

Question: Related to this similar problem.
I am attempting to solve the following:

Find a natural cubic spline function whose knots are $-1$, $0$, and $1$ and that takes on the values $S(-1)=5$, $S(0)=7$, and $S(1)=9$.

Neither my textbook nor my class notes have been particularly helpful in showing me how to work out a cubic spline problem like this. What I have seen thus far has been very theoretical, and I have not been able to find a completely worked out problem, so after I get the equations set up, I do not know how to proceed. I know it's supposed to involve a matrix, but I don't know how to set it up.
This is what I have done so far (I have tried to model what I did off of the similar problem I referenced earlier):

Suppose the natural cubic spline function has the form $S(x) = \begin{cases} S_{1}(x),& x \in (-\infty,-1] \\
S_{2}(x),& x \in [-1,0]\\
S_{3}(x),& x \in [0,1]\\
S_{4}(x),& x \in [1,\infty).
\end{cases}$
Then, in order to meet the necessary conditions for it to be a natural cubic spline, we need to have

$S_{1}(-1)=S_{2}(-1) = 5$
$S_{1}^{\prime}(-1)=S_{2}^{\prime}(-1)$
$S_{1}^{\prime\prime}(-1)=S_{2}^{\prime\prime}(-1) = 0$ (the $=0$ is the "natural" condition)
$S_{2}(0)=S_{3}(0) = 7$
$S_{2}^{\prime}(0)=S_{3}^{\prime}(0)$
$S_{2}^{\prime\prime}(0)=S_{3}^{\prime\prime}(0)$
$S_{3}(1)=S_{4}(1) = 9$
$S_{3}^{\prime}(1)=S_{4}^{\prime}(1)$
$S_{3}^{\prime\prime}(1)=S_{4}^{\prime\prime}(1) = 0$ (the $=0$ is the "natural condition)

Now, from here, I formed the $S_{i}(x)=a_{i}x^{3}+b_{i}x^{2}+c_{i}x+d_{i}$, the $S_{i}^{\prime}(x)=3a_{i}x^{2}+2b_{i}x+c_{i}$, and $S_{i}^{\prime\prime}(x)=6a_{i}x+2b_{i}$ for $i = 1,2,3,4$.
Plugging in some conditions, I found that $d_{2}=7$ and $d_{3}=7$. Also, I ended up with $c_{2}=c_{3}$, and a couple more not terribly interesting things.

At this point, I do not know how to proceed. I know I have to form a matrix, but in terms of the parameters I have here, I don't know what that matrix is supposed to look like or how big it is supposed to be.
Would somebody please tell me what to do next? And please don't ask me what I know about this or that, because honestly, I don't know anything. I'm extremely lost and frustrated to the point of tears.
Comment: Wikipedia gives you the complete resolution for the three knots case. https://en.wikipedia.org/wiki/Spline_interpolation#Example
Answer: I think you can just forget about your $S_1(x)$ and $S_4(x)$. We only care about what's happening on the interval $[-1,1]$, so we only need your $S_2(x)$ and $S_3(x)$.
You have 8 unknowns -- your $a_i$, $b_i$, $c_i$, $d_i$ for $i=2,3$.
Now we do what you did -- we start writing down equations that express the desired continuity and interpolation properties of the spline. First the interpolation requirements:
\begin{align}
S_2(-1) = 5 \quad & \Longrightarrow  \quad -a_2 + b_2 - c_2 + d_2 = 5 \\
S_2(0) = 7  \quad & \Longrightarrow  \quad d_2 = 7 \\
S_3(0) = 7  \quad & \Longrightarrow  \quad d_3 = 7 \\
S_3(1) = 9 \quad & \Longrightarrow  \quad a_3 + b_3 + c_3 + d_3 = 9
\end{align}
Then the requirement that the two segments join with $C_2$ continuity at $x=0$:
\begin{align}
S_2'(0) = S_3'(0)  \quad & \Longrightarrow  \quad c_2 = c_3 \\
S_2''(0) = S_3''(0)  \quad & \Longrightarrow  \quad b_2 = b_3
\end{align}
And finally the "natural" end conditions:
\begin{align}
S_2''(-1) = 0  \quad & \Longrightarrow  \quad -6a_2 +2b_2 = 0 \\
S_3''(1) = 0  \quad & \Longrightarrow  \quad 6a_3 +2b_3 = 0
\end{align}
Notice that there are 8 of these equations. The equations are linear, so you should be able to solve them to get the 8 unknowns $a_2$, $b_2$, $c_2$, $d_2$, $a_3$, $b_3$, $c_3$, $d_3$.
You can write the equations in matrix form, using an $8 \times 8$ matrix, but this really isn't necessary, and it probably won't help you solve them. Just solve the equations however you want. High-school Gaussian elimination will work just fine, for example.
The approach you were taking would work, too, but you'd end up with 16 equations and 16 unknowns, which makes everything a lot more laborious.
Comment: If you have trouble solving the equations, just ask again. But this is nothing to do with spline theory, really; it's just algebra.


Select field label for a value

Question: is there a way to get the label of a value from a select field?
I mean that if my select field has options like:
key1|label1
Key2|label2
how can I get label1 in my node--*.tpl.php?
Thanks.
Answer: You can use list_allowed_values().
<code>$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);
</code>
For reference field_info_field()

Select field label for a value


How to remove an item from ArrayList>

Question: I'm using an ArrayList<HashMap<String, Object>> to store items in. I know how to add an item to this list, but I don't know how to remove one. I've tried many things, such as list.remove(position); but nothing was working. I've searched on Google and read tons of similar questions which didn't help me at all.
My question is: How to remove an item from the list?
My list:
[
    { title=MyFirstElement, comments=First element of my list },
    { title=ASecondOne, comments=Two elements },
    { title=Third, comments=Never two without three }
]

Comment: The error you had concerns JSON, not really what you explained in your question. Putting that aside, just removing form a list is as easy as what you tried, list.remove(index).
You may have a JSON parsing problem somewhere else, misleading you.
Comment: Do you mean how to remove a special `Map.Entry`? How do you want to remove it, by key or by value? What's given?
Comment: I'd like to remove the whole first element using the position.
Comment: *I've tried many things, such as `list.remove(position);` but nothing was working*, what wasn't really working? How did you infer that? Do explain.
Comment: I've tried to do `list.remove(position);` when clicking on the item of my ListView. I get the position of the element in my listview and then use it in `list.remove(position);` and was getting an error "Expected BEGIN_ARRAY but was BEGIN_OBJECT"
Comment: You can create a custom model class including the title and comments and then use `list.remove(position)` if you are willing to do it without using the hashmap.
Answer: Could you please post the complete stacktrace. The eror you have mentioned is not relate to what you think. Its something relates to Json.
In general,

list.remove(index)

should work in your case.

How to remove an item from ArrayList>


Is the MSE of a vector a scalar or a matrix?

Question: Suppose $Y = X\beta + \epsilon,$ where $Y$ is $n \times 1$, $X$ is $n \times p$, and $\beta$ is $p \times 1$, and $\epsilon$ is $n \times 1$ with mean 0 and variance $\sigma^2$. The OLS estimator of $\beta$ is $\hat{\beta} = (X^TX)^{-1}X^TY$. Let $\hat{Y} = X\hat{\beta}$, then $\hat{Y} = X(X^TX)^{-1}X^TY$.
My question is, what is the MSE of $\hat{Y}$? Is it
$\operatorname{MSE}(\hat{Y}) = \operatorname{E} \left [\left(\hat{Y}-X\beta\right)\left(\hat{Y}-X\beta\right)^T \right] $ or
$\operatorname{MSE}(\hat{Y}) = \operatorname{E} \left [\left(\hat{Y}-X\beta\right)^T\left(\hat{Y}-X\beta\right) \right]$?
The former has dimension $n \times n$, and the latter has dimension $1 \times 1$.
Comment: The former expression is the covariance matrix of $\hat{Y}$. As $\hat{Y}$ is an unbiased estimator, its covariance matrix is therefore equivalent to its MSE.
Comment: By its very name, the mean squared error is a scalar; it's the mean of the squared error.
Comment: https://stats.stackexchange.com/q/244301/119261
Answer: The latter equation is closest to correct; $MSE$ is a scalar. (It is a little weird having $\hat{Y}$ inside the expectation since $\hat{Y}=X\hat\beta$.) That said, many people might ignore the expectation.
Therefore, it might be easier to remember that $MSE = \frac{RSS}{df}$ where RSS is the residual sum of squares
$RSS=(Y-X\hat\beta)^T(Y-X\hat\beta)$
and the degrees of freedom is $df=n-p$.
Finally, one point of convention: We typically say there are $p$ covariates, not including the intercept. Thus the $X$ used in the model is typically $n\times (p+1)$. Hence we usually write that $df=n-p-1$.
Comment: This is not the same as mean square error of an estimator, is it?
Comment: No, it is not. The MSE of the estimator here would be $diag\left(E\left[(\hat\beta-\beta)(\hat\beta-\beta)^T\right]\right)$.


How to know that the node of a specific type is being viewed for the first time?

Question: I want to display a block on the node page if it is being viewed for the first time. After that that block will not be displaying.
It will be for all the nodes of a given content type.
I know the Drupal put the node in the cache if it is being viewed for the first time but I can't found its code.
Is it possible? Any Ideas?
Comment: Viewed by some specific user or all user ?
Comment: all users and the block will be a custom block.
Comment: update question with  more details clearly
Answer: Used the core statistics module.
and then on node view used the function statistics_get() function and then check it the total count is less than 1.
Comment: Great! it's so useful
Answer: Use Views Blocks and filter it with Content: Has new content to know if it is being viewed for the first time.
Comment: if also contains if a node is being updated. and also I have to display a custom block.


Probability and combinations intuition

Question: This was a question randomly given in my class by my teacher:
In a class of 10, each student has the same chance of getting a scholarship. Find the probability that exactly 3 of the students will get a scholarship?
The answer was :
$$10C3\left(\frac12\right)^3\left(\frac12\right)^7$$
But I can't seem to get the intuition of why this is so. I understand that $10C3$ means that we are choosing 3 students out of 10 but I don't get how this is used here.
Answer: Here is one way to think about the problem: consider bit (binary) strings of length ten,
$$b_1b_2...b_{10}$$
where each $b_i \in \{0, 1\}$. Suppose we make the following interpretation: $b_i = 1$ if and only if student $i$ gets a scholarship. From the assumptions, any such string is equally likely, and there are $2^{10}$ of them. How many strings have exactly three $1$'s? $10\,C\,3$. So the probability of exactly three students getting a scholarship is
$$\dfrac{10\,C\,3}{2^{10}}$$
Answer: The prob. for each student to get a scholarship is $\frac{1}{2}$ and the prob for two students to get a scholarship is independent, therefore define:
$X = # of students that got scolarship$
then X is a r.v. and we have due to independency $X \sim Bin(10,\frac{1}{2})$ and we looking for $P(X=3)$ which is exactly the answer.

Probability and combinations intuition


imitate snare sound

Question:

How does he get the snare drum sound at about 1:51 when he starts imitating drums?
I think he hits the high silver strings with his nails, but my guitar just rings out when I do that. Hitting the wood is making a different noise for me.
Then I think maybe he mutes the strings left hand, but he actually plays the high E string simultaneously to the snare one time and the B string other times and I think it's hard to control that kind of muting.
So I wonder what he's actually doing to get his guitar to make that noise, I'm really struggling to replicate on mine.
Comment: Can't decide on an overdub. The 'snare' doesn't come out the same every time.
Comment: You could use your fretting hand thumb to mute the low E string and then it won't ring out if you lightly slap it with your picking hand thumb, if you can make the stretch.
Comment: It's an overdub. He's not doing it all live at the same time.
Comment: Todd is correct. You are not hearing what you are seeing. The sound you are hearing is muted strings being slapped. Lots of reverb as well.
Comment: It looks to me like he's slapping the low E string against the frets with his picking thumb and muting it with the same thumb at the same time. If you notice, he's fretting the string at the same time, effectively tuning his "drum".
Comment: @skinnypeacock you're right, that works for me. Do you want to add an answer?
Answer: The thumb slaps the bass E string into the fret board.
When the high steel E string is played simultaneously, it looks like he strikes it with the nail of the picking hand. That made the right noise for me.
If the B string is being played simultaneously, just pluck it with a finger and hit the thumb for the snare at the same time. I found coordinating this very difficult, especially to get consistent volume, but it's possible.

imitate snare sound


Como pesquisar em uma tabela por data e somar valores contidos nela?

Question: É o seguinte pessoal, estou com muita dificuldade em criar um pesquisa por data no meu banco sqlite do android.
Queria pesquisar as tabelas por data, se possivel, queria fazer uma condicional que que detectasse a data atual, e somente atualizasse a tabela (somando certos valores) não precisando criar novas tabelas.
Desde de já agradeço grandemente a quem me der uma "luz" sobre essa pergunta.
Minha tabela é essa:
CREATE TABLE IF NOT EXISTS ENTRADA (

    _id                INTEGER       NOT NULL
                                     PRIMARY KEY AUTOINCREMENT,
    DATA                DATE         NOT NULL DEFAULT CURRENT_DATE,
    SALDO               VARCHAR (20),
    DEPOSITO            VARCHAR (20),
    ECONOMIAS           VARCHAR (20),
    SALARIODOMES        VARCHAR (20),

Comment: Como assim? Você quer checar se o campo `data` é igual a data atual?
Comment: Isso, quero checar se o campo data é a data atual (por isso o CURRENT_DATE, alias, essa tabela que criei ira sempre ser criada com a data atual mesmo? Me desculpa a outra pergunta, mas comecei a mexer com sql a muito pouco tempo XD).
Comment: Dai, queria criar uma função que checasse pela data (pode ser a data atual ou outra), e somasse os campos de SALDO.. alias, queria criar somente uma tabela dessa por data(dia)... dai o somatorio seria referente ao dia da data da tabela (isso sera feito sempre atualizando a mesma tabela né? Como faço isso tb? kkkk, desculpa minha falta de experiencia no assunto)
Answer: Olá, acredito que esteja querendo algo deste tipo:
SQL SERVER
    UPDATE TABELA_A SET VALOR = X+Y
        WHERE DATA = GETDATE()

ou Oracle
    UPDATE TABELA_A SET VALOR = X+Y
        WHERE DATA = SYSDATE()

A condição que você faz para verificar é na própria clausula WHERE ou AND do UPDATE. Dê uma olhada no seguinte link que talvez possa te ajudar.
http://www.linhadecodigo.com.br/artigo/2975/comandos-basicos-em-sql-insert-update-delete-e-select.aspx
Comment: Seria algo assim sim Eric. Como faço para pegar o valor que estava anteriormente no campo SALDO, e soma-lo ao novo valor que estarei atualizando na tabela?
Comment: "Selecionar todas as tabelas com a data atual, e somar os seus campos VALOR".. Também tem como executar essa instrução? Se sim, como ficaria em SQL?
Comment: Obrigado pela resposta, o link me ajudou mais sobre os comandos em SQL :D
Answer: Use a Classe Calendar para obter e registrar o dia, mes e ano. Converta para String e grave como String no banco de dados. Use double para o valor(ponto não virgula).
"Create table..._id INTEGER...d(para o dia) text + m(mes)..y(ano) tudo "TEXT", o valor deixe em "double" na criação da tabela
//Na Classe em que fará a pesquisa use
private SQLiteDatabase database;

//depois...
public void somando() {
   Cursor cursor;
cursor = database.rawQuery("SELECT SUM(valor) FROM nomeDaSuaTabela WHERE d = ? AND m = ? AND y = ?",new String[] { dia, mes, ano });
//obtenha do sistema os valores da data ou de um EditText
        if (cursor.moveToFirst()) {
                    double total = cursor.getDouble(0);// o argumento é o int
                                                        // indice da coluna

                    mensagemExibir(
                            "Total",
                            "A Soma do Valor doQueVcQuer do dia "
                                    + dia
                                    + " de "
                                    + mes
                                    + " de "
                                    + ano
                                    + " é de\n R$ "
                                    + String.valueOf(String.format("%.2f",
                                            total)));

                }
public void mensagemExibir(String titulo, String texto) {
        AlertDialog.Builder mensagem = new AlertDialog.Builder(
                SuaClasseContexto.this);
        mensagem.setTitle(titulo);
        mensagem.setMessage(texto);
        mensagem.setNeutralButton("OK", null);
        mensagem.show();
        mensagem.setCancelable(true);

    }

jogue o método somando() dentro do evento de um Button.
Na mensagem vc tbm pode usar um NumberFormat.getCurrencyInstance().
Embora se vc for editar depois qualquer erro na digitação do valor o android costuma arredondar os doubles depois do ponto. Aí tem que rebolar mais se quiser muita precisão. Abs
Comment: Obrigado pela resposta, me esclareceu de como usar o SUM (estava usando um while para fazer a soma :P).


Python equivalent of excel nested if condition for filtering Pandas DataFrame rows

Question: Selecting specific excel rows using python. So in excel I would do
If(And(Or(A<>({"Closed",""}),Or(B<>({"Closed",""})))

For obtaining those columns in a data frame that is neither Closed or blank. Tried using
df = df[(~df.A.isin([Closed","No Data"])) &(~df.B.isin([Closed","No Data"]))]

The problem is python is removing columns which are for example:
A                        B
Approved       Closed
No Data          Restrict
Restrict           No Data

Which I don't want
As suggested in one of the links also tried
df.loc[(df[A] != "Closed") & (df[B] != "Closed") & (df[A] != "No data") & (df[B] != "No data")

Got the same result as when I tried .isin
Comment: `df = df[(~df.A.isin([Closed","No Data"])) |(~df.B.isin(["Closed","No Data"]))]`?
Comment: Brilliant thank you so much could you please help me understand why it wasn't working.
Answer: I will use this sample data:
           A         B  ~df.A.isin  ~df.B.isin  ~A & ~B  ~A | ~B
0     Closed    Closed       False       False    False    False
1     Closed   No Data       False       False    False    False
2   Approved    Closed        True       False    False     True
3    No Data   No Data       False       False    False    False
4     Closed  Approved       False        True    False     True
5    No Data  Restrict       False        True    False     True
6   Approved   No Data        True       False    False     True
7     Closed  Restrict       False        True    False     True
8   Approved  Approved        True        True     True     True
9    No Data  Approved       False        True    False     True
10  Restrict   No Data        True       False    False     True
11  Restrict  Approved        True        True     True     True

~df.A.isin column shows the value of ~df.A.isin(["Closed","No Data"]), which is True for rows where A contains neither Closed nor No Data
~df.B.isin column shows the value of ~df.B.isin(["Closed","No Data"]), which is True for rows where B contains neither Closed nor No Data
~A & ~B column shows the value of (~df.A.isin(["Closed","No Data"])) &(~df.B.isin(["Closed","No Data"]))
~A | ~B column shows the value of (~df.A.isin(["Closed","No Data"])) |(~df.B.isin(["Closed","No Data"]))
You first attempt lacks a " at the beginning of Closed". Adding it we have
df[(~df.A.isin(["Closed","No Data"])) &(~df.B.isin(["Closed","No Data"]))]

which gives us:
           A         B  ~df.A.isin  ~df.B.isin  ~A & ~B  ~A | ~B
8   Approved  Approved        True        True     True     True
11  Restrict  Approved        True        True     True     True

The result shows only those rows that are completely without Closed and without No Data.
The suggestion in comments by Wen-Ben:
df[(~df.A.isin(["Closed","No Data"])) |(~df.B.isin(["Closed","No Data"]))]

gives us:
           A         B  ~df.A.isin  ~df.B.isin  ~A & ~B  ~A | ~B
2   Approved    Closed        True       False    False     True
4     Closed  Approved       False        True    False     True
5    No Data  Restrict       False        True    False     True
6   Approved   No Data        True       False    False     True
7     Closed  Restrict       False        True    False     True
8   Approved  Approved        True        True     True     True
9    No Data  Approved       False        True    False     True
10  Restrict   No Data        True       False    False     True
11  Restrict  Approved        True        True     True     True

Here we have | (or) instead of & (and), so the rows can contain Closed or No Data, but not in both A and B. This means the rows that have:
       A         B
Approved    Closed
 No Data  Restrict
Restrict   No Data

will be included, but not rows that have:
     A         B
Closed    Closed
Closed   No Data

Your second attempt:
df.loc[(df[A] != "Closed") & (df[B] != "Closed") &
       (df[A] != "No data") & (df[B] != "No data")

needs quotes around column labels. You can either use df.A or df['A'], but not df[A]
Also, you spelled data in No data with lowercase d, while in other places you have it with uppercase D - No Data. In python, that's not the same. If we fix that:
df.loc[(df['A'] != "Closed") & (df['B'] != "Closed") &
       (df['A'] != "No Data") & (df['B'] != "No Data")]

which gives us the same thing as the first attempt:
           A         B  ~df.A.isin  ~df.B.isin  ~A & ~B  ~A | ~B
8   Approved  Approved  True  True  True  True  True  True  True
11  Restrict  Approved  True  True  True  True  True  True  True

If you rearrange this expression a little, use parentheses and | (or):
df.loc[((df['A'] != "Closed") & (df['A'] != "No Data")) |
       ((df['B'] != "Closed") & (df['B'] != "No Data"))]

we get:
           A         B  ~df.A.isin  ~df.B.isin  ~A & ~B  ~A | ~B
2   Approved    Closed        True       False    False     True
4     Closed  Approved       False        True    False     True
5    No Data  Restrict       False        True    False     True
6   Approved   No Data        True       False    False     True
7     Closed  Restrict       False        True    False     True
8   Approved  Approved        True        True     True     True
9    No Data  Approved       False        True    False     True
10  Restrict   No Data        True       False    False     True
11  Restrict  Approved        True        True     True     True


Calculate the volume of the part of a sphere that is submerged in the water

Question: I am looking to find the volume of the part of a sphere which is submerged below the water with the following information given:

the solid sphere has diameter 10cm
the top of the sphere is 2cm above the surface of the water.

I am stuck for ways to start this problem.. anyone have a few hints they could share with me?
Comment: This question has been asked at least three times today.
Answer: It's a one-liner in calculus using the disk method:
$$
V=\pi\int_{-3}^{5}\left(\sqrt{5^2-x^2}\right)^2\,dx=
\pi\int_{-3}^{5}(25-x^2)\,dx
$$
Comment: Thank you for your help!


Which method(s) can I use to predict a response when the inputs have various combinations and proportions of of categorical and numeric variables?

Question: I don't think a question like this has been asked before but please excuse me if it already has.
I'm hoping someone can help me by pointing me in the right direction with my problem as stated below.
I have a need to derive predictors for several continuous variables (let's call them A, B and C), from a combination of two categorical variables (let's call them U and V), an ordinal variable (W) and several continuous variables (let's call them X, Y and Z).
At this stage I'm not sure how important each input variable will be and indeed if some of them can be ignored e.g. W and Z may prove to be of little use.
A, B and C are likely to be correlated, but probably not linearly.
X, Y and Z show some roughly linear correlations if I look at them split by combinations of U and V.
I have some doubts about the reproducibility of U, V and W as they are logged subjectively, but on the whole they should be OK.
I have a database of several thousand records that give me values for A, B and C on a daily basis.
However, the values for U, V and X, Y and Z are given in shorter, irregular time frames, and I have around 8,000 such records.
An example of the data is given below (note that I've copied the values of A, B and C to each row on the same day but these values are the averages for the day):

My initial idea was to use something like a Regression Tree to come up with an equation for A for each combination of U, V and W (and then do the same for B and C).
However, the data set has around 10 unique values for both U and V and 5 for W, so the potential number of unique combinations is very large, even if I were to remove one of the categorical variables.  Also, I do not have values of A, B and C available that I can map perfectly to these combinations i.e. there are always two or more combinations of U and V in any day.
Answer: This seems a straight-forward problem. You have multiple predictors which you can use in a regression model as independent variables. However, several things complicate matters somewhat:

There are multiple observations per day of variables U-Z for different time periods;
These time periods are of unequal length, in irregular intervals and the number of periods varies over days;
There are multiple outcome variables A, B and C;
These are time series data, and as such you may have to model the time dimension so as not to induce bias.

The first point does not have to be a problem. A simple solution would be to just use all the variables as different inputs into the regression, where you put in variables U-Z multiple times for different periods of the day.
The second point requires more attention. Probably the easiest way is to use some rule to bin some time periods in a fixed number of periods, e.g. morning, afternoon, night.
If you want to tackle the third issue depends on whether you want to model the correlations between A, B and C. You can do this with multiple equation models.
The fourth point can be addressed with time-series analysis. Combined with the third, you can create a vector autoregressive model (VAR).
However I would start with a simple model, just to get a feel for how the model predicts by checking its performance. Since you have lots of data, I would also include interaction terms between the different independent variables. You do not run a high risk of over-fitting the data, but you should still be carefull and use e.g. cross-validation methods afterwards.
NB: these points are just a handful of the things I can think of that warrant attention. Since we cannot see what the actual case is about, you have to see for yourself what measures are necessary in this particular case.
Comment: Thanks a lot for your very informative response Tosca - it's very helpful (and sorry for the delay is response but the alert ending up in my Junk folder). Cheers, Stuart


if $A=B \cup C$ and $A,B$ are open and $C$ is closed then $C \subset B$?

Question:
if $A=B \cup C$ and $A,B$ are open and $C$ is closed then $C \subset B$?

I thought about this statement for another question that I had.

Suppose $A,B,C$ are subsets of $\mathbb{R}^n $ such that $A=B\cup C$ and $A,B$ are open and aren't closed, $C$ is closed and isn't open, does that necessaraly mean that $C\subset B$?

thanks/
Comment: No. Find a counterexample of intervals.
Answer: First of all, if you use the usual topology on $\mathbb R^n$, then the space is connected so the only sets that are both open and closed at the same time are $\mathbb R^n$ and $\emptyset$.
For a simple counterexample, consider the intervals $A = (-2, 2), B=(-2, -1) \cup (1, 2)$ and $C = [-1, 1]$.
Comment: i tried to find such sets that are are connected.
that was my mistake, thanks you
Answer: Let $D$ denote all of the boundary points of $C$.  At first glance, I guessed that the conjecture is correct, because $C$, which is closed must contain all of $D$.  Therefore $B\cup C$ must contain all of $D$.  However, since $B\cup C$ is specified as open, each point in $D$ can not be a boundary point in $B\cup C$.  This follows, because $B\cup C$, which is open, can not contain any of its boundary points.
This implies that each boundary point in $D$ must be contained in some open neighborhood of $B\cup C$.  This superficially (and wrongly) suggested that all of $C$ must be contained in some open neighborhood of $B$.
There are two things wrong with this suggested conclusion:

Even if it were true that every point $D$ is contained in some open neighborhood around $B$, that does not imply that each
point in $C$ is contained in some open neighborhood around $B$.
A case in point is $B = (-2,-1) \cup (1,2)$ and $C = [(-3/2),(3/2)].$

As has already been demonstrated by the counter example given in Numbra's response, it is feasible that every point in $D$ will also be a boundary point of $B$.  In such a case, since $B$ is open, it won't contain any point in $D$, and therefore can not be a superset to $C$.

In fact, a less extreme counter-example would be if exactly one point $d \in D$ is also a boundary point of $B$.  This (by itself) implies that $d \in C$ and $d \not\in B$, which (again) implies that $B$ is not a superset of $C$.


Using integration to find the area of horizontal cross section of a cone

Question:
Assume the volume of cone. The base of the cone is a circle with radius $r$, and height of cone is $h$, if we have a thin slice of the cone, that is a horizontal cross section with a distance $x$ away from the base, what is the area of this cross section in terms of $r,h$?

I understand that the question is telling me that the area of the horizontal cross section is divided into many "rectangles". Thus the area will be just length multiply by the change in height.
However I cannot visualise it, the area is $A= \pi r^2 (1 - \frac{x}{h})^2$ why is this so ?
Answer: It is difficult to find/draw a diagram with the variables you mentioned, so I am going to explain my answer based on the following diagram I picked off from the internet:

You are being asked to find the area of the light-green circle.
You'll notice that $\triangle ADE\sim\triangle ABC$ and so $\dfrac rR=\dfrac kH$
 But $k=H-h$ so $\dfrac rR=1-\dfrac hH$, i.e. $$r=R\left(1-\frac hH\right)$$ and the area of the cross-section is $\pi r^2$.
I think the term "thin slice" is misleading and should be replaced with "cross-section".
Comment: nice picture :-)
Comment: why must we square $(1- x/h)$?
Comment: It is called similarity. Area of a figure scales up/down by $a^2$ as the linear dimensions (in this case, radius of circle) scale up/down by $a$ respectively.


Add event on element load before it is in the DOM

Question: I want to add an event when a DOM element is loaded but the element may not be in the DOM yet.
I could think of two solutions:
(i) attach it to document.onload(). It may take a while before it happens, if it happens so it is not ideal
(ii) checking the existence of the DOM element with
window.setInterval(function() {
      if (document.getElementById("id"))  /* do stuff */
    }, 100);

None of those is very elegant. Is there any better solution?
EDIT: I forgot to mention, I don't want to use jQuery and want to have my script in the  without touching to the  of all the pages
EDIT2: The reason I am doing so is to track the proper loading of some elements and monitor how long they take to load and if they load properly.
Comment: In modern browsers there is [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/DOMContentLoaded_%28event%29) available.
Comment: No, I would rather stay away from that
Comment: Do you have any a priori knowledge about where in the DOM the element may be loaded?
Comment: What do you mean "when a DOM element is loaded but the element may not be in the DOM yet"? Specifically, what do you mean by "loaded"?
Comment: @Lukas it can be anywhere in the ``, would it matter?
Comment: @bfavaretto, I meant when the HTML element has bee has been added to the DOM tree (ie when `document.getElementById("myId")` returns something if I am correct)
Comment: @Teemu, thanks, that's a already an improvement over `document.onload()` though not universal
Comment: Considering your update: in my opinion, the developer tools provided by browsers are better suited to track the loading status/time of a page's assets (js, css, images etc). On Chrome, press f12 for to launch the dev tools, then click the "network" tab. Firefox + Firebug have a similar tab, and IE must have one too. I really don't see why trying to use js for that.
Comment: @bfavaretto Well, not quite, I want to track the performance of my website for all users (millions) in the less intrusive way, hence all my constraints. But thanks for the suggestion
Comment: Okay, that will be complicated (except for images - you can bind to their load event quite easily). Maybe this will help: http://code.google.com/p/jiffy-web/
Answer: You can try event delegation ..
Attach the click event to the document, and check for the element you want to run the function on..
document.onclick = function (event) {
  //IE doesn't pass in the event object
  event = event || window.event;

  //IE uses srcElement as the target
  var target = event.target || event.srcElement;
  var id = target.id;
  if( id === 'id'){
      clickEvent(id);
  }
};

function clickEvent(id){
  console.log("Elemennt with ID : " + id + "has been clicked !!")
};

Comment: Thanks, that would make sense for the click events but the event I am trying to track is actually the `onload` event itself. Basically I would like to make sure all the elements (including scripts and images) load properly and monitor how long it takes for them to load. I don't see how I can link that to a user generated event.
Answer: After some research, I think there is no better universal way.
A slight improvement is to to both: putting the check on document.onload() and at regular intervals (keeping a variable to make sure I don't do it twice).
This page confirms that both are safe in terms of DOM being properly loaded.
Answer: MutationObserver is a Web API provided by modern browsers for detecting changes in the DOM. With this API one can listen to newly added or removed nodes, attribute changes or changes in the text content of text nodes.
You can read more here
https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401


In Ultimate Frisbee, what is 'universe point'?

Question: I recently read a tourney report where they talked about a game that ended with 'universe point'. I don't exactly know what that is however.
So, what exactly is 'universe point', and when/how is it played?
Answer: A Universe Point is Ultimate's version of sudden death. When this is in effect, the team that scores a point, wins the match. This is usually put into effect when...

There is no score/tie game after 40 minutes. Most schools/leagues have 40 minute long games. See explanation below.
The game is being played in the "Game to goals" fashion and the score is tied at one goal less than the game total (The game total is the pre-determined number of goals required to win the game. In a "game to 15," the game total is 15). This method is made clear in the USA Ultimate Rule Book

When it comes to 40 minutes of playing time or ANY length of game debate, it depends on which league and which school you are playing for. Most league's game is 40 minutes in length (two 20 minute halves). Here are some links to other school rule books that state the same 40 minute game.
Florida Atlantic University
Angelo State University
Comment: I don't think the "40 minutes of play time" thing is correct - in my experience, time caps for ultimate games are usually 2 hours. It would be quite unusual to call a game over after 40 minutes.
Comment: Edited my answer to explain the length of game more clearly. To sum it up quick, it's really a crap shoot when it comes to the length of an ultimate game.
Comment: I replaced some dead links with the corresponding Wayback Machine snapshots - I wasn't able to find a working snapshot [for the last link](https://web.archive.org/web/20230000000000*/http://recsport.nmsu.edu/intramurals/pdf/rules/ultimate-frisbee-rules.pdf).
Answer: The term "universe point" applies to any situation in which the winner of the current point wins the game. This could be because of a time cap (soft or hard), or just because the score is tied at one less than the score that the game is being played to.
A team that is losing to an opponent that is 1 point away from the game-winning score may also use the term "universe point" the describe the situation their team (but not the opposing team) is in. In these cases, the members of the losing team might tell each other that it is "universe point" for several points in a row, in order to frame the importance of each play.
Answer: It's actually termed ultimate point, due to the fact the the game is called ultimate frisbee, not universe frisbee. Some young whippersnappers decided to change it to a useless "universe" point but in fact it's always been ultimate point! And ultimate point is the final point of a tie game, winner take all!
Comment: Where can I find reference to this original name?


Getting absolute path with Perl

Question: I want to get the absolute path of a file with Perl. The file is located at /a/b/c/file.txt. So, I want to get /a/b/c/. I can not use Cwd::cwd() at the moment, because the actual working directory is /a/b/. That is not a bug though because the Perl script is called from /a/b/.
So, is there a Perl function to catch that, or do I have to use a regex to find it?
Comment: You need the `relative` or `absolut` path?  if `relative`, `relative` to what?
Comment: The absolute refers to `/a/b/c/file.txt`. I want the `/a/b/c/`. I call it relative! Isn't that true? If I say the parent, then some may think of `c/`.
Comment: In my understanding a relative path is relative to something, like the cwd. an absolut path starts at the root directory
Comment: Well I agree, but as I said the actual working directory in my case is `/a/b`.
Comment: So you want as output?
Comment: So you want not relative path but absolute path of directory that file is located in?
Comment: Yes. The question has been answered though
Answer: use File::Basename;
my $path = "/a/b/c/file.txt";
my ($filename, $dir) = fileparse($path);

Answer: if filenames are without special characters, and are formatted as name.ext, you can use regex such as this one:
(.*\/)[\w-]+\.[\w]{3}

filename can consist of A-Z, a-z, 0-9 and - (minus)
Comment: Is `-` special character in the file name?
Comment: @mahmood i have added - as allowed char for filename

Getting absolute path with Perl


Doesn't a major scale share all its notes with its relative minor and vice versa?

Question: I came across this sentence, reading A Theory of Harmony, John Stainer, P 9 item 27:

The scale of a relative minor consists of the same notes as that of
  its relative major, with one exception, namely, the seventh degree
  (the fifth of its relative major) which is raised one semitone.

This seems to imply that a major scale's relative minor doesn't share its notes.

A minor is the relative minor of C major.
The fifth degree of C major is G.
By 1. and 2., with the statement above the seventh degree of A minor is G#.

It seems I'm misunderstanding the above quote/musical terms. Can someone here clarify its meaning for me? Or was this statement just a bloop?
Answer: He is referring to the harmonic minor scale.
Each minor scale has three variations:

The Natural Minor - the exact notes of the relative major:

C Major: CDEFGABC
A Minor: ABCDEFGA

The Harmonic Minor - Used for harmony in Western Classical, as it better implies a resolution from the V - I, since it involves the leading tone, which has a tendency to resolve to the tonic.

C Major: CDEFGABC
A Minor: ABCDEF G# A

The Melodic Minor - Used for melodic motion in Western Classical; often used in Jazz. The 6th and 7th are raised on the way up, and then both lowered on the way down.

C Major: CDEFGABCBAGFDEC
A Minor: ABCDE F#G# A GF EDCBA

So while yes, the minor does share the notes of it's relative major key, we often alter them to please our ear :)
Comment: The harmonic and melodic minor are equally common in "Classical" music, they are just used in different contexts. The harmonic minor form is used very often when constructing harmonies (primarily for V and viio chords) but it is rather rarely used in melodies due to the augmented 2nd. Melodic minor is generally used for melodic motion (hence the different versions for upward and downward versions). The melodic minor is quite rare in harmonies. This is where they get their names in fact. They are constructs used to describe the 6th and 7th degrees in minor-key music.
Comment: @Shevliaskovic The harmonic minor is used in harmonic construction in minor keys all the time, it was just generally avoided as a melodic structure (although you'll see it plenty often in Beethoven and in later Romantic era composers). "Devil's Interval" refers to the tritone (augmented 4 or dim 5) so that never had anything to do with its melodic avoidance, it's the augmented second between scale degrees 6 and 7 that they preferred to avoid. Hence the melodic minor for melody building.
Comment: In jazz and rock music, they are often used in a freer fashion as scales in their own right that can be modally rotated etc.
Comment: I thought that the harmonic minor wasn't really used in Western Classical, due to the [Devil's interval](http://en.wikipedia.org/wiki/Tritone)
Answer: In common-practice music the seventh scale degree is usually raised, but not always. It's raised when it's part of a V or viio chord, and often during rising melodic lines. It is usually back to its natural minor state however in III chords and i7 chords and generally during descending melodic lines. The sixth degree also sometimes get raised in minor.
In modal music, where the relative minor is Aeolian, these notes are generally not raised, and thus the relative key shares notes with its major completely. The only difference here is in what note is treated like a tonic.
A more accurate way to make the statement that you're asking about is that a major key and its relative minor share a key signature, but that the minor has an altered seventh (and sixth) scale degree relatively often.
Answer: The minor mode does contain all the notes of its relative major. Besides a different tonic, the big difference is that the minor mode has two mutable notes. Scale steps 6 and 7 are can be raised a half-step in some situations. The minor mode does contain "more" notes in that sense. Of course, both minor and major modes can easily accommodate all chromatic tones.


Why these words are not formulas?

Question: First of all I know that exist a question similar to this, but I don't understand the answer.
Well my question is from the book "Mathematical Logic: Part I" and Chapter 1.1.1 where they talk about propositional formulas.
The question is: They give me the alphabet $A$ and the set of words $W(A)$ and a subset $P \subset W(A)$ with $a,b, c \in P$. The book say that $a, \big{(} a \implies (b \iff c)\big{)}$... are formulas but after this the bool says that $a \wedge b, \neg (a)$... are not formulas but they are words.
But reading the book I assume that $F_0 = P$ and for each $n$, $F_{n+1} = F_n \bigcup \{ \neg F: F \in F_n \} \bigcup \{ (F \alpha G): F,G \in F_n, \alpha \in \{ \wedge, \vee ,\implies, \iff \}   \}$
So if $F_0 = P = \{ a,b,c \}$ then $F_1 = F_0 \bigcup \{ \neg a, \neg b, \neg c\} \bigcup \{a  \wedge b,...\}$ so $a \wedge b \in F_1$ and with the definition of the set of propositional formulas constructed from $P$ where $\mathbb{F} = \bigcup_{n \geq 0} F_n$ so $a \wedge b \in \mathbb{F}$ and it will be a formula.
I don't know where I have done a mistake or something similar.
Pd: Here you have a photo from the book
Answer: Brackets matter. Binary connectives go with outer parentheses, unary connectives and propositional letters don't.
$A \land B$ is not a formula (in the strict sense) because the outer parentheses are missing. $(A \land B$) would be a formula.
$\neg (A)$ and is not a formula because the parentheses are unjustified. (The same would go for $(\neg A)$.) $\neg A$ would be a formula.
Of a different category are $A \Rightarrow B, C$ and $\forall A ...$: They are not formulas because they contain symbols that are not part of the alphabet.
Can you figure out the other ones?
Comment: "Brackets matter."  That's the point I missed.  +1
Comment: The comma is not part of the alphabet.
Comment: Okey, this is the point I was ommiting
Comment: But why $A \implies B,C$ is not a formula, which symbol is not part of the alphabet? $\forall A$ I know that is not a formula because $\forall$ is not part of the alphabet but in $A \implies B,C$ the symbol $\implies$ is in the alphabet, the problem with this word are the parenthesis?
Comment: Ah okey, perfect

Why these words are not formulas?


Variable selection - K Fold cross-validation or Lasso regression?

Question: I have a set of about 40 predictor variables for a set of 20K subjects.  The outcome is a binary yes/no response, so I would like to end with a logistic regression model. My thought is to use PROC GLMSELECT to use k fold cross-validation to pare down the list of predictors. I would then use those variables in the logistic regression model without any selection (force all variables into the model). Is this legit?
Sample code for PROC GLMSELECT:
<code>proc glmselect data=traintest seed=111;

partition ROLE=selected(train='1' test='0');

class c1-c30;

model outcomeyn = n1-n10  c1-c30/ selection=stepwise(choose=CV) cvmethod=random(10) ;
</code>
I'm also not sure what is the correct selection method to use here. I get very different results between using stepwise vs LASSO or LAR. The stepwise selection results in a simpler model, which I would prefer, but I'd like to know the correct way to choose which method to use.
Answer: Fist of all, CV is not a feature selection algorithm. Rather, stepwise selection is used, and CV is used to validate its results. In general the methods you mentioned don't have to yield similar results. If you want to try LASSO without the interpretation difficulties, you may run a LASSO model first, and then run a non-regularized Logistic regression only on the features with non-zero coefficients from the LASSO model.
Comment: Thank you very much, that is helpful.
So will this be the proper code:

proc glmselect data=traintest seed=111;

partition ROLE=selected(train='1' test='0');

class outcomeyn c1-c30;

model outcomeyn = n1-n10  c1-c30/ selection=lasso (choose=CV) cvmethod=random(10) ;

And is it okay to run LASSO on a dichotomous variable?
Comment: I am unfamiliar with glmselect, but you can run logistic regression with $L_1$ regularization. Just make sure it's logistic and not linear regression, because the name "LASSO" was originally used for linear regression with $L_1$ regularization.


Can Automation Script in Maximo replace Maximo's bean class?

Question: Please consider the following scenario,
I am in workorder application's ABC tab. I have table XYZ under ABC tab which displays values from SERVRECTRANS table using relationship between WORKORDER & SERVRECTRANS objects.
Now I am introducing new 'Select Items' button at the bottom of XYZ table which takes values CONTRACTLINES object using the relationship between WORKORDER and CONTRACTLINES object. All are fine till now.
When I click OK in this 'Select Items 'dialog box, I want values to be copied from dialog box to SERVRECTRANS. There is no out of box method available in WO.class to use as dialog value whereas others buttons have.
If you see other tables in WO application, you can see dialog value like 'copyServiceItemsToWpSerSet'. This is out of the box class which copies values from 1 mboset to another mboset.
I can write either new method like above or write separate new bean class to copy selected dialog box values to SERVRECTRANS but I would like to check the possibility of using Auto-Script for this situation.
I assume auto script is kind of replacement for MBO level class execution, but still I want to explore.
Thanks in advance.
Answer: Automation Scripts run on the "server side" (see Note 1), so you cannot use them instead of beans. However, you may be able to hook a button on the dialog to an Action associated with an Action Launch Point on an Automation Script and have that script do the copying. The catch is that you can't have the script close the dialog or do other UI things like bringing up the "longop" indicator / spinny wheel.
A good warning when getting into Automation Scripting is to be careful to not think the only way to do things in Maximo is with Automation Scripting. It is super tempting when holding the Automation Scripting hammer to think of all problems as nails, but sometimes a hammer isn't the right tool for the job. For example, a crossover domain may solve the problem you are facing and would perform better and be more supportable than a customization / automation script. (Yes. Generally speaking, you should consider automation scripts to be UNsupportable customizations, not supportable and upgradeable configurations.)
Your assumption that automation scripting is a "replacement for MBO level class execution" is almost accurate. It is more of a no-outage-required tool for customizing MBOs -- which is probably what you meant, but not quite what you said.
Note 1: Basically all of Maximo technically runs on the server in a WebSphere or WebLogic JVM / application server. But in the application server, Maximo is split into different modules, such as "businessobjects" or "mbo", "maximouiweb", "meaweb" and so on. The term "server side" in reference to Maximo means "in the businessobjects module", where the MXServer lives. On the other hand, beans, for example, live in the maximouiweb module, which is considered "client side" or "UI" and which serves up / interacts with the "browser side".
Update 2022-11-25: Note 2: Maximo version 220.127.116.11 introduced some access to the UI from automation scripts, courtesy of service.webclientsession() and some other methods. It also facilitated access to the UI through psdi.common.context.UIContext.getCurrentContext().getWebClientSession(), which some have found works better than service.webclientsession(). Using these new methods, it is possible to open and close dialogs and do some other interesting things. However, it is still a mistake to think of automation scripting as being similar to JavaScript in a browser, and I recommend avoiding dependence on access to WebClientSession where possible.


Menu responsivo, bugs no android 6.0.1

Question: Bom, estou realizando um menu responsivo, ele estava funcionando perfeitamente, e ainda está na maioria dos dispositivos, o problema é que, na segunda imagem, usando um celular com a mais nova versão do android o menu buga e os ícones sociais ficam por cima, tentei usar z-index, porém não está funcionando. Alguém saberia como resolver ?
*HTML e CSS ao final da pergunta
Iphone 5 - android ver 5.0.1

Galaxy On7 - android ver 6.0.1

HTML

Murilo Gambôa

Editar perfil

Últimos vídeos

Eclesiástico

Ajuda

Sair

Facebook

Twitter

Instagram

YouTube

CSS
/* Menu do usuário */
.user-opt{
    width: 80%;
    max-width: 280px !important;
    height: 100%;
    max-width: 360px;
    background-color: rgba(255,255,255,1);
    position: fixed;
    top: 0;
    left: -360px;
    z-index: 2;
    transition: left .6s ease-in-out;
}
/* Itens do Menu */
#close-i{
    position: absolute;
    top: 20px;
    right: 20px;
    color: rgba(58,172,243,1);
}
/* Alinhamento de texto para as opções da lista */
.user-opt ul a li{
    box-sizing: border-box;
    padding: 10px;
    position: relative;
    height: 100%;
}
/* Ícones Sociais */
.social{
    float: right;
}
.i-menu{
    margin-left:44px;
    width:30px;
}

Answer: Foi necessário adicionar uma segunda 'camada'(div) para poder jogar o menu por cima dos ícones sociais
Ex (CSS):
.nova-div{
 float:left;
 position:absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 z-index: 2; /*colocar o menu como z-index 3*/
}

Menu responsivo, bugs no android 6.0.1


Can dividing two rational numbers yield an integer?

Question: I wanted to know if two non-int numbers (non-zeroes) when divided with each other can give an integer or not.I believe that's a NO. However I know they can only yield an integer $1$ provided both are the same (i.e) $\frac{2.5}{2.5}$. Am I correct. Just wanted to be 100% sure. How about when they are multiplied ?
Comment: You can certainly divide a rational by a rational and get an integer. Example: $\frac{2/7}{1/14}=4$.  If we have two numbers, rational or not, such that $\frac{r}{s}$ and $\frac{s}{r}$ are **both** integers, then $r=\pm s$.
Comment: That is not what that wikipedia page says. Remember that integers are also rational numbers.
Comment: The Wikipedia article also doesn't say "no", what it actually says is that dividing one rational by another never produces something that isn't rational. So you can't get irrationals out of rational division. (Don't forget Raymond Manzoni's comment above at this point).
Comment: $\frac{2.4}{1.2}=2$, so the answer to your question is yes.
Comment: @MistyD : Its not the point of integers or rationals. Its the point of G.C.D . If the numerator and denominator have a G.C.D of 1, they wont yield integers and leave you with some decimal part
Comment: hint: an integer is a rational number
Comment: I actually meant to ask about non-integers - Edited my question.
Comment: Can breeding two dogs yield a rottweiler?
Comment: unless both of them are a rottweiler. NO
Comment: @AndréNicolas I actually wanted to ask about non-ints like  $\frac{2.6}{5.5}$
Comment: If $r$ and $s$ are rationals, $\frac{r}{s}$ is sometimes an integer, and sometimes not.
Comment: Thanks @Iyengar that clears it up also Joel Reyes example helped
Comment: @MistyD : That don't work always. I wanted to edit further, but suddenly my internet was interrupted. Anyway you will not get an integer always when G.C.D is not 1. Suppose $\dfrac{42}{56}=\dfrac{3}{4} \notin \mathbb{Z}$ . But $\rm{G.C.D(42,56)}=14$. So here are few steps you need to work out. 1) See that numerator is always greater or equal to denominator. 2) Reduce the fraction to the least form by applying recursive cancellations. A pseudo code can be as follows. Contd..
Comment: @MistyD : .. Contd . 1) Start with $ K= \dfrac{a}{b}$. 2)$ M= \rm{G.C.D}(a,b) $3 ) $K=\dfrac{\dfrac{a}{M}}{\dfrac{b}{M}}$. Recursively repeat until it yields an integer  4) If it don't yield an integer take the new numerator and new denominator, if their G.C.D is 1 , then its division will not be an integer. Or else it would be an integer.
Comment: @MistyD : Simply to state $a=n*b$ then it means $ b | a $ for some $n \in \mathbb{z}$
Comment: What's three-fifths divided by three-tenths?
Answer: Let $n$ be an integer and $p:=\frac{n}{n+1},q:=\frac{1}{n+1}$ then $p/q=n$. Note that both $p$ and $q$ are non-integers (as $\gcd (n,n+1)=1$).
Also if $r:=\frac{n^2}{n+1},s:=\frac{n+1}{n}$ then $rs=n$. Clearly both $r$ and $s$ are non-integers, because $\gcd (n^2,n+1)=\gcd (n,n+1)=1.$
So for every integer $n$ you can find non-integral rationals whose quotient is $n$ and non-integral rationals whose product is $n$.
Answer: Of course you can:
2.2/1.1 = 2
2.2 and 1.1 are both obviously rational non-integers, and 2 is an integer. Is this what you wanted?
You can even divide two irrational numbers and get an integer:
(2 * Pi) / Pi = 2


chained position animations with jquery animate()

Question: i would like to have a set of 11 elements "fly" into a page - by a chained set of animations using jQuery animate().
i have the following: http://bit.ly/g90S3J
which seems to work quite well in FF3.6
but i see that in IE8 -the animations and positions are way off - with elements remaining off the stage, or flying of the stage, whereas in FF, they collect around the center, as they should.
what sometimes also seems to happen in FF, is that the final position of the elements seems to change on a sporadic basis once in a while. weird!!
can someone give me a hand here?
Many Thanks!
Comment: FWIW, item1 has a top margin of -1550px and when you animate it you are adding 1200px to it. It will still have a negative margin that is greater than its height.  Therefore, it will still be "hidden".
Comment: Nevermind, I see the `top` and `margin-top`...
Answer: You have this:
<code>.flyItem {
    display: inline;
    overflow: visible;
    position: absolute;
}
</code>
When I mean to set an initial position just add:
<code>  top:0;
   left:0;
</code>
To the properties and since you have:
<code>$(function(){
       $("#item1").animate({'top': '+=1200px'},2000, 'swing', function(){
      $("#item2").animate({'right': '-=2630px'},3000, 'swing', function(){
        $("#item3").animate({'top': '-=2700px'},3000, 'swing');
                                                                                });
                                                                        });

       $("#item6").animate({'right': '+=1860px'},2000, 'swing', function(){
       $("#item5").animate({'top': '+=1000px'},3000, 'swing', function(){
        $("#item4").animate({'right': '+=1000px'},3000, 'swing');
                                                                                });
                                                                        });

});
</code>
the 'flyItem'  elements must all  be inside a relatively positioned div.
Comment: You have to set an initial position for each element since IE8 is jerk.
Comment: @jesper: This is not an answer; it should have been a comment.
Comment: i tried adding the top:0;    left:0;
but there is still a difference between FF and IE.
take a look at the same link - i have just edited the position of the Blue star and Scroll - they look different in IE and FF.
Comment: ok - found the solution - the above works, when the moving elements are inside a relatively positioned div. (i edited the answer respectively)
thanks!


How to keep the size of the database reduced?

Question: I found out a very simple D7 site with less than 150 nodes had database dumps of 65M (gzipped). Which caused my entire server to become slow during the nightly database dumps.
After some searching I found this useful query:
SELECT TABLE_NAME, table_rows, data_length, index_length,
round(((data_length + index_length) / 1024 / 1024),2) "Size in MB"
FROM information_schema.TABLES WHERE table_schema = "DRUPAL_DATABASENAME_GOES_HERE";

With that I immediately found the culprit: the sessions table.
After a TRUNCATE sessions my dump is now <1M (gzipped).
How can I make sure this site's dump doesn't blow up again in the future?
I found periodic purging of watchdog and sessions tables? on drupal.org, but it's from 2007.
Answer: Don't dump session, cache_*, watchdog table content (make sure to keep the structure).
For watchdog there's syslog replacement.
If you don't need the access logging in Drupal disable that module and dump that table as well.
For huge content driven websites with lots of edits (and revisions) clearing the revision tables from time to time might help too. (e.g. with node revision delete).
Answer: Try the modules

Optimize Database, and
Database maintenance

The differences are also explained in the this fixed issue Compare with DB Maintenance in the Optimize Database issue tracker.
The first can also run cron (so, optimize at midnight).
Answer: If you find you have too many rows in the sessions table, you can adjust your PHP session settings in settings.php
/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

For example, you could reduce session.gc_maxlifetime and session.cookie_lifetime to purge the sessions table more frequently.
More info on session configuration:
PHP: Runtime Configuration: Session
Although not directly related to the large sessions table, using an alternative cache handler, such as Memcache can help reduce DB size by moving cache tables into Memcache instead.
Answer: Apart from some of the tables mentioned in some other answers already, there are plenty of other tables in Drupal 7 that you can either clear (to reduce the database size) or safely exclude when performing backups. Such as various search*-, devel*-, ctools*- or flood tables.
For a pretty long list (inventory) of those tables, have a look at my answer to "Which tables are safe to clear?"
Answer: Try redis
This will allow you to completely remove the cache tables and speed up the site in the process


DB2 Transactions - Commit everything or rollback

Question: I have a SQL Script that have multiple Inserts/Updates/Deletes and I want to guarantee that it only commits if all statements run with success.
I think the Database has the autocommit set a True and since I'm not the one responsible to manage it, I can't change it...
Thanks in advance!
Comment: What is your environment, what is the script processor? It is a setting on the transaction level and can be changed for the script.
Comment: Autocommit is controlled at the session (connection) level, so you can set it according to your requirements. The actual method of changing this setting depends on your client.
Answer: If you are submitting the SQL-script to the Db2-command-line processor (db2 clp) then you can use either a command-line option to disable commit, or you can enable or disable the autocommit on the fly inside the script.
To disable autocommit on the Db2 CLP command line:  use db2 +c -stvf scriptfile.sql
To disable autocommit inside the script file:
update command options using c off;    --disable autocommit

insert... ;

update ...;

commit;

If you are submitting the script to a different processor, you need to specify which script-processor you are using, as different tools have different methods to specify these things.


Cause of G string on Ibanez JEM sounding dead?

Question: My Ibanez JEM with floyd rose tremolo, this exact guitar: , has a problem with the G string.
The open string sounds out more or less properly (though it tends to go 'harmonic', which seems like it's probably related to the problem). On the higher frets, it lacks sustain. It sounds dull and 'weird' (like it tries to produce two notes at once, not sure how else to explain this), and the sustain is almost zero.
I have tried different strings, to no avail (exact same result). The bridge/saddle and nut seem undamaged. The fret wire looks alright on all frets, including the ones most affected by this problem.
The other strings are all fine, and I don't see any difference in any of these aspects between them and the G string. I would expect the string to hit something it shouldn't, but after studying it carefully I don't see it hitting fret wire on other frets or anything. And again, there is no difference between the G string and the others that I can see.
What could cause problems like this one, if not any of these factors?
Comment: On which Frets and which strings do you have buzz and dull sound?? please give me exact information.
Answer: I would say it's most likely a problem with the bridge.  The acoustic end point of the string, the slot or edge it lies on, can fit the string poorly (through wear or incompetent setup) in such a way that the string buzzes against it and loses energy, and the fault can be invisible- it's often a matter of tenths of a millimeter.  You probably need a luthier to look at it.
Comment: If it is that, and sounds like it could be, I'd swap a couple of saddles round - if it persists, then it will be something else. Try swapping 3rd and 6th string saddles - then you'll need to re-intone - if that's the word!
Comment: @JMoons- Tim has made a very good suggestion here: try swapping saddles around and see what happens.
Comment: Thanks for your suggestion. When you say 'incompetent setup', which aspects of the setup would I need to look at?
Answer: It really sounds like it's fretting out, even if it looks like it's not.
With a guitar like this, the tolerances can be very, very fine. It's meant to be played fast, so the action is supposed to be quite low. That means it's a lot harder to get the action right at home without experience and proper tools. I would take it to a tech.
If you're hell bent on figuring it out for yourself, then see what making the G string action higher by raising the saddle does. If it helps, then you know something is off there. You can try lowering it gradually until it just starts to fret out and then lift it slightly again, but there may be other problems. I would start by making sure the overall neck geometry is good (relief and neck angle). Check for fret wear. IF you have the gauges for it, check the nut slot or string lock assembly for the right height/depth.
Comment: Once you fret above the open string, whatever the nut does is not party to the problem. And OP seems fairly happy with open sound. If the relief is out, it'll probably affect the other strings too. Action adjustment for 3rd string sounds a favourite. Oh, why doesn't every guitar have a zero fret?!
Answer: I'm assuming you figured out the problem by now, but for anyone that has this problem and you can't figure out the problem, when doing all the stuff mentioned by others, I would suggest trying a different Amplifier. This might be a good first move actually. I had A similar issue and the amp sound like octaves on multiple, but mostly just on the little thinnest strings, because that was when you could hear it the best. When the frequencies were deeper sounding on the guitar you couldn't hear that low octave frequency. I tried tons of things but could never figure it out.
So I say try another amp because the problem wound up actually being the output filter capacitor that had one of the legs that disconnected from the circuit board. In my amp, there were two caps and one wasn't working. I also had a lot of noise, but it might of be that the cap just went bad.
The funny thing is I actually took this amp to have someone who claimed to be an amp repair guy for a major amp company, prior to figuring it out myself. The guy never even bothered to take the amp apart. He wound up telling me that it just needed to preamp tubes to get rid of the high noise floor sound. The original problem I took it in to have looked at. He just replaced the tubes with really dull lifeless JJ tubes, that have very little high-end frequency output, in order to mask or hide the problem. I decided to finally try for the third time to get the amp apart to see If I could figure it out. I finally figured out how to get off the rubber handle caps that was preventing me from getting the handle off, and it didn't take me long to see that broken capacitor.
Answer: The answers here are on the right track I think: you can fret the string and use a thin piece of paper to determine if the string is hitting other frets closer to the bridge. If it is, you can raise the saddle a little and see if that helps.
Aside from that and the saddle fitment, look into the possibility that your tremolo springs are resonating with and/or dampening the note.
Resonating springs are common on tremolo equipped guitars (google "floyd rose springs resonating"), and I think the resonance can vary a lot based on spring tension.
After all these tests, if you still cannot figure it out, it may be time to take it in to get it looked at.
Answer: I have problems with the g string to various degrees on most
of my sixty guitars. I know my way around setups and conquer
most any problem that develops with my guitars.
after 50 years of playing and modifying guitars I have recently
noticed that the truss rod adjuster quite often touches the
bottom of the fret board at the head end very close to the nut
and the first fret where most of these g string dead spots occur.
The guitars that i own are the worst when the truss rod adjuster
tends to press tightly against the bottom of the fret board and
i think i am now going to try to take a tiny file or mini chisel
to shave the wood next to the adjuster in the hope that relieving
pressure in this area will keep the truss rod from sucking the
life out of the g string at the nut and first fret.  I Hope
this helps as this is a new idea I JUST CAME up WITH jAN 2020.


Excel - Merge Multiple Columns Cells into a single Cell

Question: I have an Excel spreadsheet in the usual fashion. That is to say, rows and columns. So if there are seven rows, each column has seven values. I want to take one of these columns and make it extend down across the whole spreadsheet. TRANSFORMATION (LOGIC) used to have seven values, now it has one. How do I do this? EDIT: By "down across", I mean the column should have just one cell.
Comment: Thanks, Paul. I mean the column should have only one cell, as opposed to have seven cells like all the others.
Comment: Slightly confused on my first read: extend "down across"? Just want to clarify how you want it to look
Comment: I hope I am understanding your question correctly with my answer but if not I apologize!
Answer: In order to achieve the merging of your cells, select the desired cell range on your sheet and then you will click the "Merge" button found on the Home tab in Excel.
Note that if the content is already in the cells it will take the value from the first cell which has content in it already, so best to copy your values and such out first if you would like to preserve them.


How can I show anonymous users their own content?

Question: I've tried to reach this with views and https://www.drupal.org/project/session_node_access and https://www.drupal.org/project/views_extras with no luck.
Any suggestions?
Comment: The simple answer is that you can't. The whole thing of being anonymous is that you aren't identified/identifiable. There is no way to associate anonymous content with a specific user. If content needs to be assigned to specific users, they can't be anonymous.
Comment: If you can give us more detail as to your goal, we may be able to provide more assistance.
Answer: An anonymous user is a user with uid=0. So all (repeat all) anonymous users have the same uid value, and therefor there is no way to do what you are asking for out of the box.

There are various techniques you could programmatically do, but of course they all have their limitations.
Starting an anonymous session. Here when the node is created you add the Node ID in a $_SESSION variable and you can use this to retrieve the Node ID and pass that to the views arguments. Obviously, the limitation is that as soon as you close the browser, the session ends and you can no longer tell if it's the same user. So you have to start the cycle again, create a new node, etc...
Using cookies same as above but with cookies. Once cookie expires or it's cleared it's over.
Using IP You would save the IP as a field in the Node and you can query the DB to retrieve the Node that belongs to that IP. Obviously, the limitation here is if the user's IP changes it ends here.
Combination of all 3 Lastly, you could do all 3, have the other 2 as possible backups.
Comment: `there is no way to do what you are asking for.` @Jaypan also says, `If content needs to be assigned to specific users, they can't be anonymous.`  But... Commerce, which uses Views can show anonymous users their own order/cart view
Comment: Interesting comment @NoSssweat (bonjour!) ... didn't know / realize that. If you have more info /details about ***how*** Commerce does that, then feel free to add (edit) that in my answer (or get the question reopened to post an extra answer!
Comment: They likely store it in a cookie/session - as carts often do. But this runs into the issues that Pierre lists - there is be no way to do it consistently, since once that cookie is lost, there is no way to associate the user back with their content. Consider logins - they expire when the cookie expires, and the user requires some sort of identifier to be able to tell the system who they are again. This is the username/password combination. Without a method to re-identifying the user, there is no way to re-associate their content. And if the user can identify themselves, they aren't anonymous.
Comment: merci for the edit @NoSssweat ! And to Jaypan also merci for the additional comment (if you want that edited in the answer also: please go ahead!


Matrix derivative calculation

Question: If given $\mathbf{G}(t)=\exp(\mathbf{F}(t-t_0))\mathbf{A}\exp^T(\mathbf{F}(t-t_0)) + \int^t_{t_0}\exp(\mathbf{F}(t-s))\mathbf{M}\exp^T(\mathbf{F}(t-s))ds$
$\exp$ represents expotional matrix, and $\mathbf{F}, \mathbf{A}, \mathbf{M}$ are constant matrices
How to take derivative of $\mathbf{G}(t)$? w.r.t $t$?
$\frac{d\mathbf{G}(t)}{dt}=?$
Answer: I assume that $\exp^T(F(t-t_0))$ is the transpose of $U(t-t_0)=\exp((t-t_0)F)$, that is ${U(t-t_0)}^T$.
Then $G'(t)=FU(t-t_0)A{U(t-t_0)}^T+U(t-t_0)AF^T{U(t-t_0)}^T+M+\int_{t_0}^t (FU(t-s)MU(t-s)+U(t-s)MF^T{U(t-s)}^T) ds$.
Comment: OK Nathan, thank you.

Matrix derivative calculation


Weblogic server takes too long to start on windows

Question: Weblogic server takes too long to start on windows.
I want it to run some soa applications in jdeveloper.
how to make it start faster?
I found some solutions for linux, but not for windows.
thanks for your help in advance.
Answer: If more than 30 seconds, you have a problem.
Maybe the problem is not windows but the projects you previously uploaded to the server.
Try to create a new project from jdeveloper and press Run to start the integrated weblogic:

if too much time → disable temporarily windows firewall and/or your antivirus and try again
if less than 30 seconds → the production server contains too much projects, too much libraries to be loaded, etc.

I usually HAD a lot of problems because of the company antivirus system.
Answer: If you're running Windows, sometimes Weblogic binds itself to all network adapters configured on your machine running Windows. This doesn't happen on Linux systems.
All these redundant bindings end up eating a couple of seconds of startup time. To minimize it:

Start Weblogic: on JDeveloper, go to Run > Start Server Instance
Go to the admin console at http://localhost:7101/console and login as
weblogic/weblogic1
On the left side navigation bar, select Environment > Servers
Select Default Server from the table
On the Listen Address field, enter: 127.0.0.1
Restart Weblogic

This should reduce at least 30 seconds of startup time for Weblogic instances running on Windows.


Example of distribution whose support is strictly positive

Question: I am looking for something similar to the normal distribution in which there are a mean and a standard deviation representing the amount of variation. However, the value must always be positive, i.e. $P(x \leq 0) = 0$.
Comment: @LongThai you should also recognize that the **strictly positive distribution** referred to in the question you link is quite different from the _strictly positive distribution_ you describe--namely, those theorems refer to the _density_ being strictly positive, while it seems you are referring to the _support_ being strictly positive. This is the same as focusing on, for $f:D\rightarrow R$, whether the domain $D$ of $f$ (your question) or the range $R$ of $f$ (linked question) is restricted to be positive.
Comment: What about a Gamma or a log-normal distribution ? There is a mean and a standard  deviation for these distributions. Do you mean something else by "similar to the normal distribution" ?
Comment: You could transform a symmetric Beta distribution to any interval $[a,b]$ using an affine transformation.
Comment: @FedericoPoloni he means the support, not the density
Comment: That means I want something that has the simibar shape to normal distribution.
Comment: Isn't a normal distribution strictly positive? Or am I misunderstanding the definition?
Comment: A gamma distribution with a large shape parameter can certainly look quite similar in shape to a normal distribution.
Comment: @MichaelChirico thanks for your comment, I've updated my question.
Answer: You may be interested in this gallery of distributions. In addition to

the gamma distribution
the lognormal distribution
the $\chi^2$ distribution
and the truncated normal distribution

that have already been brought up, you could check

the F distribution
the exponential distribution
the Weibull distribution
the power lognormal distribution

All of these have defined means and variances. Pick the one you like best.
Answer: What about the truncated normal distribution? Try for example
library(truncnorm)
x <- seq(0,10,by=.01)
plot(x,dtruncnorm(x, a=3, b=Inf, mean = 5, sd = 1),type="l")

This gives

By taking the mean of the underlying normal distribution $\mu$ (mean in the command) larger you can make it look "almost" normal, without a nonzero probability of nonpositive values.
Comment: Thanks for your answer, I think the only issue is that the mean is not exactly the same with the given value. But as you stated, using a larger mean can help.
Comment: Indeed. As you cut off probability mass in the left part of the distribution, there is no way the mean can stay *exactly* the same.
Answer: There are infinitely many such distributions ...
Consider the family of uniform distributions from $0$ to $N$ (non-inclusive of $0$), where $N$ is an arbitrary integer.
Now choose any one of these, say $X_1 \sim U(0,3)$.
Then the sum of $X_1 + \dots + X_{10}$, where $X_1, \dots, X_{10} \overset{\text{iid}} \sim U(0,3)$ will be approximately normal in shape.
This uniform sum distribution is also known as the Irwin-Hall distribution.
Comment: In the comments above, OP mentions that he wants "something that has a shape similar to the normal distribution"
Comment: good eye. will emend to reflect.
Answer: Two suggestions for you:

The Non-central $\chi^2_1$ distribution which is (can be) obtained by squaring the normal distribution $N(\mu,1)$?

This easily satisfies your relation to normal as it always shares the parameters of some underlying normal. However, it always skews right, so while it may look sort of normal, it will never be.

The distribution of number of heads from a series $n$ of coin flips (also known as the $Binomial(n,p)$ distribution) looks more and more like the normal distribution as $n$ increases.

The drawback here is that the support is always finite and includes 0; this latter can easily be remedied by just adding 1.


Java8 stream filter by multiple parameters

Question: I have the following class:
public class Transfer {
    private String fromAccountID;
    private String toAccountID;
    private double amount;
}

and a List of Transfers:
....
private List<Transfer> transfers = new ArrayList<>();

I know how to get one transfer history:
transfers.stream().filter(transfer ->
    transfer.getFromAccountID().equals(id)).findFirst().get();

But I want to get by fromAccountID and toAccountID, so the result will be a List of Transfers. How can I do that with Java8 Stream filter functions?
Comment: you should never call `get()` straight from an optional result except in cases where you know there will be a value present. rather you should utilise [`orElse`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElse-T-) or [`orElseGet`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElseGet-java.util.function.Supplier-) depending on which is most appropriate for your case
Comment: your advise was really helpful today, get() threw an exception, in order to handle it, I've used orElse and check it if it is null. Cheers!
Answer: filter by the two properties and collect into a list.
List<Transfer> resultSet =
      transfers.stream().filter(t -> id.equals(t.getFromAccountID()) ||
                        id.equals(t.toAccountID()))
               .collect(Collectors.toList());

Answer: You can filter by both properties (getFromAccountID() and getToAccountID()), and collect the elements that pass the filter to a List:
List<Transfer> filtered =
    transfers.stream()
             .filter(t -> t.getFromAccountID().equals(id) || t.getToAccountID().equals(id))
             .collect(Collectors.toList());


Assign inner list to new variable - Python

Question: I stumble upon some issue with list. I have nested list like this one
[[1, 2, 3], [4, 5, 6],[7, 8, 9]]
This list can be arbitrarily large and inner list does not need to be in the same length(size).
What I would like to achieve is to take out each inner list and assign to new variable.
This means in our toy example the following.
Var1=[1,2,3]
Var2=[4,5,6]
Var3=[7,8,9]

I can index it manually in toy example each inner list, but this not desired result. I need to store as separate variable each inner list. Moreover I prefer function to do this for me.
What I need is a function that takes nested list and assigns each inner list to variable automatically. Input of function should be nested list and output should be each inner list assign to variable. The solution should scale to larger list size.
Comment: is there a reason you want to do this? what makes indexing the original list a problem?
Comment: I need to be automatic. I do not want do it manually.
Comment: ok, can you edit the question saying how assigning to different variables would make your problem easier? as it stands you have not pointed out why indexing is not an optimal approach for you
Comment: @ python_user Done it.
Comment: You can use a dictionary to solve your problem. Maintain a counter for key and loop through the nested list. That way it will be automatic too.
Comment: @python_user It is bad because imagine that I have longer list with numerous entries. E.g. let's say 100 inner list. I need to every time to refer to index.
Comment: Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables)
Answer: This should work:
main_list = [[1, 2, 3], [4, 5, 6],[7, 8, 9]]
for i in range(len(main_list)):
    declare_statement = f'Var{i} = {main_list[i]}'
    exec(declare_statement)

'''
now each value of the main_list is stored in variable different variable with
prefix "Var" and index of that value as postfix
'''

That means print(Var0) would display [1, 2, 3], print(Var1) would display [4, 5, 6] and so on but honestly I don't see a point to this.
You could've achieved the same thing by print(main_list[0]) and print(main_list[1]) it is just a waste of memory to assign each value of a list to a variable and it also defeats the purpose of lists and arrays.
Comment: Thanks. This is what I look for.