The SharedPreferences doesn't save the checked box in my Android app

Question: I have a check box in an AlertDialog that starts when the app starts. I added "SharedPreferences" to save if the check box is checked or not. If the check box checked, the AlertDialog never starts or shows when the app starts. But my problem is: When I check that box, the AlertDialog starts in every time when I launch the app.
checkbox.xml (layout file):
<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/checkboxDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        style="?android:attr/textAppearanceMedium" />

</LinearLayout>
</code>
The onCreate method in the MainActivity.java:
<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View checkBoxView = View.inflate(this, R.layout.checkbox, null);
        final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkboxDialog);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences prefs = getSharedPreferences("state", 0);

                if(prefs.getBoolean("x", false) == true)
                {
                    checkBox.setChecked(true);
                }
                else if(checkBox.isChecked() == true)
                {
                    SharedPreferences myPrefs = getSharedPreferences("state", 0);
                    SharedPreferences.Editor editor = myPrefs.edit();
                    editor.putBoolean("x", true);
                    editor.commit();
                }
            }
        });
        checkBox.setText("Test");
        final Context context = this;
        AlertDialog.Builder mainDialog = new AlertDialog.Builder(context);
        mainDialog.setTitle("Test");
        mainDialog.setMessage("Test my dialog!");
        mainDialog.setView(checkBoxView);
        mainDialog.setPositiveButton("Go to website", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                startActivity(browseIntent);
            }
        });
        AlertDialog alertDialog = mainDialog.create();
        alertDialog.show();

        ...
    }
</code>
Comment: you are never initialising your checkbox with the value from sharedpreferences..
Comment: @Tobrun Can you explain more?! because I never used the SharedPreferences before. Thanks.
Comment: add something like *checkBox.setChecked(myPrefs.getBoolean("x",false));* in onCreate
Comment: @Tobrun I added that line of code, but same problem!
Comment: Take a closer look at your `onCheckedChanged()` callback: once you check your checkbox and write its state, you'll never write it again because you'll always end up in the first if-branch. You don't need `SharedPreferences` out there anyway. Simple debugging would solve your problems.
Comment: @SqueezyMo I am a beginner, I never used the debugging before and I don't know how I use it! If you can help me with the correct code. Thanks.
Comment: But I told you what's wrong with your code. Just put `Log.d()` calls in relevant parts of your method and see how the execution flows. You'll notice the flaw before long.
Comment: @SqueezyMo Why use `Log`, which is for, er, logging, instead of the debugger?  The debugger will find it in 30 seconds.
Comment: @MrGlitch Trying to build apps without knowing how to use the debugger is like trying to build a house with no cement.  Just Google for it.
Comment: @Simon Because debugging is not limited to using debugger. See what `d()` stands for. Print statements is the simplest approach, surely not the only one.
Comment: @SqueezyMo Debugging with logging is about the hardest way to do it.  Reserved for those really difficult bugs related to threading, race conditions etc.  Bugs like this are much easier to fix with the debugger and the Android community does a lousy job of explaining how to debug to noobs.
Comment: @Simon Logging lets you see the whole picture at a glance. I usually find myself using logging more often than the debugger. Matter of preference, I guess, so there's no ground for arguing. In simple scenarios any approach will do.
Comment: @Simon I found a small bug in this line `if(prefs.getBoolean("x", false) == true)` by using the debugger (Changed to `prefs.getBoolean("x", false) == false`), but the main problem I didn't find a solution for it. :(
Answer: I found the answer here:

http://examples.javacodegeeks.com/android/core/content/android-sharedpreferences-example/

Hope it will help others.
Thanks.


PHP if file exists, always show that exists

Question: I have database columns attach1 and attach2.
I need to show files (pdf) from those columns, but only if they exist in directory www.domain.com/uploads.
Attach1 contains real file but attach2 does not.
I tried something like this:
<?php
$file = $row['attach'];
$exists = file_exists('uploads/'.$file.'');
if ($exists) {
  echo $file;
}
if (!$exists) {
  echo 'No file1';
}
?>

<?php
$file2 = $row['attach2'];
$exists = file_exists('uploads/'.$file2.'');
if ($exists) {
  echo $file2;
}
if (!$exists) {
  echo 'No file2';
}
?>

But everytime it echoes me back, that file exists, even when attach2 contains nothing. Why?
Comment: Not to your question, but there are a number of pointless things in your code sample. You don't need to concatenate an ampty string onto the end of the filename. you don't need to save the result of `file_exists` in a variable. You can use `else` to simplify your conditionals.
Comment: Did you try to `echo $file2` and make sure it's not empty? If it is, you'd be checking `file_exists('/uploads')`, which is of course `TRUE`.
Comment: try this 'if(isset($file)'
Comment: Yes I'm sure its empty. Ok if I'm checking the directory, how can I check concrete file?
Answer: If your filename is empty, then you are passing only the directory name to file_exists. Directories are files too. And I reckon the directory does actually exist. It is not lying to you.
You can either check that the filename from the database is not empty, or you can pass the whole string to the function is_dir to see if it is a directory. I assume you only want regular files.
That would look something like this:
 <?php
 $file = $row['attach'];
 $exists = file_exists('uploads/'.$file.'') && !is_dir('uploads/'.$file.'');
 if ($exists) {
   echo $file;
 } else {
   echo 'No file1';
 }
 ?>

I changed the if statement to use an else clause. It is equivalent to using a second if like you did.
Comment: How would I do that? Please.
Comment: Which part? `is_dir`?


How to count the number of occurrences of a attribute in a string of another table

Question: Im struggling with a complex SQL query, I want to count how many times attribute x in table 1 shows up in a string in table 2.
so t1 has a name attribute and t2 has an participants attribute and a project attribute
ID | Name
---------
0  | Bob
1  | Bill
2  | Jill

T2
Project | Participants
-----------------
0       | Bob, Bill
1       | Bob, Jill
2       | Bob

Output
Bob  3
Bill 1
Jill 1

Participants in t2 is a string. Is there anyway to do this?
Comment: You are struggling because the query will be complex, and that will be because table T2 is not in first normal form. If the "Participants" string comes from some external source, so you have no control over it - that is fine, but it shouldn't be stored that way in a relational database, like Oracle. The string should be broken down into its component tokens, and the result is what should be stored. As it is, you will have to do the "tokenization" (normalization) yourself, in every query, and that's complex, and you will struggle with it.
Comment: I would recommend to desgin table T2 to be in first normal form:
[link](https://en.wikipedia.org/wiki/First_normal_form)
Answer: You should primarily focus on fixing your data model. Each participant to each project should be stored as a separate row rather than munged in a delimited string, possibly referencing the other table through a foreign key constraint:
project_id    participant_id
         0                 0   -- Bob
         0                 1   -- Bill
         1                 0   -- Bob
         1                 2   -- Jill
         2                 0   -- Bob

Then you could efficiently phrase the query:
select t1.*
    (select count(*) from table2 t2 where t2.participant_id = t1.id) cnt
from table1 t1

That said, given your current layout, one option uses string functions:
select t1.*,
    (
        select count(*)
        from table2 t2
        where ', ' || t2.participants || ', ' like '%, ' || t1.name || ', %'
    ) cnt
from table1 t1

Answer: If the participants only appear once in each project then you can use:
SELECT t1.Name,
       COUNT( t2.Participants) AS cnt
FROM   t1
       LEFT OUTER JOIN t2
       ON ( ', ' || t2.Participants || ', ' LIKE '%, ' || t1.Name || ', %' )
GROUP BY t1.Name

Which, for the sample data:
CREATE TABLE t1 ( ID, Name ) AS
SELECT 0, 'Bob'  FROM DUAL UNION ALL
SELECT 1, 'Bill' FROM DUAL UNION ALL
SELECT 2, 'Jill' FROM DUAL UNION ALL
SELECT 3, 'Tim'  FROM DUAL;

CREATE TABLE T2 ( Project, Participants ) AS
SELECT 0, 'Bob, Bill' FROM DUAL UNION ALL
SELECT 1, 'Bob, Jill' FROM DUAL UNION ALL
SELECT 2, 'Bob' FROM DUAL;

Outputs:

NAME | CNT
:--- | --:
Bill |   1
Jill |   1
Bob  |   3
Tim  |   0

db<>fiddle here


TNB Frames (Principal Normal Vector)

Question: From the way I'm looking at it, there should be two ways to find the principal normal vector of a plane curve $C$ given by vector equation
$$ \pmb{r}(t) = x(t)\pmb{i} + y(t)\pmb{j} + 0\pmb{k}. $$
That is, the way as laid out in TNB Frames:
$$ \pmb{N}(t) = \frac{T'(t)}{\|T'(t)\|} \quad (1)$$
(where $T$ is the unit tangent vector) and by simply rotating the unit tangent vector $T$ by $\frac{\pi}{2}$ counterclockwise :
$$ \pmb{N}(t) = -\frac{y'(t)}{\|\pmb{r}'(t)\|}\pmb{i}  + \frac{x'(t)}{\|\pmb{r}'(t)\|}\pmb{j} \;\quad (2) $$
(this is similar to how the normal vector to the tangent is found in the vector form of Green's Theorem). But when I solve out equation $(1)$ to get
$$
  \pmb{N}(t) = \frac{T'(t)}{\|T'(t)\|}
             = \dfrac{\left\langle \frac{x''(t)}{\|\pmb{r}'(t)\|}, \frac{y''(t)}{\|\pmb{r}'(t)\|} \right\rangle}{\sqrt{\frac{(x''(t))^2 + (y''(t))^2}{\|r'(t)\|^2}}}
             = \dfrac{\langle x''(t), y''(t)\rangle}{\|r''(t)\|}
$$
and compare components between $(2)$ to get
$$
  -\frac{y'(t)}{\|\pmb{r}'(t)\|} = \frac{x''(t)}{\|\pmb{r}''(t)\|}
  \;\text{ and }\;
  \frac{x'(t)}{\|\pmb{r}'(t)\|} = \frac{y''(t)}{\|\pmb{r}''(t)\|},\;\;\;
$$
things don't seem to work out. For example, the above equalities do not hold for curve
$$ \pmb{r}(t) = \langle t^2, t^3 \rangle, $$
and I'm not sure why. Am I misunderstanding how the principal normal vector is supposed to work, or is my math just wrong? Any insight would be appreciated.
Edit: For clarification, if I had a closed curve oriented counterclockwise, I would expect both methods to yield an orthogonal vector to $T$ of unit length pointing towards the region bounded by the curve. I would expect both derivations to produce the exact same vector in this case. That's essentially the crux of my problem.
Comment: When calculating (1), make sure to use the quotient rule for calculating $T'(t)$.
Comment: Thank you a bunch- I can't believe I missed that. I'll go through the calculations later, but I'm fairly confident that was the problem
Answer: So, as user197427 pointed out, I did miss the quotient rule when solving for the normal. The math got really ugly really quickly once I correctly applied the derivative, to the point that solving it out would be a real tedious chore.
Nonetheless I wanted to close this question with the answer of "my math was wrong."

TNB Frames (Principal Normal Vector)


imagebutton becomes very large when I choose my avatar

Question: I have an imagebutton that is fixed to the top right of the navigation menu and when you click on it, you could select an image from your android library and make it as your avatar.
However, once you select your picture, the imagebutton instead becomes very large.
Here is how the button is initally: Before Choosing avatar
here is how the button is after choosing the avatar: After choosing avatar
I inserted this piece of code inside the onCreate() method in NavDrawerActivity class
imgButton = (ImageButton) navigationHeaderView.findViewById(R.id.imageButton1);
imgButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");

        startActivityForResult(intent, IMAGE_UPLOAD_REQUEST);
    }
});

RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), getThumbnail("desiredFilename.png"));
roundedBitmapDrawable.setCircular(true);
imgButton.setImageDrawable(roundedBitmapDrawable);

Here is my XML:
<ImageButton
   android:layout_gravity="right"
   android:id="@+id/imageButton1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/round_button"
   android:scaleType="fitXY"
   app:srcCompat="@android:drawable/ic_menu_gallery"/>

Answer: Try to add this into XML to set fixed size:
android:maxWidth="42dp"
android:maxHeight="42dp"

42dp is just example, set whatever you want
Comment: I tried with 5 and with 20, but it's the same thing
Answer: Judging by what you've given us to work with, the image size of the avatar is much larger than the original icon. If you want it to be the exact same size as the icon, you could either downscale the image, or change the size of the ImageButton from wrap_content to a fixed value. :)
Change this:
android:layout_width="wrap_content"
android:layout_height="wrap_content"

To this:
android:layout_width="THE WIDTH OF THE ICON"
android:layout_height="THE HEIGHT OF THE ICON"

EDIT:
Bit of an abstract thought, but may as well try it.
Change this:
<ImageButton
            android:layout_gravity="right"
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/round_button"
            android:scaleType="fitXY"
            app:srcCompat="@android:drawable/ic_menu_gallery"/>

To this:
<ImageButton
            android:layout_gravity="right"
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/round_button"
            app:srcCompat="@android:drawable/ic_menu_gallery"/>

Comment: I never had maxWidth and maxHeight. Do you mean layout_width?
Comment: Yes sorry, my bad.
Comment: I get this now... weird. Not sure what's the problem but thank you for trying... https://imgur.com/a/OKJyB
Comment: That's odd. Please refer to my edit for further steps.
Comment: no luck, just turns the circle into a square instead.
Comment: Is the image just white? If so, try changing it to something that's easier to spot (i.e giving it a RED color) Then we might be able to see if that large white square in the previous image you showed me is the actual image, or if it's just a random object.
Comment: No it's a real image with no white spots..that exact code works on another app but on that app it doesnt for some reason
Comment: Strange. If the code works on another app, could you copy all of the files over into a new project? Or are other things in your current project causing the problem?
Comment: ok got it to work! had some stupid setcolor code that was there for no reason, had to remove it..but now I have a xml problem
Comment: That's great to hear! Could you elaborate on the XML issue?
Comment: I am having this problem https://imgur.com/a/7PWGm .....do you know how to make the lsit stick on top?
Comment: Try: `android:layout_alignParentTop="true"` or `android:layout_alignTop`
Comment: Are any of the colours you use white?


How to test median category of ordinal variable

Question: I have an ordinal variable with 6 categories. The first category that goes above 50% of cumulative frequency is called the median category. How should I test whether this category is truly a median category? Should I state the hypothesis as in this case, the cumulative frequency of the sixth category is at least 50% and alternative hypothesis such as the cumulative frequency of the fourth category is less than 50 %? Should I then proceed with testing proportion with a binomial test?
Answer: You do not say how the entries in your table arose. I explore two scenarios.
Assuming categories 1 through 6 are bins into which 44 values have been sorted: You have $12$ observations below the 5th bin and $16$ above. If there is a 50-50 chance of falling above or below that bin, then the probability that $12$ or fewer out of $12 + 16 = 28$ fall below is $0.2858.$
pbinom(12, 28, .5)
[1] 0.2857941

This is the P-value of a
test of the null hypothesis that observations not in the 5th bin are equally likely to fall above or below it. We cannot reject that null hypothesis at the 5% level.
Assuming that labels 1 through 6 are levels of a true categorical variable:  The $n=44$ ordinal observations x are
x = rep(1:6, c(2,2,3,5,16,16))
x
 [1] 1 1 2 2 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5
[23] 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6

median(x)
[1] 5

The median of the categorical variable is $5,$ and
there is no hypothesis to be tested.
Comment: The values are from a questionnaire survey, where each response category is the time period like once a day, once a week...


Prove Intersection of $\sigma$-algebras is a $\sigma$-algebra and the powerset is a $\sigma$-algebra

Question: Fix a set $\Omega$. A $\sigma$-algebra on $\Omega$ is a non-empty collection of subsets of $\Omega$ closed under taking complements and countable unions.
I'd like to prove that (1) for finite $\Omega$, $2^\Omega$ is a $\sigma$-algebra and that (2) the intersection of a family of $\sigma$-algebras is a $\sigma$-algebra. Are these proofs correct?

The def. says "non-empty collection" so the collection contains something and the complement of that something hence the whole things $\Omega$. Since it contains the whole things, it contains its complement, hence the empty set $\emptyset$. This guarantees that $2^\Omega$ and $\bigcap \mathcal{A_i}$ of $\sigma$-algebras $\mathcal{A_i}$ are non-empty.
(Stmt 1) Pf. $2^\Omega$ contains all subsets of $\Omega$. So it's closed under taking complements and countable unions.
(Stmt 2) Pf. Let $\{\mathcal{A_i}\}$ be a family of $\sigma$-algebras.

$A\in \bigcap \mathcal{A_i}\implies A\in \mathcal{A_i} \forall i\implies A^c \in\mathcal{A_i}\forall i\implies A^c\in \bigcap \mathcal{A_i}$
Let $A_j\in \bigcap \mathcal{A_i}$ for $j\in J$. Then $A_j\in \mathcal{A_i} \forall i \forall j$. Therefore $\bigcup A_j\in \mathcal{A_i} \forall i$. Hence $\bigcup A_j\in\bigcap\mathcal{A_i}$
Comment: Um, what is your question?
Comment: The post is tagged with `proof-verification`.
Comment: x @saadtaame That is a fact, not a question.
Comment: Ok sir, now it's a question.
Comment: what is $2^\omega$ ?
Comment: Notation for the powerset of $\Omega$.
Comment: From wiki there is another condition of countably intersection for the definition of a sigma-algebra, is this condition redundant? Why don't you need to prove it?
Answer: Your proofs are OK.  Well, maybe in (1) you should also state that $2^\Omega$ is nonempty.  Similarly in (2) show that $\bigcap \mathcal A_i$ is nonempty.
Comment: They are empty by def. They all contain $\Omega$ and $\emptyset$. Right? Question: by OK you mean that there are simpler proofs?
Comment: That is not stated in the definition.  But it is true, so should be mentioned in the solution.
Comment: The def. says "non-empty collection" so the collection contains something and the complement of that something hence the whole things. Since it contains the whole things, it contains its complement, hence the empty set.
Comment: Exactly right.  So include that in your solution.
Comment: Alright. Thank you for the time.
Answer: Your proof of statement 1 is nearly correct, you should also proof, as GEdgar mentioned, that the powerset is never empty.
This is quite clear from the definition if Omega is nonempty. If Omega is the empty set, then you need to proof a bit more
(look e.g. here: https://proofwiki.org/wiki/Power_Set_of_Empty_Set)
Point 1 of your proof of statement 2 is fine.
In point 2 of statement 2 you need to state that J is a countable index set and not an arbitrary, since sigma-algebras are closed only under countable unions.


Is PCG random number generator as good as claimed?

Question: I have a demand for extremely fast acceptable-quality random number generator (RNG). This means rand()%2 should not alternate between 0 and 1 (that totally kills the simulation, as in one problem I indeed to rand()%2 every second time rand() is called). In my simulation, speed is absolutely the most important criterion apart from rand()%2 not alternating between 0 and 1. So, my requirements in the order of importance are:

rand()%2 should have a high-quality output
The speed should be extraordinarily high
Statistical quality of the random number generator must be good (not that important)

I have found that permuted congruential generator (PCG) is faster than Mersenne Twister (MT), and Mersenne Twister is faster than e.g. minstd_rand. Both Mersenne Twister and PCG satisfy the rand()%2 requirement. The only generator I have found that is faster than MT and PCG is standard linear congruential generator (LCG) which has poor output for rand()%2.
For my application, I therefore believe that PCG is the best choice. But I'm starting to have some doubts about the statistical quality of PCG.
There is some marketing on the PCG website. However, PCG does not have any paper in a reputable scientific journal, the paper being just a preprint. Although it was stated that the reason for not accepting the paper was its length, this blog post says they missed some relevant literature.
However, Mersenne Twister has been published in a reputable journal.
So, my question is, can I believe the marketing on the PCG website? Is there a RNG that is a better choice when both performance and statistical quality are considered? Is there something in the literature that is better than PCG, which I believe might be the case due to the review comments of the PCG paper?
I'm planning to publish my results in a reputable scientific journal, so a RNG that has been published in a reputable scientific journal (so that I could cite it) would be appreciated, but not if the performance is much poorer than PCG.
Comment: @Tim this question is about non-cryptographical generators. Those cannot be used for cryptography.
Comment: Could you please spell out your acronyms?
Comment: Wouldn't it fit https://crypto.stackexchange.com/ better?
Comment: There are lots of generators that are much faster than the Mersenne Twister that are also high-quality, surely high quality enough for your purposes, so don't feel those are your only two choices!
Answer: Other people have looked at the statistical qualities of the PCG generators and found them to be good, see for example https://lemire.me/blog/2017/08/22/testing-non-cryptographic-random-number-generators-my-results/. On that page you will also find references to other RNGs, that are all faster than MT. If being published and raw speed are important for you, you could use one of the RNGs from http://xoroshiro.di.unimi.it/, but note that in the + or * versions the lowest two bits are of problematic quality and are the reason why these generators fail some tests. So you should not use rand() % 2 to get a random boolean. You could use a sign test instead. The ** versions should produce high quality output for all bits though.
Comment: @juhist That makes sense if 32 bits of randomness are enough for your needs (besides random booleans).
Comment: Thanks! I tested xoroshiro128plus. In microbenchmarks, it is faster than PCG32 but for some strange reason, in the whole application test it makes the application run slightly (about 6%) slower than PCG32... Not sure why. Actually, now that I took a second look at std::uniform_int_distribution, it isn't using rand()%2 but division instead. An older version of my code used rand()%2.
Comment: Now when testing it again, I observed that 100 million 32-bit divisions take 0.29 s, whereas 100 million 64-bit divisions take 0.84 s. I could make a wrapper around xoroshiro128+ to make it return two 32-bit integers instead of one 64-bit integer...
Answer: PCG generators are more or less fine if you use them single-stream in a single application (albeit they will be very slow if you use a state larger than 64 bits). In all other situations, they should be avoided. You can find a very detailed discussion here: http://prng.di.unimi.it/pcg.php .
As for benchmarking: a PCG32 generator fits a single register due to the small state size (64 bits). xoroshiro128+ (or ++) uses more registers, and this takes time (they must be loaded and saved). In microbenchmarks this will not show up because the compiler keeps all the state in registers (which is why I always suggest to benchmark inside an application). Note, however, that a period of $2^{64}$ bits is really too short for any scientific application. You should have a period at least large as the square of the number of outputs you are using.
Comment: Detailed rebuttal from the PCG author:
https://www.pcg-random.org/posts/on-vignas-pcg-critique.html
Comment: Could you please elaborate the "You should have a period at least large as the square of the number of outputs you are using."?
Comment: This is a standard consideration from the literature. For example, imagine you have a 64-bit generator using 64-bit values, and that the generator can emit all possible values. This means that as you emit values, you will see a duplicate only after $2^{64}$ outputs. But you should see duplicates roughly after $2^{32}$ steps (a little bit more, see the distribution for the Birthday Paradox). So if you use less than the square root of the period, you'll never see this statistical flaw.


I can't move blocks

Question: I currently have a site that has quite a lot of blocks (about 120 in 1 region and many others in other regions).
Recently the Block admin page stopped working for me. I can't add any blocks through that screen, however when I go to the block detail page, I can.
All new blocks are handed the weight 0, and I cant change that (not by drag and drop, neither by manually entering the weight).
Anyone who know how I can fix this? Is it because there are too many blocks?
Comment: What does JavaScript console say about it? Use Google Chrome, Firebug plugin in Firefox, or similar tool in a browser you are using. Just not IE, please.
Comment: The javascript console is clean, no errors or warnings.
Answer: 120 blocks in one regions seems to be excessive, you may want to attempt to consolidate them into a custom block and use context to set those.  Also may want to look at creating multiple regions that reside in the same area
Answer: I had a similar issue, where I couldn't change the weight of my blocks and all new blocks had a weight of 0. I deleted a bunch of old blocks (about 50) and I was then able to assign weight to them again. I assume the issue was I had too many.
Comment: Yes it looks like this. My plan is to delete the old ones and create some extra regions. It seems like the limit is only per region. Thanks for your answer!

I can't move blocks


Apache Server shutting down, whats the reason?

Question: I'm quite new to Linux so I don't really know how to fix this problem.
I have a vServer running on CentOS, managed by Plesk 10. My website shuts down randomly for a few hours now.
The error in the apache log says the following:
<code>[Sun Aug 19 21:31:00 2012] [notice] caught SIGTERM, shutting down
[Sun Aug 19 21:32:21 2012] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Sun Aug 19 21:32:22 2012] [notice] Digest: generating secret for digest authentication ...
[Sun Aug 19 21:32:22 2012] [notice] Digest: done
PHP Warning:  Directive 'safe_mode' is deprecated in PHP 5.3 and greater in Unknown on line 0
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] RSA server certificate CommonName (CN) `Parallels Panel' does NOT match server name!?
[Sun Aug 19 21:32:22 2012] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Sun Aug 19 21:32:22 2012] [notice] Apache/2.2.15 (Unix) DAV/2 mod_fcgid/2.3.6 mod_ssl/2.2.15 OpenSSL/1.0.0-fips configured -- resuming normal operations
</code>
Comment: It is receiving `SIGTERM`. Find out what is sending that signal.
Answer: Something is sending it sigterm, says the first line.  That will always originate externally.  Perhaps there is a cronjob set to restart it periodically?  Perhaps there is a problem with plesk?  It is impossible to say from that log what has happened, except that something issued a command to shut it down.
It's possible, given that it is doing init stuff after it's stopped, that a watchdog is assuming it is hung and restarting it.  If that's the case, and you notice it's down for a while, check that you have enough entropy in your entropy pool or change the random device to /dev/urandom (possible security weakness if you do that).  After it is started, apache will often block and wait for random data (for SSL) before servicing any requests, SSL or not.
Comment: Problem was that php didn't have enough Memory assigned in Plesk.
Comment: So something wrong with plesk, then :P


Do left-handed guitarists view the same patterns as right-handed?

Question: Do left-handed players see the same scale formations, chords, patterns as right-handed, or is it just as simple as seeing the mirror-opposite?  What about the ones that play left-handed and string the instrument with the high E on top - it's always fascinated me , but I've never really seen any interviews that described how they view the neck.
Examples:Toni Iommi;Dick Dale; Al Mckay;Otis Rush;Freddie King;Hendrix
Answer: Yes, they do.
The main reason for that is that nobody will rebuild tons of literature just to mirror the shapes. Actually, it's not a big problem, it's just a matter of getting used to.
When I, right handed guitarist, just learned how to read tablature, it seemed very confusing, that thickest (upper) string is at the bottom. But it took not more then 30 minutes of adjusting and now I do not notice that at all - it just seems natural.
Also, I have read about the experiments, where people wore special glasses that made everything look upside down. After a while their brain have adjusted to it and they just do not notice the difference.
Answer: In general, yes: the patterns for scales and chords are the same for left-handed guitarists as they are for right-handed guitarists because they re-string the guitar so that the low-E string is on top and the high-E string is on the bottom, as it is for right-handed players.  Hendrix, for example, took right-handed guitars and flipped them upside-down to play left-handed, but he also re-strung the guitar so that the order of the strings from top to bottom was the same.
The most famous exception is Albert King, who played right-handed guitars upside-down without re-stringing them, so that the low-E was on the bottom and the high-E on top.  This inverts all of the patterns, which isn't so much a problem for the brain as it is for the fingers.  The standard chord patterns work well for certain fingerings, but when you invert them, they don't work as well, since our fingers are not all the same length.
As an example, consider the B7 chord in first position.  Here it is on a normally-strung guitar:
<code>$A.2.$D.1.$G.2.$B.0.$e.2
</code>
Now here it is, if the strings are reversed (like if you took a left-handed guitar and flipped it upside-down without re-stringing it):
<code>$E.2.$A.0.$D.2.$G.1.$B.2
</code>
Try fingering that.  I found it very difficult to do.
Comment: Dick Dale does the same thing.
Answer: I have played that way (right-handed stringing, played upside down) since I was given a guitar at the age of 10. Being left-handed, I just picked it up and played it, not realising that the stringing was "wrong" for me.
When my best friend (right-handed) got a guitar a few months later, I could play his and he could play mine, which was very useful. The chord diagrams look exactly right for the way I play.
I played in bands using a electrified acoustic guitar. When I bought my first solid electric (an Antoria Gibson SG copy) it was left-handed, so I thought I'd try to learn to play "properly" left-handed. This meant throwing away over 10 years of playing experience so I abandoned the idea and converted the SG copy to right-handed stringing. This meant fitting a new nut and reversing the angle of the bridge. I used that guitar for many years.
Nowadays, I have a left-handed Strat which was easy for a local dealer to convert because the bridge has enough adjustment in it. It just needed a new nut and a new set of strings. I also recently bought a genuine SG Standard, again left-handed. I ordered a new scratch plate for it with the post holes for the bridge reversed - I drew round the existing one then turned it upside down to get the new position for the bridge posts then send it to a company that makes specialised scratch plates. It was fairly cheap and a quick turnaround. I then gave the guitar and the scratchplate to the same dealer who converted it.
I have not removed the scratchplate to see how it looks underneath but the dealer said that he's fill the old bridge post holes with mahogany dowling or similar, then re-drill them. Anyway, it plays beautifully.
Any questions, feel free to contact me on email@example.com.
Mike Rex
Edinburgh
Scotland
Answer: Yes!  I am a left handed guitarist!  And yes i look at right handed diagrams.  It is basically identifying your fingers.  Remember!  the index finger is always number 1, the middle number 2, ring number 3, and pinky 4.  You cannot go wrong!!!


Issues with EC2 Elastic Load Balancer DNS and routing

Question: We're trying to run a fairly straightforward setup on Amazon EC2 - several HTTP servers sitting behind an Amazon Elastic Load Balancer (ELB).
Our domain is managed in Route53, and we have a CNAME record set up to point to the ELB.
We've experienced some issues where some - but not all - locations are intermittently unable to connect to the load balancer; it seems that this may be the resolution of the ELB's domain name.
Amazon support advised us that the underlying Elastic IP of the load balancer has been changing, and that the problem is that some ISPs' DNS servers do not honour the TTL. We're not satisfied with this explanation, because we replicated the problem using Amazon's own DNS servers from an EC2 instance, as well as on local ISPs in Australia and via Google's DNS server (184.108.40.206).
Amazon also confirmed that during the period where we noticed down time from some locations, traffic passing through the ELB was down significantly - so the problem is not with our endpoints.
Interestingly, the domain seems to resolve to the correct IP on the servers that cannot connect - but the attempt to establish a TCP connection fails.
All the instances attached to the ELB have been healthy at all times. They're all
Does anyone know how we might go about diagnosing this problem more deeply? Has anyone else experienced this problem with the Elastic Load Balancer?
Thanks,
Comment: I should add as another note - despite this seemingly being potentially related to DNS or routing, as far as we can tell our domain *always* resolves to the correct EIP - running the `host` utility resolves to the same address on systems where we can connect and systems where we can't.
Answer: I found this question while Googling for how to diagnose Amazon Elastic Load Balancers (ELBs) and I want to answer it for anyone else like me who has had this trouble without much guidance.
ELB Properties
ELBs have some interesting properties. For instance:

ELBs are made up of 1 or more nodes
These nodes are published as A records for the ELB name
These nodes can fail, or be shut down, and connections will not be closed gracefully
It often requires a good relationship with Amazon support ($$$) to get someone to dig into ELB problems

NOTE: Another interesting property but slightly less pertinent is that ELBs were not designed to handle sudden spikes of traffic. They typically require 15 minutes of heavy traffic before they will scale up or they can be pre-warmed on request via a support ticket
Troubleshooting ELBs (manually)
Update: AWS has since migrated all ELBs to use Route 53 for DNS. In addition, all ELBs now have a all.$elb_name record that will return the full list of nodes for the ELB. For example, if your ELB name is elb-123456789.us-east-1.elb.amazonaws.com, then you would get the full list of nodes by doing something like dig all.elb-123456789.us-east-1.elb.amazonaws.com. For IPv6 nodes, all.ipv6.$elb_name also works. In addition, Route 53 is able to return up to 4KB of data still using UDP, so using the +tcp flag may not be necessary.
Knowing this, you can do a little bit of troubleshooting on your own. First, resolve the ELB name to a list of nodes (as A records):
$ dig @ns-942.amazon.com +tcp elb-123456789.us-east-1.elb.amazonaws.com ANY

The tcp flag is suggested as your ELB could have too many records to fit inside of a single UDP packet. I'm also told, but haven't personally confirmed, that Amazon will only display up to 6 nodes unless you perform an ANY query. Running this command will give you output that looks something like this (trimmed for brevity):
;; ANSWER SECTION:
elb-123456789.us-east-1.elb.amazonaws.com. 60 IN SOA ns-942.amazon.com. root.amazon.com. 1376719867 3600 900 7776000 60
elb-123456789.us-east-1.elb.amazonaws.com. 600 IN NS ns-942.amazon.com.
elb-123456789.us-east-1.elb.amazonaws.com. 60 IN A 188.8.131.52
elb-123456789.us-east-1.elb.amazonaws.com. 60 IN A 126.96.36.199

Now, for each of the A records use e.g. curl to test a connection to the ELB. Of course, you also want to isolate your test to just the ELB without connecting to your backends. One final property and little known fact about ELBs:

The maximum size of the request method (verb) that can be sent through an ELB is 127 characters. Any larger and the ELB will reply with an HTTP 405 - Method not allowed.

This means that we can take advantage of this behavior to test only that the ELB is responding:
$ curl -X $(python -c 'print "A" * 128') -i http://ip.of.individual.node
HTTP/1.1 405 METHOD_NOT_ALLOWED
Content-Length: 0
Connection: Close

If you see HTTP/1.1 405 METHOD_NOT_ALLOWED then the ELB is responding successfully. You might also want to adjust curl's timeouts to values that are acceptable to you.
Troubleshooting ELBs using elbping
Of course, doing this can get pretty tedious so I've built a tool to automate this called elbping. It's available as a ruby gem, so if you have rubygems then you can install it by simply doing:
$ gem install elbping

Now you can run:
$ elbping -c 4 http://elb-123456789.us-east-1.elb.amazonaws.com
Response from 220.127.116.11: code=405 time=210 ms
Response from 22.214.171.124: code=405 time=189 ms
Response from 22.214.171.124: code=405 time=191 ms
Response from 220.127.116.11: code=405 time=188 ms
Response from 22.214.171.124: code=405 time=190 ms
Response from 220.127.116.11: code=405 time=192 ms
Response from 22.214.171.124: code=405 time=187 ms
Response from 188.8.131.52: code=405 time=189 ms
--- 188.8.131.52 statistics ---
4 requests, 4 responses, 0% loss
min/avg/max = 187/163/210 ms
--- 22.214.171.124 statistics ---
4 requests, 4 responses, 0% loss
min/avg/max = 188/189/192 ms
--- total statistics ---
8 requests, 8 responses, 0% loss
min/avg/max = 188/189/192 ms

Remember, if you see code=405 then that means that the ELB is responding.
Next Steps
Whichever method you choose, you will at least know if your ELB's nodes are responding or not. Armed with this knowledge, you can either turn your focus to troubleshooting other parts of your stack or be able to make a pretty reasonable case to AWS that something is wrong.
Hope this helps!
Comment: Thanks for the great answer. We originally figured out most of this through trial and error, but this will be a handy reference.
Answer: The fix is actually simple: Use an A record rather than a CNAME in Route53.
In the AWS Management Console, choose "A record" and then move the radio button labeled "Alias" to "Yes."  Then select your ELB from the dropdown menu.
Comment: You'd have to use a CNAME if your DNS was hosted someplace other than Route53.  But A record aliasing is a feature that is specific to Route53 and is intended to solve the exact problem you're encountering.  The [Route53 docs](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingAliasRRSets.html) explain it in greater depth.
Comment: I don't understand the rationale behind this fix. Amazon's documentation for the ELB specifically says that a `CNAME` record should be used. What would be the benefit of an `A` record / what is changing here?
Comment: It's called "Alias Target" as opposed to an A record. http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/HowToAliasRRS.html
Comment: @jamieb Can you provide a link to that piece of documentation?
Answer: There are some potential solutions you could try in this AWS developers forum. https://forums.aws.amazon.com/message.jspa?messageID=387552.
For example:
potential fix #1

We had a similar problem when we moved to ELB, we resolved this by
  reducing the name of our ELB to a single character. Even a 2 char name
  for ELB caused random problems with network solutions DNS resolutions.
Your ELB's DNS name should be something like ->
  X.<9chars>.us-east-1.elb.amazonaws.com

potential fix #2

I'm the original poster. Thanks for all the responses. We were able to
  reduce the frequency with which we experienced DNS issues by setting
  the TTL very high (so they would cached by non-Network Solutions
  servers). However, we were still getting enough problems where we just
  couldnt stay with Network Solutions any longer. We thought of moving
  to UltraDNS based on good reports on the service, but it looked like
  Route 53 (which uses UltraDNS under the covers, it would appear) would
  be cheaper for us. Since switching to Route 53, we have no more DNS
  issues, and our ELB names can be nice and long too.

There were other things to try in that post but those seem to be the best leads.
Comment: Thanks for the suggestions. Unfortunately it seems that the problem lies purely in the DNS resolution of the hostname for the ELB, not for our record that aliases to it. Our record always resolves to the ELB's hostname properly.
Comment: Did @jaimieb's fix solve the problem?
Comment: If I understand you correctly then the problem is that you have CNAME/ANAME records that resolve to a CNAME/ANAME record ELB, and your part is resolving just fine, no performance issues, but once you get to the ELB's DNS records the performance problems show up?
Comment: @slm - potential fix #1 does not help. I would recommend removing it from the post.


Reduce scrolling lag when using server side images for Tableview

Question: I currently have a tableView which can display any number of results. each row has an image which is pulled from a server. Assuming the Server is fast and the device has a reliable connection how can i reduce the lag when scrolling through the list.
I looked at loading the images on the background thread and this has definitely improved things however you can clearly see the images rendering as you scroll up and down.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {

      static NSString *CellIdentifier = @"Cell";
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

      if (cell == nil)
      {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      }

      if (tableView == self.searchDisplayController.searchResultsTableView)
      {
         cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
      }
      else
      {
         cell.textLabel.text = self.TableData[indexPath.row];
      }
      _ImageURL = self.ImageData[indexPath.row];
      dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
      dispatch_async(queue, ^
      {
          UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_ImageURL]]];
          dispatch_sync(dispatch_get_main_queue(), ^
          {

              [[cell imageView] setImage:image];
              [cell setNeedsLayout];
          });
      });
      return cell;
 }

Is there any method to improving this or is it more likely to be a constraint of the server speed and device bandwidth. My server is no Facebook server but its a decent paid one that i use for other applications.
Also since moving the images to the background task i notice that now and again a row will miss loading an image, any thoughts on this?
Comment: What you're doing is totally wrong. You must supply a placeholder and return immediately. Later you can reload the table when you have the image. Please do a search, as this is one of the most commonly asked of all questions.
Answer: I recommend you to use SDWebImage library, everything will be handled for you, from async downloads to caching management.
Here is  the link for downloading and documentation.
You can also use Facebook's  AsyncDisplayKit  if you don't need image caching.
Good Luck.


Does changing the home directory of www-data break anything (esp. apache)?

Question: We're running on Ubuntu and have an Apache2 webserver with some apps that require cron-jobs installed.
The cron jobs occasionally send mails which of course goes to the www-data user. The home dir of that user is /var/www but for security reasons that directory is owned by root (maybe this is a bad idea...) which makes it difficult to use www-datas account.
I'm considering changing www-datas home directory to /home/www-data to make things easier.
Would changing the home directory of the Apache default user break anything?
Comment: Consider the alternative: Use an email alias to forward mail for www-data to another user.
Comment: I have considered that, and I might still go that route, but there are also other things besides mail, like all the .-files for settings etc.
Comment: Did any of these answers solve your question, or did you find a solution yourself?
Comment: Well, I got no definite answer before trying it out myself. And it didn't break anything ;-) So I have accepted the simplest answer that says so.
Answer: Changing the home dir for that user wont break Apache. Apache will have a root www path set so make sure you dont delete or change permissions for that folder (or folders for multiple sites).
Answer: No it wouldn't. I have set up several VHOST's where the document root directories are in my HOME directory. The tree structure is similar to this
HOME

PUBLIC_HTML
Domain1
Public
Private
log
cgi-bin
backup

Domain2
Public
Private
log
cgi-bin
backup

Since you have an existing site ensure that you change the vhost configuration files to point to the appropriate document root's, change the logs to write to the log directory under the respective domain directory that you have just created instead of var/log. I usually create a separate .conf file for each vhost rather than having a single lengthy default conf file. It gives me a great deal of flexibility to manage my sites.


Ability to flag each uploaded image separately after doing multiupload

Question: I want to create some kind of photography website where users will be able to flag some images for later use.
This is the user story:

Photographer upload images of the client event on the website
Page with a gallery is created
A client comes to the gallery page and marks few items using Flag module
A view is created with a list of flagged images so Photographer can get a list of images for further manipulation

The problem is if I use multiple image field there is no way to use Flag module as it works only with nodes, and I have all images in a single node.
There is this issue in Flag module where it says why is not possible.
So I'm wondering if there is a way to convert images to nodes after creating an initial node that contains all of the images?
Or do you have any other suggestion how to handle this?
Comment: Does your question really have anything with ajax?
Comment: Well, i was under impression that some solution would work with Ajax, and now Ajax is also used for flags.
Answer: It's easily possible to create a node per uploaded picture using a custom module. Alternatively, you could use https://www.drupal.org/project/node_gallery to let users upload every picture to its node from the very beginning.
Answer: I kinda went on another way, instead of doing this conversion I actually just used Media module which is now in the Core, and with that, I get every image as a single entity that is then able to be flagged.
So

Use Media with Entity Browser instead of regular Image Field
Create view block and placed it in the content with contextual filters to take current ID from URL which then lists all images + flags
Hide images on manage display in the content type so I don't get duplicates
Create another View with flag relationship to list only flagged content

And that did the trick, I now have a gallery on a page where every image has a flag under it, and I'm able to export only flagged ones.


Problema ao tentar inserir alerta de maioridade em loja online

Question:

Comment: Sobre o erro, remova um cifrão `$$` correto seria `$`; O segundo `innerHTML` está faltando o sinal de `+`, dessa forma ele está apenas reescrevendo o código interno do elemento; É necessário "escapar" as aspas de seu código (de ambos `innerHTML`), por exemplo `"<div id=\"master\" …"`
Comment: Dica: Adicionar múltiplas *tags* só por adicionar, não vai ajuda-lo e provavelmente outros membros podem pedir o fechamento da pergunta.
Answer: Como o @ValdeirPsr falou...
Na linha
var home_principal = $$(".cms-index-index")

Retire um dos $, ficaria assim:
var home_principal = $(".cms-index-index")

No innerHTML te 2 problemas:
1- Em
home_principal[0].innerHTML+="
Este site oferece conteúdo impróprio para menos de 18 anos
";
home_principal[0].innerHTML="
Tenho mais de 18 anosTenho menos de 18 anos
"

Na segunda linha você está sobre escrevendo o innerHTML da primeira linha
home_principal[0].innerHTML+="
Este site oferece conteúdo impróprio para menos de 18 anos
";
home_principal[0].innerHTML="
Tenho mais de 18 anosTenho menos de 18 anos
"

2- Quando você quer usar aspas dentro de outras aspas precisa "escapar" as aspas internas com \ ou mudar as aspas duplas por aspas simples,
ou seja, por fora use " e dentro ' ou vice-versa.
Com os dois erros do innerHTML corrigidos ficaria assim:
home_principal[0].innerHTML+="
Este site oferece conteúdo impróprio para menos de 18 anos
";
home_principal[0].innerHTML+="
Tenho mais de 18 anosTenho menos de 18 anos
"

Aspas duplas para marcar início e fim da string e aspas simples para marcar início e fim dos atributos das tags HTML


Did any pianist in history ever sight-read one of Liszt's Transcendental Études?

Question: Liszt was known to be able to sight-read any piece, even Chopin's Etudes Opus 10 and Grieg's Piano Concerto, both Piano and Orchestral Part.
Since Liszt also composed some Études himself, I was wondering if anyone ever sight-read them?
One thing I always thought is that the reason Liszt was able to sight-read Chopin's Etudes was that they are very chromatic and predictable in their chord progressions.
I am specifically referring to his Transcendental Études since they are way less predictable and dissonant (take for example, Eroica) than, for example, his "Grand Études de Paganini" (The Paganini Etudes such as La Campanella and Caprice 24), since those are way more chromatic and predictable in their chord progressions.
After some research online I didn't find anything about anyone ever sightreading any of his Études, which is why I came here.
Did any pianist in history ever sight-read one of Liszt's Transcendental Études?
Comment: Having heard the music would affect how you sight-read it.
Comment: Hm, I'm not sure how often sight-reading "makes the news" in the written record. Some folks do it every day…
Comment: You're setting up a problem specifying such famous pieces. How would your really know the person has never seen the music?
Comment: Probably lots of pianists have tried. But how many notes did they get right?
Comment: You are not going to be able to play it if you cannot sight-read it.
Comment: @NeilMeyer - Your first sight-read could be garbage or way too slow and you can eventually play that Transcendental Etude at concert quality. The implication in the phrase "sight-read any piece" is that the first sight-read is of passable accuracy and speed compared to concert-quality versions.
Answer: Sure. In 1977 or so, Bob Spano, who is now the Music Director of the Fort Worth Symphony Orchestra (and also a fine pianist), was this crazily talented high school kid who was studying piano at IUSB (as was I, although I was a considerably less talented college kid). One semester at juries, he wasn't happy with anything he had been working on, so in a monumental act of chutzpah he walked into his jury, opened up Liszt's Transcendental Etudes, and sight read one of them. One of the profs said "so that's how Liszt wrote it, Bob?" Bob grinned and said "Every note."
So yeah, he sight read it. No, it wasn't flawless, but he did pretty well convey the music without too much fakery. I believe he got a B.
Comment: By any chance, was it the F major Transcendental Etude ("Pastorale")? I've read it's semi-widely considered the easiest of the Transcendental Etudes.
Comment: @Dekkadeci I think not. It was a more stormy sounding one. I can't say much more, as it was 45 years ago.


How to access rules condition values in the rule event?

Question: I have created a rule (using Rules) in which I added 3 conditons. Now I want to access the conditions values in the action that on which condition the action is performed.
I am attaching the screenshot :

As shown in the screenshot, I want to access
<code>[commerce-license:type], Data value: Diamond Subscription
</code>
How can I achieve this ?
Comment: Could it be that "event" should be "action" in your title? If so please edit your title. If not: why doesn't it show up anywhere in your actual question?
Comment: If you code conditions on a rule, they all have to be true before the rule is executed. So the value will always be "Diamond Subscription". If you access the value within the rule you'll always get the same result. Is that what you want?
Answer: I'm not sure if it'll be the only thing you need to do to get this to work, but I think you may get closer (= simplify your challenge) by ALSO using the Conditional Rules module. Some more details about this module (from its project page):

... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):


Is There a Conjugate Prior for a Multivariate Hypergeometric Likelihood?

Question: I am working on a problem using a multivariate hypergeometric likelihood. The multivariate hypergeometric distribution does not belong to the exponential family of distributions, so (to my knowledge) we cannot guarantee that a conjugate prior exists.
However, Wikipedia claims on its page about conjugate priors that the univariate hypergeometric distribution is conjugate with a beta binomial. This post shows that the posterior in the univariate case is for M-x, the "number of target individuals in the population shifted by the number observed in the sample".
Does the multivariate hypergeometic distribution have a conjugate prior? My hunch is that it would be the multivariate form of the beta-binomial, the dirichlet-multinomial. However, I don't know how to show that analytically. If it does have a conjugate prior, what would the posterior's hyper-parameters be?
Comment: What are the parameters of the multivariate hypergeometric on which you want to use a conjugate prior? Using [the standard definition](https://en.wikipedia.org/wiki/Hypergeometric_distribution#Multivariate_hypergeometric_distribution), with the $K_i$'s being the parameters there is no conjugate prior.
Comment: The $K_i$'s would be the parameters. Is there a simple explanation as to why? Or has one just not been found yet?
Comment: As you wrote, this distribution is not from an exponential family, hence cannot enjoy a conjugate prior.
Answer: According to this compendium of conjugate priors, the prior for the multivariate hypergeometric distribution's parameters is a Dirichlet-Multinomial distribution.
(The fact that the hypergeometric distribution does not belong to the exponential family does not preclude the possibility for conjugate prior. Simply, its existence is not guaranteed.)


Why does log-linear analysis seem to ignore the Poisson regression equidispersion assumption?

Question: As far as I understand it, log-linear analysis is based on the use of a Poisson regression. This is what I understood from various online resources, like this online tutorial or this text whose intro says: "In this chapter we study the application of Poisson regression models to the analysis of contingency tables. This is perhaps one of the most popular
applications of log-linear models [...]".
The wikipedia article on log-linear analysis lists three assumptions for log-linear analysis:

The observations are independent and random;
Observed frequencies are normally distributed about expected frequencies over repeated samples [...]
The logarithm of the expected value of the response variable is a linear combination of the explanatory variables. [...]

However, unless I misread it, it does not mention the assumption that the mean should equal the variance (aka equidispersion), as usually assumed when using a Poisson regression:

Mean=Variance By definition, the mean of a Poisson random variable must be equal to its variance.

What am I missing?
Can I simply ignore the equidispersion assumption when using a Poisson regression for a log-linear analysis? Isn't there a risk, for example, that coefficients detected as significant will actually be non-significant -or vice versa?
Or is it implied that I should use an alternative when the equidispersion assumption is not met, like negative binomial or generalized Poisson regressions?
Thanks,
Answer: Quoting from Section 4.3.3 of the second edition of Agresti's "Categorical Data Analysis":

Overdispersion is common in the modeling of counts. When the model for the mean is correct but the true distribution is not Poisson, the ML estimates of model parameters are still consistent but standard errors are incorrect.

He continues to describe both negative-binomial and quasi-likelihood approaches to deal with overdispersion. So yes, for these models it (should be) implied to proceed in a way that takes into account the relationship between fitted values and variance.
The omission of this issue in introductory explanations of count modeling isn't really different from starting with the assumption of homoscedasticity and a normal error distribution in linear regression. You start from the simple, then build from there.


What is this chord in Schubert's D. 531?

Question: Consider following extract from Schubert's Der Tod und das Mädchen (D. 531) :

I assume that the indicated chord in the penultimate bar can be seen as a transition between the chords of D major and A major (voice leading). But can it also be seen as a real chord? Which chord would it be?
Answer: It's a suspended chord - A7sus4, sometimes called A11. The bass is as the penultimate chord, A, there's no M3, but a sus (D) which drops to M3 (C♯), to end on a perfect cadence on the key chord, D major. Guessing that it starts in the parallel key of Dm.
Comment: Yes, it starts in the key of D minor (score: http://ks4.imslp.info/files/imglnks/usimg/f/f1/IMSLP16210-SchubertD531_Der_Tod_und_das_M%C3%A4dchen.pdf).
Answer: In older theory it is an 11th. The notes written are the first (A), fifth (E), 7th(G) and 11th (D).


Recording with both a Multi-Effects Pedal and a Modelling Amplifier at the same time

Question: I want to achieve a setup where I have a guitar plugged in to a multi-effects pedal (the Zoom G1XON to be precise) going to a modelling amp (the Marshall Code 25); I want to then use the modelling amp as a USB interface to record my guitar directly into a DAW. If I do this, will I still be able to record the effects on the multi-effects pedal even though it in itself is not connected to the computer directly?
I ask this because I already have a Zoom G1XON (which unfortunately doesn't allow for direct USB recording), and am looking to purchase a modelling amplifier that lets me record directly into my computer. I know that the modelling amplifier also comes with some built in effects, but I would like to be able to use some pedal based effects (like the wah) from the Zoom G1XON while recording. I also find that the effects pedal has some effects that are not found on the modelling amplifier and would like to be able to incorporate some of those effects while recording.
Any help would be appreciated. Thanks!
Comment: Still not sure why you think the marshal might strip the zoom effects. Even if the USB-to-daw audio was the "clean, untouched" input that the Marshal receives (bypassing all Marshall effects and modeling), that input is from the ZOOM.
Comment: If you are plugging the guitar into the zoom, and then the zoom into the marshal, why wouldn't you hear the zoom effects?
Comment: I know I would hear it while playing through the amp, but I am not sure this would be true if I try to record the sounds I'm getting using the amp as a USB interface.
Answer: Because the signal going to the amp has the effects already applied by the Zoom, yes of course you can do this. The Marshall will apply the amp model - it cannot strip the effects off as all it receives is the audio.


Filtrar lista jquery datatble no evento enter

Question: Quanto instancio: myTable = $('#dynamicTableDesc').DataTable();
Ao tentar chamar a função:  myTable.fnFilter(this.value); da erro myTable.fnFilter is not a function e ao chamar: myTable.ajax.reload(); funciona perfeitamente.
Já quando instacio: myTable = $('#dynamicTableDesc').dataTable();
Com d minúsculo.
Ao tentar chamar a função:  myTable.fnFilter(this.value); funciona e ao chamar: myTable.ajax.reload(); não funciona.
O que devo fazer para fazer funcionar?
Código Completo:
    myTable = $('#dynamicTableDesc').DataTable({
                    sAjaxSource: "/@controller/List",
                    bServerSide: true,
                    bPaginate: true,
                    pageLength: 50,
                    dom: '<"html5buttons"B>lTfgitp',
                    buttons: [
                        //{ extend: 'copy' },
                        //{ extend: 'csv' },
                        { extend: 'excel', title: '@titulo' },
                        { extend: 'pdf', title: '@titulo' },
                        {
                            extend: 'print',
                            customize: function (win) {
                                $(win.document.body).addClass('white-bg');
                                $(win.document.body).css('font-size', '10px');
                                $(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
                            }
                        }
                    ],
                    aoColumnDefs: [
                            { bSortable: false, aTargets: [-1] },
                            { bSearchable: false, aTargets: [-1] },
                            {
                                mRender: function (data, type, row) {
                                    var id = data;
                                    var html = "";
                                    html += "";
                                    html += "";
                                    html += "";
                                    return html;
                                },
                                aTargets: [-1]
                            }
                    ],
                    fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                        $(nRow).attr("id", aData[aData.length - 1]);
                        return nRow;
                    }

                });
                $('.dataTables_filter input')
                    .unbind()
                    .bind('keyup',
                    function (e) {
                        if (this.value.length == 0) {
                            myTable.fnFilter('');
                        } else {
                            if (this.value.length >= 3 && e.keyCode == 13) {
                                myTable.fnFilter(this.value);
                            }
                        }
                    });

myTable.ajax.reload();

Comment: Coloque mais sobre seu código. Você está tentando fazer um filtro através de um campo `input` ?
Comment: @WéllingthonM.deSouza como citei, meu problema esta sendo na instancia do DataTable. O filtro funciona se eu instanciar ele com d minusculo, mas o reload para de funcionar. Se eu instanciar com D maiúsculo o reload funciona mas a busca não funciona.
Comment: quando pedimos para que de mais detalhes sobre o código, é porque temos que analisar como ele esta sendo usado pois não tem como adivinha as coisas, mais mesmo assim vou chutar uma resposta independente de estar errada.
Comment: Desculpe.. postei o código todo!
Comment: Creio que a resposta seja a solução
Answer:
Na verdade, a confusão aqui é sobre a diferença entre $().dataTable() que você está usando e retorna um objeto jQuery e a antiga DataTables API e $().DataTable() que retorna a nova instância da API. ( Tradução livre )
Fonte: Forum DataTables em Inglês

Sabendo-se isso, para que o método reload() funcione chame do seguinte jeito:
myTAble.api().ajax.reload();

Veja que no manual ao lado direito há uma Nota de atualização explicando a diferença entre as versões.
Comment: Perfeito cara. obrigado!


Calculating fluxintegral out of the surface $1-x^2-y^2$

Question: I am trying to calculate the flux integral of the vector field
$$
\vec{F} = (x,y,1+z)
$$
Out of the surface $z=1-x^2-y^2$, $z\geq 0$
Answer : $\frac{5\pi}{2}$
I begin by defining a vector that traces out the surface and calculate the cross product of its derivate to get normal vector.
$$
\vec{r} = (x,y,1-x^2-y^2)\\
\vec{r}_x\times \vec{r}_y = (2x,2y,1)
$$
Next, I calculate the corresponding double integral using polar coordinates:
$$
\iint \vec{F} \cdot \hat{n}dS = \iint_D\vec{F}\cdot\vec{n}dxdy = \iint_D2+x^2+y^2dxdy\\
=\int_0^{2\pi}\int_0^{1}(2+r^2)*rdrd\theta \neq \frac{5\pi}{2}
$$
Where am I going wrong?
Answer: Isn't $\vec F \cdot (\vec r_x\times \vec r_y) = 2x^2+2y^2+1+1-x^2-y^2 = 2+x^2+y^2$?
Answer: You should consider that $ds$=$\frac{dxdy}{\sigma}$ and thus projecting the whole surface on the XOY plane where $\sigma$=$|\vec n . \vec k|$ and $\vec n$ is the unit vector that is in this case $\vec n$ = $\frac{\vec grad(S)}{||\vec grad(S)||}$ = $\frac{2x\vec i + 2y\vec j + 2z\vec k}{\sqrt{4x^2 +4y^2 +4z^2}}$=$\frac{x\vec i + y\vec j + z\vec k}{\sqrt{x^2 +y^2 +z^2}}$=$\frac{x\vec i + y\vec j + z\vec k}{1}$ where $x^2 +y^2 +z^2=1$ and so you can evaluate your integral.
$$
\iint \vec{F} \cdot \hat{n}dS = \iint_D\vec{F}\cdot\vec{n}\frac{dxdy}{\sigma} = \iint_Dx^2+y^2+z(1-z)\frac{dxdy}{z}=\iint_D \frac{x^2+y^2-(1-x^2-y^2)+\sqrt{1-x^2-y^2}dxdy}{\sqrt{1-x^2-y^2}}=2 \iint_D \frac{x^2+y^2}{\sqrt{1-x^2-y^2}}dxdy -\iint_D \frac{1}{\sqrt{1-x^2-y^2}}dxdy + \iint_D dxdy$$. With D= {${{ (x,y) \in R^2 \ ,  x^2+y^2=1}}$} Now considering $x=rcos(\theta)$, $y=rsin(\theta)$ with the Jaacobian $|J|$ = $r$ you can solve the integral that will surely lead to $\frac{5\pi}{2}$
Comment: I don't know what question you're answering, but it certainly is not this one.
Comment: What do you mean ?
Comment: Even when you added all this, you still had the equation of the surface wrong. This is a paraboloid, not a sphere. Saying "you can solve the integral that will surely lead to $5\pi/2$" is a bit glib, since I highly doubt it does. :)
Comment: Am sorry misread the surface equation


"Left homotopy" and "right homotopy" are equivalent in an $\infty$-category.

Question: Let me give some context for the question. Following Lurie's convention, by an $\infty$-category/quasicategory I mean a simplicial set $S:\Delta^{op}\to Set$ satisfying the inner horn filling condition, that is, for all $0<k<n$, any map $\Lambda^n_k\to S$ can be extended to a map $\Delta^n\to S$ along the inclusion $\Lambda^n_k\hookrightarrow \Delta^n$.
We can define a relation on the edges of $S$, i.e. $\phi:\Delta^1\to S$ (equivalently $\phi \in S_1$) as follows. For an edge $\phi : \Delta^1 \to S$ we use the notation $\phi : C\to C'$ to mean that $d_1\phi = C$ and $d_0\phi = C'$. Then, given two edges $\phi, \phi' : C\to C'$ we say they are homotopic if there is a 2-simplex $\sigma : \Delta^2 \to S$ with $d_0\sigma = 1_{C'}:=s_0C'$, $d_1\sigma = \phi'$ and $d_2\sigma = \phi$. Let's denote this relation $\sim_1$. (There's a slight chance I messed up the indexes here, hence I attached a picture to state the correct diagram generally used to represent the 2-simplex).
It turns out this is an equivalence relation. But we could very much have defined the relation by "swapping" $\phi$ and $1_{C'}$, i.e. we could have said : $\phi\sim_2 \phi'$ if and only if there is a 2-simplex $\sigma : \Delta^2 \to S$ with $d_0\sigma = \phi$, $d_1\sigma = \phi'$ and $d_2\sigma = 1_C$. Since a picture is worth a thousand words, we can describe this with the following diagram :

(In the picture the name of the edges and vertices are changed because I simply took a screenshot of a paper by Moritz Groth which didn't use the same naming convention as I did in the first picture)
As it turns out, when $S$ is a quasicategory, these two relations coincide, that is, $\phi \sim_1\phi' \iff \phi\sim_2 \phi'$. I tried proving these two were indeed equivalent. My goal was to start with say a homotopy in the first sense, this gives a 2-simplex. Cook up two other to specify a map $\Lambda_k^3\to S$ for some $0<k<3$, which would allow me to exhibit a homotopy in the second sense as the new face of the 3-simplex obtained with the horn filling condition. I've tried various combinations of 2-simplices but I couldn't find the one that gives me what I needed.
Answer: You can find a proof in Rezk's notes here as proposition 11.6.
Briefly, here is the strategy.  Write $f \sim_l f'$ if there exists a $2$-simplex showing $f \simeq f' \circ 1$, and $f \sim_r f'$ if there exists a $2$-simplex showing $1 \circ f \simeq f'$.  Then we shall show:

$f \sim_l f'$ implies $f \sim_r f'$.
$f \sim_r f'$ implies $f' \sim_l f$.

The two statements combined imply that the equivalence relations $\sim_l$ and $\sim_r$ are symmetric, and also equal.
You can find the $3$-simplices that establish these statements on the bottom of page 30 in Rezk's notes. To make this post self-contained, here are images of these diagrams.  In this first diagram, we have a $\Lambda^3_1$ horn where the left triangle witnesses $f \sim_l f'$ and the other two right triangles are degeneracies.  Filling in the simplex, we obtain the outer triangle, which is a witness for $f \sim_r f'$.

In the second diagram, we have a $\Lambda^3_2$ horn where the upper right triangle witnesses $f \sim_r f'$ and the other two triangles are degeneracies.  Filling in the simplex, we obtain the outer triangle, which is a witness for $f' \sim_l f$.


Appropriate number of degrees of freedom in t-Copula

Question: In a consultation paper (EBA/CP/2014/08) the European Banking Authority (EBA) wrote: "it is proposed […] that Gaussian or Normal like Copulas are not to be used for operational risk modelling. For instance a T-Student copula with few degrees of freedom (eg. 3 or 4) in most cases appears more appropriate to capture the dependencies between the operational risk events."
So far I always thought that degrees of freedom (dof) equal the number of observations minus the parameters to be estimated and are thus well defined. The EBA paper, however, gives the impression that the dof—at least in the case of copulas—are the choice of the modeller. If so, what would be a suitable measure/argument to choose the degrees of freedom of a t-Copula?
Answer:
So far I always thought that degrees of freedom (dof) equal the number of observations minus the parameters to be estimated and are thus well defined.

You're confusing two very different things.
a) Let's start with the family of (univariate) t-distributions. There's a degrees of freedom parameter, $\nu$, that is just that - a parameter - freely definable if we want to use a t-model for something. We don't have to have any data, we're not necessarily doing any sampling, but the $t_3$, the $t_6$ and the $t_{14.38}$ distributions (each with their own densities) are all perfectly sensible objects.
$\,$ More generally, the bivariate-$t$ (and beyond that, the multivariate $t$) are also families of distributions, which has a particular degrees of freedom parameter  - and also a correlation parameter (parameters in the multivariate case) - that between them describe the distribution (and hence, the dependence structure among the variates in the corresponding copula).
b) Now, under the case where we're sampling from a normal distribution with mean $\mu$ such that the observations are independent and identically distributed, if we calculate $T=\frac{\bar{x}-\mu}{s/\sqrt{n}}$ then it turns out that $T$ has a $t$ distribution where $\nu=n-1$. Similarly, in a regression situation, $\frac{\hat{\beta}-\beta}{\text{s.e.}(\hat{\beta})}$ has a $t$ distribution where $\nu=n-p$ where $p$ is the total number of mean-parameters estimated. The $t$ also turns up in a number of other similar sampling situations.
$\,$ At no point in this copula problem are we dealing with creating a sampling statistic like those.
Instead we're looking at bivariate (or more generally multivariate) distributions of variables (which we're typically attempting to estimate from data), which underlying variables have some copula. We're then using as a model for that copula the one based on the copula for the bivariate-t (/ multivariate-t). That is, we're describing the dependence structure in terms of some (more-or-less) simple mathematical construction that is sometimes useful at describing the tail-dependence among variables. So our model is chosen so that $\nu$ (and $\rho$) give it the properties we want to see; they might be estimated (e.g. via ML), or they might be selected, or one might be estimated (e.g. by matching a nonparametric correlation in in the sample) and the other selected to yield a certain level of tail dependence.
In some cases (and operational risk is sometimes one of those) you may not have much ability to use data to assess tail dependence; then it's quite common to simply choose some suitable copula. The Gaussian copula has a correlation matrix but doesn't have tail dependence. The t-copula has in addition a single parameter (the d.f. parameter) that allows you to increase or decrease the amount of tail dependence (in effect, the joint-riskiness) of your variables in your model.
In that case, you might - just as they suggest - simply choose some $\nu$ to express some desired amount of tendency to "move together" in that high upper tail. Suggested values are right there in the text you quote.


Analyticity of the convolution of two functions

Question: This question came about when trying to answer this one.
Does there exist a function $f\in C^\infty(\Bbb R)$ not identically zero such that:

$f$ is supported on $[-1,1]$,
$f$ is analytic on $(-1,1)$,
The convolution $f*f$ is analytic at $0$?

Typical example of an $f$ satisfying 1. and 2. is $e^{-1/(1-t^2)}\chi_{[-1,1]}$, where $\chi_A$ is the characteristic function of the set $A$.
Comment: Do you know whether $e^{-1/(1-t^2)}\chi_{[-1,1]}$ satisfies 3.?
Comment: what does analytic at $0$ mean?
Comment: It can be expanded as a power series on a neighborhood of $0$.
Comment: No, I don't. I have tried examples that are not $C^\infty$, like $(1-x^2)\chi_{[-1,1]}$, but none of them satisfy 3.
Comment: Doesn't $f = 0$ work?
Comment: @mathworker21 Yes, I should have included the condition  $f\not\equiv0$.
Comment: Also, the link saying "this one" is broken
Comment: @mathworker21 Mot for me. The question has been deleted.
Answer: Here is an argument that such a function does not exist under the additional assumption that $f$ is odd or even. Let $F = f \ast f$. Then for any $n \ge 0$ we have that
$$
F^{(2n)}(0) = (f^{(n)} \ast f^{(n)})(0) = \pm \int_{-1}^1 (f^{(n)}(t))^2 \, dt = \pm \| f^{(n)} \|_2^2.
$$
Assuming that $F$ is analytic in a neighborhood of $0$ implies that there exists some $C$ such that
$$
\| f^{(n)} \|_2^2 = |F^{(2n)}(0)| \le C^n (2n)!
$$
for all $n \ge 0$. Now let $a = \inf \{ x : f(x) \ne 0 \}$ be the left endpoint of the support. Applying Taylor's theorem with the integral form of the remainder around $a$ (where the Taylor series is zero) we get that for any $x \ge a$:
$$
\begin{split}
|f(x)|^2 & = \frac{1}{(n!)^2}\left( \int_{a}^x (x-t)^n f^{(n+1)}(t) \, dt  \right)^2 \le \frac{1}{(n!)^2} \int_{a}^x (x-t)^{2n} \, dt  \cdot \int_{a}^x (f^{(n+1)}(t))^2 \, dt \\
 & \le \frac{1}{(n!)^2} \frac{(x-a)^{2n+1}}{2n+1} \| f^{(n+1)} \|_2^2 \le \frac{(2n+2)!}{(n!)^2} \cdot \frac{C^{n+1} (x-a)^{2n+1}}{(2n+1)} \\
& = (2n+2) \binom{2n}{n} C^{n+1} (x-a)^{2n+1} \le (2n+2) \cdot 4^n \cdot C^{n+1} (x-a)^{2n+1},
\end{split}
$$
using Cauchy-Schwarz as well as the estimate $\frac{(2n)!}{(n!)^2} = \binom{2n}{n} \le 4^n$ for the central binomial coefficient. This shows that for all $|x-a|$ sufficiently small we get that $f(x) =0$, i.e., $f$ vanishes in a neighborhood of $a$, contradicting the definition of $a$.
Additional remarks about the general case: Note that this argument does not use the assumption (2) of analyticity of $f$. However, if one drops both the requirements that $f$ is odd or even and that it is analytic in $(-1,1)$, then there are simple examples of such functions $f$. E.g., any smooth function supported on $[1/2,1]$ will have the property that $f \ast f$ is supported on $[1,2]$, so it is trivially analytic near $0$. This indicates that the argument above does not easily apply to the general case of a function which is not odd or even.
Comment: Your $f$ is real. And how do you deal with the case $f_o \ast f_e$
Comment: @reuns: I assumed the question was about real-valued $f$. But you are correct that the general case does not follow as easily from the odd/even case as I thought.
Comment: Very nice argument. I have been trying to extend it to the general case without succes so far.
Comment: Actually, I just noticed that this proof really does not use the analyticity of $f$, only of $F$ near $0$. (Also, analyticity would automatically imply that $a=-1$.) However, if $f$ is not analytic, there is an easy example of such a function, namely one that has a support contained in say $[1/2,1]$, for which $F$ would have support contained in $[1,2]$, so it would be trivially analytic near $0$. At least this shows that the general proof would need some substantial new argument.


Indisponibilidade da Classe Image do System.Drawing

Question: Não tá disponível essa classe.
System.Drawing.Image;

Utilizo o Vs 2013 e NetFramework 4.5.2 e a dll system.drawing v.4.0
Já adicionei as referências e já inclusive importei uma dll "nova" e não fica disponível.
Só declarando System.Drawing já funciona.
Comment: Qual o tipo do projeto? O que você está tentando fazer com o código mostrado acima? Declarar uma variável ou fazer um import (using)?
Comment: @jbueno using estava tentando.
Answer: Se você quer utilizar esta classe (Image) no namespace, terá que definir um Alias para ela.
Após isso, poderá fazer o seguinte:
using System;
using System.Drawing;
using System.Windows.Forms;
using meuAlias = System.Drawing.Image;

namespace Imagem {
    public partial class TesteImagem : Form {
        public TesteImagem() {
            //Construtor
        }

        public void MeuMetodo() {
            //Acessando diretamente a classe com o caminho completo
            var imagem1 = System.Drawing.Image.FromFile("c:\teste.bmp");

            //Usando o Alias criado no Namespace
            var imagem2 = meuAlias.FromFile("c:\teste.jpg");
        }
    }
}

Lembrando que os namespace servem para simplificar a codificação, não se precisa deles caso sempre usar os nomes completos.
Veja, podemos acessar diretamente esse método Range, que está na classe Enumerable, que por sua vez, está no namespace Linq:
var teste = System.Linq.Enumerable.Range(0, 10);

Leituras recomendadas
Em C# é possível usar um alias local para classe ou namespace?
Como usar o alias de namespace global


Copy files from path to path same structure for each user

Question: How to copy files from source
/backup/cpbackup/daily/a1/public_html/index.html
/backup/cpbackup/daily/b2/public_html/index.html
/backup/cpbackup/daily/c3/public_html/index.html
/backup/cpbackup/daily/d4/public_html/index.html
/backup/cpbackup/daily/e5/public_html/index.html
/backup/cpbackup/daily/f6/public_html/index.html

to destination
/home/a1/public_html/index.html
/home/b2/public_html/index.html
/home/c3/public_html/index.html
/home/c4/public_html/index.html
/home/e5/public_html/index.html
/home/f6/public_html/index.html

Answer: This would be one way to do it:
for user in user1 user2 user3 user4 user5 user6; do
  cp /backup/cpbackup/daily/$user/public_html/index.html /home/$user/public_html/
done

Answer: Another way to do it (assuming you're trying to copy all the files over):
rsync -a /backup/cpbackup/daily/user* /home/

If you want just index.html and nothing else:
rsync -av --include=*/ --include=*public_html/index.html --exclude=* /backup/cpbackup/daily/user* /home/

Comment: the user not like user 1 and user 2 , it's example , i mention usernames like jogn and smith not all have the same user name folder
Comment: Then substitute * for user* `rsync -a /backup/cpbackup/daily/* /home/`


Android Sweet Alert Dialog dependencies

Question: I read Sweet AlertDialog tutorial and I have added dependencies to my project this way:

select Build.Gradle (Module:app) and open
go to this line:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

and change to:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'cn.pedant.sweetalert:library:1.3'
}

Run the my app.but i get this error:
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.android.support:appcompat-v7:21.0.0.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.pom
         https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.jar
         file:/D:/sdk/ADT-Bundle-Windows-x86-20140702.Full_p30download.com/sdk/extras/android/m2repository/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.pom
         file:/D:/sdk/ADT-Bundle-Windows-x86-20140702.Full_p30download.com/sdk/extras/android/m2repository/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.jar
         file:/D:/sdk/ADT-Bundle-Windows-x86-20140702.Full_p30download.com/sdk/extras/google/m2repository/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.pom
         file:/D:/sdk/ADT-Bundle-Windows-x86-20140702.Full_p30download.com/sdk/extras/google/m2repository/com/android/support/appcompat-v7/21.0.0/appcompat-v7-21.0.0.jar
     Required by:
         MyApplication:app:unspecified > cn.pedant.sweetalert:library:1.3 > com.pnikosis:materialish-progress:1.0

And when i add appcompat-v7-21.0.0.jar i get this error:
Error:Failed to find: com.android.support:appcompat-v7:21.0.0
Open File
Open in Project Structure dialog

Comment: I got the same error. I have no clue how to fix. Why is Android so convoluted. :/
Answer: Remove appcompat-v7-21.0.0.jar first, then try replace your dependencies with the following:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'cn.pedant.sweetalert:library:1.3'
}

Comment: write your code and i get this error:Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not resolve com.android.support:appcompat-v7:21.0.3.

         > repo.jfrog.org
   > Could not resolve com.android.support:appcompat-v7:21.0.3.
     Required by:
         MyApplication:app:unspecified > cn.pedant.sweetalert:library:1.3 > com.pnikosis:materialish-progress:1.0
      > Could not GET 'https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom'.
         > repo.jfrog.org
Answer: If its a case of missing support library, I think you need to download Android Support Repository from the
Android SDK Manager->SDK Tools->Support Repository->Android Support Repository.

Android Sweet Alert Dialog dependencies


dom referenceing vs storing dom reference

Question: What is the difference between the following statements?
$("#txt").val("123");

and
var txt=$("#txt");
txt.val("123");

Which one is most efficient?
Comment: both are the same... second one is efficient if you are accessing `$("#txt")` multiple times because in that case you will be doing the dom lookup only once... assuming you are not running `var txt=$("#txt");` again and is only reusing the variable `txt`
Comment: test by yourself at http://jsperf.com, it depends on the browser and commonly the storing will more efficient since not storing will search the entire DOM on the document again and again.
Answer: Both version go through the motion of finding a relevant dom element and setting a value
There is no benefit to doing one or the other unless you need to reference it again. Consider this:
if ( $("#txt").val()!='123' )
  $("#txt").val("123");

// vs.

var txt=$("#txt");
if ( txt.val()!='123' )
  txt.val("123");

The latter is more efficient because you are only looking for the element once.
But if you are simply setting it.. either way in your example is going to be the same amount of work. Slightly more overhead from setting a variable first, but nothing to shake a stick at...but even the above situation isn't likely worth shaking a stick at either, unless you enjoy nickel and diming fractions of microseconds.
Answer: In your code, if you need only once to target a desired element selector:
$("#txt").val("123"); // is just fine

But most of the time programmers need to reference multiple times to the same element, and to increase the overall application performance they store the selector into a variable memory slot:
var txt  = $("#txt");
var input = $("#someInput");

input.on('input', function() {
   txt.val( this.value ); // *
});

txt.addClass('selected'); // JS says "hey I know this guy!"

where at this point JS doesn't need to go all over the document looking for your #txt input on every keyup / keydown or other input events. Can you imagine the benefit?
Answer: If you're going to be operating on the value of #txt more than once, it is best to cache the selector as you did in the second version, if you're going to be using the object multiple times. In the end, you probably won't notice any considerable performance increases by using one method v. the other.
As for quantitative data:
versionOne(): 0.0359999998472631
versionTwo(): 0.02500000037252903

This test seems to suggest that the first one is slower, using window.performance. When running this, make sure to empty your browser cache.
(function() {
    var v1 = [];
    var v2 = [];
    function avg(data) {
        var sum = 0
        for(var i = 0; i < data.length; i++) {
            sum += data[i];
        }
        return sum / data.length;
    }
    function versionOne() {
        $("#txt").val('hello');
    }
    function versionTwo() {
        var txt=$("#txt");
        txt.val("123");
    }
    for(var i = 0; i < 1000; i++) {
        var start = window.performance.now();
        versionOne();
        var end = window.performance.now();
        v1.push(end - start);

        var start = window.performance.now();
        versionTwo();
        var end = window.performance.now();
        v2.push(end - start);
    }

    console.log("versionOne(): " + avg(v1));
    console.log("versionTwo(): " + avg(v2));

})();

Fiddle
Comment: In the end, if a programmer is going to want to operate on the object more than once, they should cache it.
Comment: You're doing it wrong. jQuery does cache the selector for you. If you executed the [tests the other way round](http://jsfiddle.net/4RNGa/1/), the result would be the opposite.
Comment: Regardless, I knew that, as I stated in the first sentence. The "test" was just to provide a visualization. I'm not sure I understand where you saw that my answer has merit for a downvote.
Comment: I think the answer is not useful because the quantities are wrong and quite misleading. Btw, measuring them in milliseconds is hinting at inaccuracy.
Comment: With [this setup](http://jsfiddle.net/4RNGa/3/), I'm getting results around `jquery selector2: 0ms (109µsec); jquery selector1: 0ms (59µsec); jquery selector2: 0ms (52µsec)` (yes, executing `$("#txt")` a second time is twice as fast as the first)
Comment: @Bergi If invalidate your cache (do a hard reload) then you should see that `versionTwo` is consistently faster than `versionOne`
Comment: Not when versionTwo is the first invocation, no. After Sizzle's cache is filled, they perform quite equally (unmeasurable differences). | Edit: In your updated test suite (4) with 100000 iterations and `Date.now` in Opera 12.16 I'm getting `versionOne(): 0.03874; versionTwo(): 0.03865`


How many taxonomy terms are too many?

Question: I have a website where I publish book reviews. For each book I publish 2-3 quotes from the book. I'm using the following fields as taxonomy, so that when a user clicks on them he/she can find more content of that category.

Book name
Author name
Publisher

Lets say, over the period of time, I add reviews of about 5000 books, then there will be 5000 taxonomy terms for "book name". Same for the other categories.
My question is, are these too many taxonomy terms for Drupal? Or is there a better way of doing this. All I'm trying to do is, when a user clicks on author's name, he/she can find more content from that author.
Answer: Short answers:

Drupal should have no problem with 5000 terms.
Using a taxonomy for this is the best solution in Drupal.

You may also want to use Taxonomy manager as suggested by kala4e4k in a comment.
What is the upper limit?
Well, taxonomy vocabularies are managed by the database, so this limit is determined by the maximum number of rows you can store in a table in the database you're using.
If you're using MySQL, there is no built-in limit to the number of rows per table (just pick a big enough number type to manage the primary key), but there are other constraints on table size besides number of rows. If you have a 500 Gbyte hard drive and each record is 1 KB is size, your maximum number of rows will be 500 million (if you dedicate the entire drive to this single table, which is not a very realistic scenario). If you buy a 10 Tbyte hard drive, you may run into your operating systems file size limitation (for instance, I believe Ubuntu's maximum is 5 TB, so your limit will be 5 000 million terms instead of 10 000 milion - given the same assumptions about record size).
Comment: Also, I want suggest you to use the Taxonomy manager module: https://www.drupal.org/project/taxonomy_manager
Comment: I understand the database restrictions, but what I'm worried about is that when I will open the terms page in admin section in future, 5000 terms will be loaded. I'm not sure if Drupal or Taxonomy Manager module uses pagination if there are too many terms.
Comment: It is trivial to turn on pagination for the taxonomy term admin page. Take a look at: http://drupal.stackexchange.com/questions/75597/how-do-i-enable-pagination-on-a-taxonomy-term-page

How many taxonomy terms are too many?


Transferir o valor de uma variavel para o ctrl+C em Python?

Question: Estou fazendo um trabalho e preciso que o valor de uma variável vá para o clipboard para que eu possa usá-la em um outro momento.
Tem como fazer isso no Python v2.7?
Answer: Pode usar essa lib pronta, como o:

https://pypi.org/project/pyperclip/

Tem suporte para Windows, Mac e Linux (em Linux requer gtk ou PyQt4)
Instalando via PIP o pyperclip:
pip install pyperclip

Exemplo de uso:
import pyperclip

variavel = "Python"

pyperclip.copy(variavel)

Nota: internamente o https://pypi.org/project/clipboard/ usa o pyperclip, por isso removi da resposta, não há vantagem alguma em seu uso, o único motivo qual o autor criou a lib foi pra ter um "nome melhor" (talvez ele não saiba como o import funciona)


A function for returning a list of tuples that correspond to indices of ALL elements of an ndarray sorted?

Question: I'm aware of numpy.argsort(), but what it does is return indices of elements in an array that would be sorted along a certain axis.
What I need is to sort all the values in an N-dimensional array and have a linear list of tuples as as result.
Like this:
>>> import numpy
>>> A = numpy.array([[7, 8], [9, 5]])
>>> numpy.magic(A)
[(1, 0), (0, 1), (0, 0), (1, 1)]

P.S. I don't even understand what the output of argsort is trying to tell me for this array.
Answer: np.argsort(A) is sorting each row of A separately. For example,
In [21]: np.argsort([[6,5,4],[3,2,1]])
Out[21]:
array([[2, 1, 0],
       [2, 1, 0]])

Instead, you want to flatten your array into a 1-dimensional array of values, then argsort that. That can be done by setting the axis parameter to None (thanks to @Akavall for pointing this out):
In [23]: np.argsort(A, axis=None)
Out[23]: array([3, 0, 1, 2])

Then use np.unravel_index to recover the associated index in A.

In [14]: import numpy as np

In [15]: A = np.array([[7, 8], [9, 5]])

In [4]: np.column_stack(np.unravel_index(np.argsort(A, axis=None)[::-1], A.shape))
Out[4]:
array([[1, 0],
       [0, 1],
       [0, 0],
       [1, 1]])

Note, for NumPy version 1.5.1 or older, np.unravel_index raises a ValueError if passed an array-like object for its first argument. In that case, you could use a list comprehension:
In [17]: [np.unravel_index(p, A.shape) for p in np.argsort(A, axis=None)[::-1]]
Out[17]: [(1, 0), (0, 1), (0, 0), (1, 1)]

Comment: You can do `np.argsort(A, axis=None)` and skip the `ravel()` step.
Comment: @Akavall: Thanks very much for the improvement.
Comment: No need for the list comprehension, `np.unravel_index` will take an array of indices as first argument, somehting like `np.vstack(np.unravel_index(np.argsort(A, axis=None)[::-1], A.shape)).T` is more _numpythonic_.
Comment: @Jamie: Thanks for the improvement!


Viewing Referenced Field Images in node template

Question: I'm stuck with a probably simple problem, maybe someone can help?
I have a node (representing a route) which has a reference to other nodes (points of interestes)
Like this node.field_poi
Every field_poi has it's own images attached
from the node template I'm trying to get the images, but no way!
There are my attempts, where am I wrong?
{{content.field_poi.0.entity.field_image.0.entity.uri.value}}
{{kint(node.field_poi.0.entity.field_image.0.entity.uri.value)}}
If I try this, it breaks completely the page:
{{kint(node.field_poi.0.entity)}}
Answer: Thanks to the slack channel #drupaltwig, I found a solution!
I leave it here, in case somebody else needs it
<code>{% for curr_poi in node.field_poi %}

{% if curr_poi.entity.field_image.entity.uri.value is not empty %}

<img class="product-image" src="{{curr_poi.entity.field_image.entity.uri.value | image_style('app_list')}}" />

{{curr_poi.entity.title.value}}

{% endif %}

{% endfor %}
</code>

Main hints:

use node instead of content
iterator is curr_poi do not use a index
I used twig_tweak drupal module in order to user the filter | image_style('app_list')

Thanks to @kekkis @markconroy