Printing Objects via "<<" in a Linked-List in C++

Question: For an assignment (and for myself) I need to be able to print a singlely linked list of "Stock" objects.
Each Stock as the following private data members:
1 int
1 string
This is my print function in the linked list class I had to use/develop. I am not allowed to use STL::list().
//list.h
template<class NODETYPE>
void List< NODETYPE>::print() const
{
if(isEmpty() ){
    cout<<"the list is empty\n\n";
    return;
}

ListNode< NODETYPE> *currentPtr=firstPtr;

cout<<"The list is: ";

while (currentPtr!=0){
    //cout << currentPtr->data << ' ';
    currentPtr = currentPtr->nextPtr;
}

cout<< "\n\n";
}

Now for the Nodes in the List, listnode.h:
//ListNode.h
//ListNode Template Definition
#ifndef LISTNODE_H
#define LISTNODE_H

template< class NODETYPE > class List;

template < class NODETYPE>
class ListNode {
friend class List < NODETYPE>;

public:
    ListNode (const NODETYPE &); //constructor
    NODETYPE getData() const;

private:
   NODETYPE data;
   ListNode< NODETYPE> *nextPtr;

};

 template<class NODETYPE>
 ListNode< NODETYPE >::ListNode(const NODETYPE &info): data (info), nextPtr(0)
 {

 }
 template<class NODETYPE>
 NODETYPE ListNode<NODETYPE>::getData() const{
    return data;
 }

#endif

Now my Stock Class:
class Stock{
public:
    Stock(); //default constructor
    Stock(string, int); //overloaded constructor
    ~Stock(); //deconstructor
    void setSymbol(string); //sets stock symbol
    void setShares(int);
    string getSymbol();
    int getShares();
private:
    string symbol;
    int shares;
};
Stock::Stock(){
symbol=" ";
shares=0;
}
Stock::Stock(string s, int num){
    cout<<"Creating Stock with supplied Values! \n\n"<<endl;
    symbol=s;
    shares=num;
    price=p;
}

Simple int main() for testing:
int main(){

List < Stock > portfolio_list;

Stock Google("GOOG", 500);
Stock VMware("VMW", 90);
Stock Apple("APL", 350);

portfolio_list.insertAtFront(Google);
portfolio_list.insertAtFront(VMware);
portfolio_list.insertAtFront(Apple);

portfolio_list.print();

return 0;

}

So obviously, I get operator errors for "<<" in list.h, because it can't output the contents of my stock class. My end goal is to loop through every element in a linked list and print the string symbol and int. I'm assuming I will need to use some sort of operator overloading? Or am I way off base? If I do, should this be implemented in my Stock class? Thanks in advance.
Answer: You will need to overload the << operator.
Answer: If I understood your code, you'll have to overload the << operator to both ListNode and List classes.
//Representation of ListNode
template <class T>
ostream& operator << (ostream& ostr, ListNode<T>& ls) {
    return ostr << "Foo"; //replace "Foo" with the proper representation
}

//Representation of List
template <class T>
ostream& operator << (ostream& ostr, List<T>& ls) {
    ostr << "[ ";
    for(ListNode<T> *i = ls.firstPtr; i != NULL; i = i->nextPtr)
        ostr << *i << " ";
    return ostr << "]";
}

Would print [ Foo Foo Foo ] for a 3 element list.
BTW, you should mark those functions as friend if you need to access private members.
Comment: so instead of `return ostr << "Foo";` it should represent calls to my template'd object? I don't quite follow how to get an integer from my stock object from there then. If I have an Object 'Stock' and I want to stream out an 'int Num' and 'String Name' from it.
Comment: @Staypuft the representation of a `Stock` object could be `ostr << "(" << s.symbol << " " << s.shares << ")"` and the result should be `[ (GOOG 500) (VMW 90) (APL 350) ]`
Answer: I think the answer could be more simple. You should only have to just override the << operator the Stock class.
Since your List's print() function is set to point at each node, and then cout << currentPtr->data, the only thing that needs to have an operator overload is each individual "data" class.
In this case, that is your Stock class.
So in order to be able to perform
    cout << currentPtr->data << ' ';

you basically also need to be able to do
    int main(){

        Stock Google("GOOG", 500);
        cout << Google << ' ';
    }

That way, all your list needs to do is cout the class occupying "data" in your list, in this case Stocks.
SO
your Stocks class needs to have an operator overload similar to what was mentioned above. It could look something like this:
//Representation of Stock
ostream& operator << (ostream& ostr, Stock &st) {
    return ostr << "stuff"; // "stuff" is your data (st.symbol and whatever else)
}

That way you only have to override the << operator once! :)
Comment: Oh, didn't notice the date on this. ... I'm a little overdue. Haha, well then this probably won't have much use, but hopefully it's still helpful!


How do I practice arpeggios on the piano?

Question: Just to keep it simple, say we're talking about C major. I just practice (imagine I hit a key with each letter written).
C E G
D F A
E G B
F A C
G B D
A C E
B D F
C E G
Which is just the 7 diatonic chords of c major. So I try to do this on all major scales and minor scales. Is this effective? it seems a bit simplistic.
I mainly do this in order to get some memorization of the chords of each scale but I'm not sure if this is a good method. Or should I add the inversions of each chord as well?
C E G
   E G C
    G C E
      C E G
D F A
  F A D
    A D F
      D F A
E G B
... and so on
Basically, I'm just wondering what is the most common or effective way of practicing arpeggios on a piano.
Answer: More usual would be to practice arpeggios in C major just using the notes C, E, G. Using a pattern something like this:
C E G C' E' G' C'' G' E' C' G E C (using C' for the octave above C etc.)
Using fingerings:
1 2 3 1 2 3 5 3 2 1 3 2 1
Also practice the same thing with the left hand, and then with both hands together.
The do the same thing in other keys. E.g. in D major use this pattern:
D F# A D' F#' A# D'' ...
and so on for other key signatures.
I am not sure I see any great advantage in practicing the other sequences you mention, such as D, F, A.
It would be useful to get a book of scales and arpeggios such as the ones published by the exam boards (e.g. ABRSM) as they give the sort of scales and arpeggios that are encountered most frequently.
A couple of advantages of doing arpeggios like this would be: (a) this is the way arpeggios frequently arise in music by Mozart, Beethoven, Schubert etc. and (b) the "thumb under" technique need to play the arpeggios fluidly this way encourages a flexible and fluid way of playing.
Most of what I have just said is pretty much in line with my experience of classical piano, and may not be quite the same as other genres. Jazz pianists may see things very differently, I guess!
Comment: Agree with looking at the exam syllabi, but ABRSM advocates starting arpeggios with black key start notes to start with another digit than the thumb (1), so thumb can be used on subsequent white key - like Eb major for example.
Comment: Yes, I wasn't advocating the fingering 1-2-3-1-2-3-5 for all keys. For some (e.g. inversions), it is better to use 1-2-4-1-2-4-5, and if starting with the a black note, better to avoid starting with the thumb. Hence my recommendation to get a copy of a book of scales and arpeggios.
Answer: I think it depends what you want to achieve.

I mainly do this in order to get some memorization of the chords of
  each scale:

Then do it! there is nothing bad about it, also the progression makes sense in a way that the VII degree resolves back to I. (It contains the same notes as the V7 - without root).

what is the most common or effective way of practicing arpeggios on a
  piano.

There is many ways of practicing arpeggios on the piano and many of them make sense for what they are gaining for. Your suggested way has one big disadvantage, that is that it is pretty time consuming since you are talking about 84 chords (not counting inversions) while many of them are repetitions. Repetition is one of the main aspects of practice, but if you want to move a bit quicker through the circle of fifth I would recommend the following:
Start in C major then move downwards, like this:
C |
Bm7♭5 |
Am |
Then (in your head already in G major), move a step down:
G |
F♯m7♭5 |
Em |
and so on...
Put together you play I, VII, VI and change the key up a fifth, by moving one step further down (You might want to change to an octave higher at some point). You then will end up with 36 different chords.
Inversions of course are a good thing to practice, ABRSM-tests often ask for inversions when asking for arpeggios.
You can then also add an octave and practice the chords like this, also giving a different shape for the inversions:
RH: c-1 e-2 g-3 c-5
LH: c-5 e-4 g-2 c-1

(NOTE: that the fingering is not consistent when moving through different chords with mixed black and white keys)
Answer: More important than the notes and fingering is ergonomically HOW to play.  The arm is a machine designed to obey certain laws of physics.  Although, we can and do bend those rules but bending the rules of physics comes with a price: Mediocrity or injury.
Each finger is a different length, they have different types of tendons and bones, they radiate at different angles, several different muscles can move them and many of these muscles are very weak and prone to fatigue.  Ironically, those are the ones most pianists use and think they have to build strength and endurance in order to play. They actually need to not use those muscles and use the proper big ones. BTW, there are no muscles in your fingers.
Practice doesn't make perfect, perfect practice makes perfect and imperfect practice creates bad habits which are difficult to eradicate from muscle memory (the brain).
It would be best that you find a teacher who will not allow you to touch the piano until you master the movements properly and understand the physics of the piano and your arm.  The second you first touch a piano your brain maps the movement and if you strike the key using incorrect movement, the brain wires it in.  If there is a leap or scale that eludes you, it isn't because you need more practice, it is because an errant movement is getting in your way and always will.  Practicing more won't fix anything.  Practicing properly will. You need a teacher to tell you how to move based upon physics, not errant movement that their teacher taught them and their's before them.  It isn't fact because that is how they were taught.  Even "facts" can be wrong.
Playing arpeggios involves a lot of movement from up/down, in/out, moving the arm, using pronator and supinator muscles, adjusting the elbow, adjusting the forearm, playing with gravity, forward shifts, grouping, then they all need to be combined. There are just as many things NOT to do such as pressing, abducting, crossing the thumb under the palm, isolating fingers, ulnar and radial deviation, trying to play with a still and quiet hand, trying to equalize the fingers . . . The arm plays the fingers, the fingers don't play the piano.
The point is, your first teacher and first movements must be perfect for, once a bad habit is set in stone, it can take a lifetime to eradicate.
Some teachers like to let the student "figure it out" which some students do as they improve and experiment.  But it would be better to teach them everything properly before they start playing.  We don't let people drive cars or fly planes that way.  Why pianists?  Oh, is it because nobody dies?  What is a career doomed for mediocrity?
Most teachers should not be teaching.  Maybe if we put them all on a plane and said "Land it."


Page title with substitution on views page

Question: I have a view page that requires a dynamic page title. It is a simple substitution of the label field.
If I use {{ label }} it works fine for the title displayed on the page, but it doesn't substitute the label for the actual page title (in meta)
I was able to fix this by using hook_views_post_render using the following code
// Set the route title.
$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$route->setDefault('_title', $title);

$view->setTitle($title);

However, the title only works if the page is not cached. For the cached pages, the page title is missing. This feels like a bug in drupal, but I am hoping that there is a simple way to get this done.
Answer: You can't change the route object in a hook. Use a RouteSubscriber to add a dynamic _title_callback to the view route.
Otherwise setTitle() should work. The bug you've described is not a bug. It's about caching in general. When you add dynamic data you also have to add the cache metadata, which defines what kind of dynamic data this is.
For example if the dynamic title depends on the node 123:
$output['#cache']['tags'][] = 'node:123';


How to find the upper bound for this series

Question: I came across this series in a book and the author tells the upper bound and it checks out under the conditions but i could n't find the connection or the reason if u may, that had i not been presented with this info, that i could have used to find the upper bound myself.
For $s>1$ the sum of $2^{p}-1$ terms of the series is less than
$\dfrac {1} {1^{s-1}}+\dfrac {1} {2^{s-1}}+\dfrac {1} {4^{s-1}}+\dfrac {1} {8^{s-1}}+\ldots +\dfrac {1} {2^{\left( p-1\right) \left( s-1\right) }} < \dfrac {1} {1-2^{1-s}}$
Any hints or clues would be much appreciated.
Comment: I think there are just $p$ summands, not $2^p - 1$. Then why you hesitate to use the identity $$ 1 + r + \cdots + r^{n-1} = \frac{r^n - 1}{r - 1} \quad (r \neq 1)$$ for this problem?
Answer: Use the fact that if $|x|<1$, then $\frac{1}{1-x}$ has the power series expansion
$$\frac{1}{1-x}=1+x+x^2+x^3+\cdots +x^n+\cdots .$$
Or, in less fancy language, if $|x|<1$, then the infinite  geometric series $1+x+x^2+\cdots+x^n+\cdots$ has sum $\frac{1}{1-x}$. In your particular example, $x=\frac{1}{2^{s-1}}$. Since $s>1$, we have $|x|<1$.
More explicitly, for this value of $x$, the left-hand side is just
$$1+x+x^2+\cdots+x^{p-1}.$$
This finite geometric series has sum
$$1+x+x^2+\cdots+x^{p-1}=\frac{1-x^p}{1-x}=\frac{1}{1-x}-\frac{x^p}{1-x}.$$
This says that the sum on the left-hand side is less than $\frac{1}{1-x}$.  It even says by how much it is less, namely $\frac{x^p}{1-x}$.


Use db_select with multiple conditions of which one needs to apply

Question: My question is not a duplicate and it has complex conditions. Please let me explain. In my second condition, first I need to check if number value is correct (in first condition I checked complete opposite). If so, then check if there's a value in email column. Then show error message if there's a value in email column. My problem is I need to write first query (already done by me) and second query under the same 'db_select'
Checking for email value only activates if webform value matches a value in 'number' column.

I have a table containing two columns namely, 'number' and 'email'.
I need to run a db_select query to display same error message when a webform is submitted. My conditions are as follows:

Show error message if number value provided by webform does not matches a value in 'number' column
Show error message if number value provided by webform matches a value in 'number' column but corresponding 'email' column is not empty.

So far I'm able to show error message for the first condition.
db_set_active('mydatabase');
    $query = db_select('mytable', 'c');
    $query->fields('c', array('number','email_address'))
    ->condition('number', $phoneval, '=');
    $result = $query->execute()->fetchAll();

if (empty($result))
{
    form_set_error('phone_number','We have no record of that Assessment Number');
}

How can I show the same error message for condition 2? I don not want to query the database again and thinking of using for db_or this.
Thanks
Comment: My question is not a duplicate and it has complex conditions. Please see the updated question.
Answer: Syntax for db_or :
$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

For More Information
Answer: db_set_active('mydatabase');
$query = db_select('mytable', 'c');
$query->fields('c', array('number','email_address'))
->condition('number', $phoneval, '=')
->condition('email_address', $mailval, '=');
$result = $query->execute()->fetchAll();

You could use nested if
if (empty($result)) {
  // do print_r($result);
  // here you will get the result in array
   if (empty($result['number'])) {
    form_set_error('phone_number','We have no record of that Assessment Number');
   } else if(empty($result['email_address'])) {
   form_set_error('email_address','We have no record of that email');
   }
}

Comment: Thanks but my conditions are complex than you think. As in your second condition, I'm not matching email address but only number value. first show error message if number value doesn't match 'OR' if number value matches but there's a value in email column.
Answer: Can't you just use PHP for this?
db_set_active('mydatabase');
  $query = db_select('mytable', 'c')
    ->fields('c', array('number','email_address'))
    ->condition('number', $phoneval, '=');
  $result = $query->execute()->fetchAll();

// Don't forget to set the db back to default
db_set_active();

if (empty($result)) {
    form_set_error('phone_number','We have no record of that Assessment Number');
}
// We found a record with matching number... check e-mail
else {
  // Grab the first item in array
  $result = reset($result);
  // If e-mail's not empty, show error.
  if (!empty($result->email_address)) {
    form_set_error('phone_number','We have no record of that Assessment Number');
  }
}


How to interpret coefficients from a GARCH model?

Question: Recently I have opened a question here to understand the output of a GARCH model.
My goal is to understand if the series I'm checking is heteroscedastic or not.
I'm using the garch() function from the tseries package.
First I built a linear regression like this:
mod <- lm(a ~ b)

Then I need to check if the residuals of this linear regression present heteroscedasticity.
I did:
g <- garch(resid(mod), order(c(1,1)))

and then
summary(g)

I get the follow output:
> summary(g)

Call:
garch(x = lm(A ~ B)$resi, order = order(c(1, 1)))

Model:
GARCH(1,2)

Residuals:
    Min      1Q  Median      3Q    Max
-4.2058 -1.0262  0.1404  1.1069  3.6553

Coefficient(s):
    Estimate  Std. Error  t value Pr(>|t|)
a0 3.361e-04  9.352e-05    3.594 0.000326 ***
a1 3.045e-01  4.486e-02    6.787 1.14e-11 ***
a2 1.209e-06  8.855e-02    0.000 0.999989
b1 4.938e-01  1.060e-01    4.660 3.17e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Diagnostic Tests:
    Jarque Bera Test

data:  Residuals
X-squared = 18.84, df = 2, p-value = 8.108e-05

    Box-Ljung test

data:  Squared.Residuals
X-squared = 49.7251, df = 1, p-value = 1.769e-12

Thanks to the user who answered my question, I now understand that the ao is the intercept and the other a1 and b1 are the coefficients I need to check to understand if this time series is heteroscedastic or not.
The problem (doubt) is that now I also see a2 in the regression table: What does it stand for?
Is it correct to say that if all coefficients have a $p$-value above 0.05 (...)
Comment: I've made some edits to your question which still looks unfinished at the moment (please, fill the `(...)`!).
Answer: The output says that a2 is really insignificant.
What you have is (essentially) a hypothesis test that assumes homoscedasticity and can be rejected so that you would infer there really is heteroscedasticity.  What you seem to want is a test that assumes heteroscedasticity that you can reject in order to infer homoscedasticity.  In principle you could have such a test, but in practice I don't think you can.
Thinking like a Bayesian will help some, but it still isn't going to make a nice dividing line between "has volatility clustering" and "close enough to homoscedastic".


Get master key to access HttpTrigger in Azure Function 2x

Question: I need to get a key to access code for HttpTrigger https://mydomain.azurewebsites.net/api/registration?code=Key. In Azure function 1x, with Url https://$functionAppName.scm.azurewebsites.net/api/functions/admin/masterkey
will return my master key like {"masterKey":"ehp9f***************************"} but, in Azure Function 2x this way isn't work. How can I  connect HttpTrigger in PowerShell with Azure Function 2x. Another SCM Api or syntax instead of (Invoke-RestMethod -Uri https://mydomain.scm.azurewebsites.net/api/functions/admin/masterkey -Headers @{"Authorization"=$accessToken;"If-Match"="*"} ).Masterkey in Azure function 1x.
Thanks for your support
Comment: I wonder how to get too :((
Answer: This is a known issue check this wiki doc:ARM Impact and this issue:listSecrets broken for function keys in V2.
For now there is a new api however it's not released you could check this issue:Expand/Improve Functions ARM APIs.
Here is a sample api:
POST api/sites/{name}[/slots/{slot}]/host/default/listkeys
{
"masterKey": "<keyvalue>",
"functionKeys": {
  "default": "<keyvalue>",
  "my-key": "<keyvalue>"
},
"systemKeys": {
  "test-system": "<keyvalue>",
  "my-key": "<keyvalue>"
}
}

Answer: For those who cannot find the _master key as described in this article Get the function's master key, go the the root of the function resource and look in the App keys tab.
Answer:
Navigate to your function in the Azure portal and click on Manage and
  find the Host Keys section. Click on the Copy button in the _master
  row to copy the master key to your clipboard.

Source: Get the function's master key
If you need to retrieve the master key inside an ARM template, take a look at the listkeys function.
Comment: sorry, my mistake with my question I want to use PowerShell to get a master key, In Azure Function 1x with syntax
$masterKey = (Invoke-RestMethod -Uri https://mydomain.scm.azurewebsites.net/api/functions/admin/masterkey -Headers @{"Authorization"=$accessToken;"If-Match"="*"} ).Masterkey.
And I detect 'https://mydomain.scm.azurewebsites.net/api/functions/admin/masterkey' is not work in 2x so, I want no find some 'scm api' to instead It


When is a matrix a constant multiple of unit matrix

Question: How can it be proved that if a matrix has all eigenvalues equal and it's eigenvectors form a complete set, then the matrix is a scalar multiple of the identity matrix?
What happens if the eigenvectors do not form a complete set?
Thanks for the help.
Comment: What do you mean by a complete set?
Comment: @KennyLau It spans the entire space. As for when the eigenvectors do not form a complete set, see $\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right)$ for an example.
Comment: @Arthur I was asking the Author for clarification...
Comment: @KennyLau And you got a clarification from me. For the time being you will have to make do.
Answer: For part 1: if eigenvectors $v_1, v_2$ of an $n \times n$ matrix $A$ share an eigenvalue $\lambda$, then so do all linear combinations of $v_1, v_2$:
$$
A(a_1v_1 + a_2v_2) = a_1A(v_1) + a_2A(v_2) = a_1\lambda v_1 + a_2 \lambda v_2 = \lambda (a_1v_1 + a_2v_2).
$$
Thus, if $A$ has a set of eigenvectors sharing an eigenvalue $\lambda$ which span the whole space, then in fact every vector of the space is an eigenvector. In particular, this is true for the standard basis $e_1, \ldots, e_n$. Now note that the $i$th column of $A$ is equal to $Ae_i$, and
$$
Ae_i = \lambda e_i,
$$
so that $A = \lambda I_n$.
For the second part: hint, consider the matrix
$$
B = \begin{pmatrix}
2 & 1 & 0\\
0 & 2 & 1 \\
0 & 0 & 2
\end{pmatrix}.
$$
Also, for any invertible matrix $P$, consider $PBP^{-1}$.
Answer: If a matrix $A$ has all eigenvalues equal, it means that the characteristic polynomial of the matrix is $p_A(t)=(t-\lambda)^n$.
Considering that $\dim(V)=n$ and that all the eigenvectors span all the space, you can say that $rk(A-\lambda I)=0$ which implies the matrix has $n$ blocks in its Jordan Normal Form. It easily follows that it is diagonalizable and, by having all the eigenvalues equal, it is a multiple of the identity.
Edit:
If all the eigenvectors do not span all the space, you have $rk(A-\lambda I)=k >0$ which implies that the Jordan Normal Form of the matrix has less then $n$ blocks, so it is not diagonalizable.
Example: $$\begin{pmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1\\\end{pmatrix}$$
Answer: Matrix $M$ has repeated eigenvalue $\lambda$, and is diagonalizable, hence the Jordan form is:
$$\begin{bmatrix}\lambda\\&\lambda\\&&\ddots\\&&&\lambda\end{bmatrix}=PMP^{-1},$$
for some invertible $P$.
Hence $$PMP^{-1}=\lambda I\implies PM=\lambda I P$$$$ \implies M = P^{-1}\lambda I P= \lambda I P^{-1}P = \lambda I,$$
as required.
Answer: Let $V$ be a vector space of dimension $n$ over a field $F$. Let the matrix be $A$ and its eigenvalue be $\lambda$.
By the assumption, we have $A \vec v = \lambda \vec v$ for all $\vec v \in V$.
Substituting $\vec v = \vec e_i$, one gets $A\vec e_i = \lambda \vec e_i$ where $\{\vec e_1, \vec e_2, \cdots, \vec e_n\}$ is the standard basis of $V$.
Then:
$$\begin{array}{rcl}
AI_n &=& A[\vec e_1~\vec e_2~\cdots~\vec e_n]\\
&=& [A\vec e_1~A\vec e_2~\cdots~A\vec e_n]\\
&=& [\lambda \vec e_1~\lambda \vec e_2~\cdots~\lambda \vec e_n]\\
&=& \lambda [\vec e_1~\vec e_2~\cdots~\vec e_n]\\
&=& \lambda I_n
\end{array}$$
$\blacksquare$
Answer: Hint: the eigenvectors of the $n\times n$ matrix $A$ span the whole space $K^n$ (where $K$ is the base field) if and only if $A$ is diagonalizable.


How to add switch button in navigation drawer

Question: I want to use switch button in navigation drawer for adding and removing fragment from main layout.
this my code-
menuitem.xml`

<group
    android:id="@+id/drawer_group1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_timer"
        android:icon="@drawable/ic_timer"
        android:title="Timer">

    </item>

    <item
        android:id="@+id/addFragment_Bt"
        app:actionViewClass="android.widget.Switch"
        android:title="Most Used" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings"
        android:title="Settings">

    </item>
</group>`

MainActivity.class
public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        switch (menuItem.getItemId()) {
            case R.id.addFragment_Bt:

                Switch switchCompat = findViewById(R.id.addMostUsed_Bt);
                switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        FragmentManager fragmentManager = getSupportFragmentManager();
                        Fragment fragment = fragmentManager.findFragmentById(R.id.Most_Used_Fragment_container);
                        if (isChecked == true) {
                            if (fragment != null) {
                                fragmentManager.popBackStack();
                            }

                        }
                    }
                });
                break;
        }
    }
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;

    }
}

for now i am just trying to remove already added fragment.
Answer: menuitem.xml
<item android:id="@+id/nav_switch"
            app:actionLayout="@layout/switch_menu"
            android:title="Send"
            android:icon="@drawable/ic_menu_send"/>

switch_menu switch_menu is layout for switch.
switch_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_id"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:text=""/>
</LinearLayout>

Access Switch into activity:--
SwitchCompat switch_id;
switch_id =  actionView.findViewById(R.id.switch_id);
        switch_id.setChecked(true);
        switch_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), switch_id.isChecked()? "is checked!!!" : "not checked!!!",Toast.LENGTH_SHORT).show();
            }
        });

The output using above code is:

I hope its work for you.
Answer: This Works for me.
///This is menu item.
<item
     android:id="@+id/darkModeMenu"
     android:title="Dark Mode"
     android:icon="@drawable/ic_darkmode"
     app:actionViewClass="androidx.appcompat.widget.SwitchCompat"
     ></item>

//write this on the on create() method of Activity.
val menuItem = navigationView.menu.findItem(R.id.darkModeMenu)
    val switch_id = menuItem.actionView as SwitchCompat
    switch_id.setChecked(true)
    switch_id.setOnClickListener(View.OnClickListener {
        Toast.makeText(
            applicationContext,
            if (switch_id.isChecked()) "is checked!!!" else "not checked!!!",
            Toast.LENGTH_SHORT
        ).show()
    })

Answer: I tried these methods but not works. After an hour of research. Finally, I found an answer.
Keep the focus on my point
First, add switch in the activity_main_drawer. Where your other drawer menu items
       <item
            android:id="@+id/app_bar_switch"
            android:title="Switch"
            app:actionLayout="@layout/switch_item"
            app:showAsAction="always" />

and add below is XML by creating @layout/switch_item. Make sure to add id @+id/darkModeSwitch to your switch button. If XML creates automatically then just add the id to switch button.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Switch
        android:id="@+id/darkModeSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        tools:ignore="UseSwitchCompatOrMaterialXml" />
</RelativeLayout>

And finally, add the below java code
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Code starts here
        NavigationView navigationView = binding.navView; // your navigation drawer id
        MenuItem menuItem = navigationView.getMenu().findItem(R.id.app_bar_switch); // first insialize MenuItem
        @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchButton = (Switch) menuItem.getActionView().findViewById(R.id.darkModeSwitch);
        // if you are using Switch in your @layout/switch_item then use Switch or use SwitchCompact
        switchButton.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b){
                Toast.makeText(this, "True", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this, "False", Toast.LENGTH_SHORT).show();
            }
        });
}

I hope it helps.


Refresh output line containing download percentage

Question: I'm writing a script that has to download several files from the www.
To make it more expressive I've just added a download hook to calculate the downloading percentage of the file that has being downloaded. Printing it out on the terminal produces a lot of output because I rewrite the same line each time the percentage counter is incremented, example:
1% - Downloading test.jpg
2% - Downloading test.jpg
... and so on

I'd like to obtain something like many bash scripts or programs (such as "apt-get" from ubuntu): refresh the line containing the percentage without have to write several times the same line containing the the updated percentage.
How can I do that?
Thanks.
[edit]
I'm using Python3.2 to develop the file downloader.
Comment: Yeah, sorry. Didn't find it before posting this.
Comment: related: [Download progressbar for Python 3](http://stackoverflow.com/a/13895723/4279)
Answer: You need curses:
http://docs.python.org/howto/curses.html
Answer: Use \r (carriage return) and write directly to the terminal with sys.stdout.write:
import time
import sys
for i in range(101):
    sys.stdout.write('%3d%%\r' % i)
    time.sleep(.1)

Or a little more Python 3-ish:
import time
for i in range(101):
    print('{:3}%'.format(i),end='\r')
    time.sleep(.1)

Comment: This doesn't work for me
Comment: @Patrick: requires running at a command line console. Most IDEs don't support it.
Comment: Was running it in xterm (rxvt). Didn't work.
Comment: python-3 worked for me


Two cards are drawn at random from a normal deck of cards.

Question: I was wondering how to do this question.
"Two cards are drawn at random from a normal deck of cards.What is the probability that the second card is
 a two if the first card was a two?"
And how do i do questions similar to this?
Thank you.
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer: This is done by observing that after drawing a two you're left with a deck of $51$ cards of which 3 are twos. The probability is therefore $3/51 = 1/17$.
The more elaborate solution is to use the definition of conditional probability calculate the probability that you pick $2$ twos (which is $6/1326=1/221$) and divide that by the probability that the first you pick is a two which is $4/52=1/13$. The qutient is $13/221=1/17$
Comment: Thank you.It seems i was overthinking this one a bit.
Answer: Hint:
There are $51$ equiprobable candidates for the second card (all cards except the first one). Among these candidates there are $3$ two's.
P.S. The question: "What is the probability that the first card (taken blindly) is a two if the second card appears to be a two?" is often experienced as "more difficult" but can be handled just the same way.
Comment: Yea, the way it was worded did make it pretty harder in my opinion.Thank you for your help.


Can this function be a density function of a continuous random variable X?

Question: F(x) = 0, if x < 1
F(x) = 1, if 1<=x<=2
F(x) = 0, if x>2
I think it could be, as long as the integral is 1. Any ideas?
Comment: Yes, you argued correctly.  I would rather call it $f(x)$.  That way, $F(x)$ can be used for the cumulative distribution function.
Comment: The word 'continuous' in your title is redundant. If a random variable has a PDF then it is by definition 'absolutely continuous'. That is even stronger than continuous.
Comment: thanks Andre! Do you also know that why Q (rational number field) does not have a finite subfield? How to prove it?
Comment: You are welcome. Any subfield contains the unit element $1$. But then since it is closed under addition, it contains all positive integers. There are infinitely many already. You can o on to prove (easily) that the only subfield of $\mathbb{Q}$ is $\mathbb{Q}$.
Comment: I see. Thanks Andre. Btw, did you find that I have a fancy name?
Comment: Yes, I noticed, a very famous name. Also fancy in the social sense, but that is of no interest.
Answer: Your function is the probability density function of a random variable distributed uniformly on the interval $[1,2]$.
As well as having an integral across the real numbers of $1$, a probability density function also needs to be non-negative.  Your function has this property.


Aplicar efeito jQuery ao elemento HTML atual?

Question: Tenho o seguinte código que quando coloco para rodar, ele dá display:none e display:block em todos os elementos e eu gostaria que aplicasse este efeito só no elemento corrente:
//jQuery
$( ".titulo" ).mouseover (
      function() {
        $(".overlayContent").css("display", "none");
      }
    );
    $( ".titulo" ).mouseout (
      function() {
        $(".overlayContent").css("display", "block");
      }
    );

//HTML

Post

Este span é um background-color:#000 com opacity:.5 que desaparece quando mouseover. Só que todos desaparecem e eu queria que só o corrente desaparecesse. Poderá ver o efeito neste link http://catalogos.axitech.com.br/
Comment: @Kazzkiq na verdade não existe funcionamento porque a unica coisa que aparece é o `overlay 0.5` entre a imagem e o titulo posicionado por `position:absolute` e `z-index` respectivos. Se inspecionar elemento verá exatamente a posição dos elementos.
Comment: E você quer que o overlay suma apenas quando se passar o código no título? Ou pode ser no bloco inteiro? Pode ser apenas com CSS ou você quer a solução com JavaScript?
Comment: @Kazzkiq pode ser no bloco inteiro. Eu tentei no bloco inteiro mas ficou piscando que nem discoteca ai eu comecei a tentar com o titulo.
Answer: Acredito que para este problema apenas CSS já resolva tudo:
.detalhesArticleHome .overlayContent{
    opacity:0.5;
}

.detalhesArticleHome:hover .overlayContent{
    opacity:0;
}

O que o código acima faz é atribuir a opacidade que você deseja ao elemento .overlayContent toda vez que o mouse passar pelo bloco inteiro.
Caso você queira fazer um efeito "fade-in" e "fade-out" no overlay, é possível utilizar ainda a propriedade transition do CSS para a animação.
Comment: Eu gostaria da aplicar um efeito mais trabalhado tipo fadein e fadeout uma vez com o script pronto.
Comment: Apliquei o efeito com transition e css mas isso só funciona a partir da versão 10 do Internet Explorer mas mesmo assim resolveu.
Answer: Seria algo mais ou menos assim:
$( ".titulo" ).mouseover (
  function() {
    $(this).prev(".overlayContent").css("display", "none");
  }
);
$( ".titulo" ).mouseout (
  function() {
    $(this).prev(".overlayContent").css("display", "block");
  }
);

Comment: dsantoro se reparar no código no link  poderá verificar que o seu código não deu certo só porque a `class="overlayContent"` não está exatamente um item anterior a `class="titulo"` ... alguma ideia?
Comment: @dsantoro: Seria possével elaborar um pouco melhor sua resosta


pass response from external authentication interface (EAI) through webseal to browser

Question: I have an application that wants to return a response back to the browser from the EAI.  In this case, the response is a dynamically created XML document.  WebSEAL seems to drop this response and return a 302.  I want both a security session cookie from webseal and the XML response returned in the EAI response to end up at the browser, preferably with an HTTP 200 response, but maybe other response codes.
To elaborate:

form-based authentication, posting userID, password, registered token value to trigger URL
WebSEAL triggers and passes request to EAI
EAI authenticates user ID and password, invokes webservice with user ID and registered token value
web service returns XML in its response
EAI sets authentication headers based on XML content and passes response onto WebSEAL
WebSEAL catches authentication headers and creates security session and set cookie header for the credential
WebSEAL responds with a 302 and removes the response body passed through the EAI from the web service

Question: Can WebSEAL be configured to pass the response untouched other than adding the credential cookie so that the requester gets the credential and the XML message body?
Comment: And your question is?
Answer: It sounds like WebSEAL is throwing a 302 back to the EAI because there isn't a valid session.  Also, for the other responses, you might need to check your operation handlers in the WebSEAL config and adjust accordingly.  Also, make sure your EAI application junction is set to unauthenticated.  Otherwise WebSEAL will go into an infinite redirect loop (your browser will eventually stop the madness).  Make sure your EAI is passing back the correct authentication data back to WebSEAL so a valid TAM session is created.
There is a good diagram of the process flow for TAM 7 at:
http://publib.boulder.ibm.com/infocenter/tivihelp/v2r1/index.jsp?topic=%2Fcom.ibm.isam.doc_70%2Fameb_appl_guide%2Fconcept%2Fcon_ext_authe_intfc_proc_flow.html
Also, a good write up on developing EAIs:
http://pic.dhe.ibm.com/infocenter/ieduasst/secv1r0/topic/com.ibm.iea.tam/tam/6.1/authentication/eai_server.pdf


How can I style the webform submissions table?

Question: Using Drupal 9 and Webform, I'm unable to find the twig template used to output /contact/form/submissions.  Is there a place in the documentation that lists the twig templates?  I see there is a View created that looks like it has submissions, but disabling it doesn't break the page.  If there is a better way to style it, that could also work.
Comment: Does this answer your question? [Is there a "best practice" for overriding a contributed module's controller in Drupal 8?](https://drupal.stackexchange.com/questions/281093/is-there-a-best-practice-for-overriding-a-contributed-modules-controller-in-d)
Answer: Check out Is there a "best practice" for overriding a contributed module's controller in Drupal 8?
If you override the WebformSubmissionListBuilder, you can do almost anything you want to the results, including custom theming.


Thread 1: EXC_BAD_ACCESS (code=2, address 0x1)

Question: So Yeah. I ran my application (an RSS reader) and I received this error. It points to this line: 0x10e0098:  movl   (%eax), %edx and the code in my MainViewController.m is
UIViewController *WebViewController =
 [[WebViewController alloc] initWithNibName:@"WebViewController.h" bundle:nil];

Answer: the nib name does not have the .h extension (that is the header file). Try this:
UIViewController *WebViewController =
 [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];

assuming the filename of your nib is WebViewController.xib.
Comment: But have you created a Xib? And what's its name?
Comment: I have. It's WebViewController.xib. But I still get the error
Comment: Profile the app with NSZombie enabled and it should give you more information about what is going wrong.


PHP page structure SEO query

Question: I have what I presume is a simple question regarding PHP file structure.
If index.php has a doctype/meta/headers/body that are opened and closed within the script, but then contains header.php which again has a doctype/basic meta/headers/body that are opened and closed, and contains navigation.php that does the same and footer.php that does the same again.  What are the implications for SEO?
I'm a newbie, I'm sure it is very poor coding practice and crawlers will have issues indexing the page as it looks like there are 4 or 5 pages within one, but how fatal for SEO is it(if at all)?
Thanks in advance
Comment: Why in the world do you display several html documents on one page?
Comment: I wouldn't personally but been asked the question by a friend and didn't know the answer.
Comment: One page is one document. Several document on a page is wrong. A smart browser will try to correct it. But still... Don't do it.
Comment: Thanks, it struck me as very poor considering my friend paid (well) for the site.  I'll fix it for him.
Answer: The way you structure your site server-side doesn't matter, the final output you see in your browser's "view source" feature is all search engines can see. Use W3's validator to make sure everything is closed properly.
Edit: I think I misunderstood your question. No, you can't have more than one "document" per page.
Comment: The final output does have several sets of meta content (all be it empty), UTF etc where the internal php scritps (header/footer) are called down the page via firebug.  Will that have an effect?

PHP page structure SEO query


Are questions about undefined terms on-topic?

Question: I am struggling to understand why the question "Is a small business owner without employees a capitalist?" is on-topic.
Yes, it is about a topic related to the economy (not economics though) and the term is used by Marx, but more in a political context. A more suitable question in my opinion would be something like "how does XY (e.g. Marx) define who is a capitalist?"
My main question is: Why is the linked question on-topic?
My subquestion is: Which of the following inquiries would be off-topic?

Is a person who recently came into money nouveau riche?
Would most people consider the US economy neoliberal?
In your opinion what do I think the definition of communism is?
Comment: Im personally in favor of considering Marxist questions off topic.
Answer: In the standard Overlapping Generations model of Diamond, there are two generations, each living two periods. In the first period of their life, the Young have no capital, and they work in firms where the capital is owned by the Old. So in the heart of, let's say, "western mainstream economics", we have a model that relies on the total separation of labor and capital, and distinguishes between "workers" and "capitalists" (in terms here of property rights) in the most clear-cut way.
This is a good example in my opinion as to why the term" "capitalist", if properly defined (as it must be done with all terms that have also sociopolitical flavor), can be used in economics of any strand and for proper economic modeling and thinking.
You are certainly right in pointing out that the question as posed by the OP was clumsy - and at the same time, as is sometimes the case with clumsy questions, it provided an opportunity to try to properly treat the term.
As for your three inquiries:
1) I don't remember seeing an economics model or book using the "nouveau riche" concept (as perhaps a label for special behavioral assumptions that could lead to special outcomes). Off-topic also because it does not involve economic inference.
2) This asks for opinion-based answers, and the re-phrase "is there any study as to how many people consider..." appears necessary. But it would be off-topic anyhow, since it does not involve economic inference.
3) In my opinion, this asks for opinion-based answers.
Comment: @denesp. But there is no "one", "correct", "universal" meaning for "capitalist", this is the whole point, this is why we need to anchor such terms to elaborate theories and systems of thought (or create one ourselves), if we ever want to use them in a fruitful way.
Comment: In the meantime OP of the linked question stated in a comment under [another question](https://economics.stackexchange.com/questions/18887/since-when-is-the-economy-of-england-based-on-the-capitalist-system) where I asked him to define what he considers capitalism that " I have another question about capitalism and it's a valid question. I didn't have to explain what I mean by capitalism." So I don't think giving him a pass with his clumsy question was a good idea.
Comment: I agree with your judgement on all three of my subquestions. I just don't see the difference between these and the linked question. Which to me seems unclear and/or opinion based, as it got four very different answers. I also wonder if this is proper treatment of the term.
Comment: On the owners of capital, which exist in many models (e.g. Diamond's OLG): This is a very clear term. It is not, however, synonymous with capitalist. If it were, then the Soviet state, or the Soviet people, as owners of all Soviet capital would have been capitalists.
Comment: @denesp As for the Soviets: but they were capitalists. The soviet state did appropriate the surplus value of the workers. This is standard analysis of the _socialist regime_, as a transition phase to communism, standard by marxists themselves.The supposed difference is that the appropriated surplus was controlled by the state, and the state gave back the surplus to the people. This did not make it a true communist regime, but then again, it was just a phase on the road to communism.
Comment: If there is no one correct universal meaning for capitalist then the question is opinion based, is it not? At the very least I learned something about the Soviets.
Comment: This for me is the point where we need to accept some things will be debatable, without being opinion based. Economics is a social science, so not everything can beaccurate as in physics. Only by discussing we can get to better definitions.
Comment: @denesp I agree with JoaoBotelho, and this is why I insist on formulated theories in the context of which we need to define and use a term: in essence, they are opinions too, but much more elaborated and by many people, and sometimes with some empirical backing also.
Comment: I will not make endless objections, here is my final one: I just read the answers to [this other question](https://economics.stackexchange.com/questions/18972/the-right-term-for-a-market-that-tends-towards-consumers-switching-suppliers-fre). This is a debate on how to model an economic phenomenon. I think it is interesting and on-topic. The post I object to is not like this: It is not a discussion of an economic phenomenon, but on what people mean by a term that is not essential in any economic model.
Answer: I think the question Is a small business owner without employees a capitalist? is probably off-topic because it uses a term ("capitalist") without a clear definition making it hard to know exactly what the poster is asking. Usually, this is at least grounds to put a question on hold until it can be clarified.
I agree, for example, that the modified question "How does marx define capitalism" or even "Is a small business owner without employees a capitalist is marxist economics?" would be less ambiguous.
My personal feeling is that well-specified questions on Marxist economics should, in principle at least, be on topic here. It needs a bit of policing to keep out Marxist rants and such, but helping to understand the history of economic thought, and using the modern tools of economic to debunk outmoded ways of thinking about the economy seem to be in remit.
Comment: This answer reflects my own views on the subject, but being on the meta site I accepted the majority answer to create consensus.


How to use user feedback from Webforms

Question: Say I want to ask the user to rate articles on usefulness from 1-10.
How can I apply that rating to weight calculations for future searches of the same issue/tags?
I would like the most useful articles to appear higher in the search results.
Answer: Best using of any of below module to solve your query. I think as per your query, no any module for 1-10 rating. Hope these module help you to do same as you want.

Star Rating

Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.

Rate

This module provides flexible voting widgets for nodes and comments.

Fivestar

The Fivestar voting module adds a clean, attractive voting widget to
  nodes and comments and any entity.
Comment: I have update my question. @KrishnaMohan I have just suggest OP to use any of these modules. It's not correct or wrong way to suggest then pls update if any text needed or I'll delete from here & next tym I'll aware of these.
Comment: No no you are correct. I am sure Rate module can solve OP's query. :)
Answer: Refer to my answer to the question about "Is there a Drupal rating module that lets you rate from 1 - 10?" for an "inventory" of rating related modules.
Note that quite a few of these modules have the VotingAPI module as a dependency.
To actually "apply that rating to weight calculations for future searches", you might consider including these rating results via an appropriate set of fields in a "View" that you'd created to display your search results, which you'd probably then also want to "sort" by the rating results (like 'highest rated' first).

How to use user feedback from Webforms


How should I configure the wysiwyg filter to align the images?

Question: This is how my configuration in the wysiwyg filter looks like (in Drupal7):
a[!href|target<_blank|title],
img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd

However my configuration does not work for aligning images.
I have reviewed my code and the alignment is done using the "style" tag:

I tried the following configuration for the image but that does not work either:
img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float|**style**],

Here is another attempt that did not work:
@[style]

And I also tried like so:
img[*],

Another attempt is what is detailed in this alternative: http://screencast.com/t/jUOwMxmpu
So what is the right configuration for the images to be aligned? What is my error?
Comment: Maybe you still have Drupal's default "Limit allowed HTML tags" filter enabled, besides wysiwyg_filter? This filters out any inline css styles on display.
Answer: Some people forget to turn off the built-in HTML Filter when they enable the WYSIWYG Filter.  If you double-filter, you will lose your img attributes.
For my part, though, I prefer to not put the float on the img; instead, I float the div that surrounds the image and caption, allowing them to float together.  (Example image, with floated caption "A battle...": http://www.westkingdom.org/content/new-members).  To give the content editors a good user experience, I allow them to set floats on images with ckeditor, but I move the markup to the div in a render hook when the content is displayed.  In this scenario, I don't need to allow floats on the image at all.
I have a writeup of how I achieved responsive images with captions using media 2.0, wysiwyg filter, and a couple other modules, and a couple of custom hooks.
Answer: You need to whitelist the style attribute on your image tag img[!src|style] and then you need to also whitelist the style properties that can be used. You should see a "Layout Properties" group of checkboxes, check the one that says "float."
Comment: I tried to configurate with your suggests:  http://screencast.com/t/WCupjASwmy44 and http://screencast.com/t/74iOevHtL9f and nothing.  Thanks for your help and thanks for your answer.
Comment: Did you clear your cache? I just tested the configuration on a clean install and it works.
Comment: I cleared cache and nothing.  The images on the editor are not alignment.


Criar um SlideShow somente com Html e CSS

Question:

<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Projeto 01</title>

Home

News

Redes Sociais

Blog

❮

❯

CSS
#container {
    background: white;
    display: both;
}
.topo {
    height: 200px;
    background-color: teal;
    box-shadow: 0 0 08px;
    margin: 10px;
}
.topo p {
    color: #000;
}
.topo ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}
.topo li {
    float: left;
}
.topo li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}
.topo li a:hover {
    background-color: #111;
}
.conteudo {
    display: block;
    border-radius: 04px;
    box-shadow: 0 0px 05px 0;
    margin: auto;
    padding: 20px;
    width: 60%;
    height: 600px;
    background-color: orange;
    float: both;

}
.conteudo p {
    color: #000;
}
.esquerda{
    width: 15%;
    height: 400px;
    background-color: ;
    border: 1px solid #000;
    margin: 30px;
    border-radius: 03px;
    float: left;
    }
.direita {
    width: 15%;
    height: 400px;
    background-color: ;
    border: 1px solid #000;
    margin: 30px;
    border-radius: 03px;
    float: right;
}

#rodape p {
    text-align: center;
    color: black;
    font-size: 16px;
}
.mySlides {display:none}
.w3-left, .w3-right, .w3-badge {cursor:pointer}
.w3-badge {height:13px;width:13px;padding:0}

Possuo pouco conhecimento na área de desenvolvimento. Conheço apenas o básico em Html e CSS (não sei javascript ou jquery).
Mas ainda sim, preciso criar um pequeno slide para um projeto que estou desenvolvendo.

Preciso adicionar as imagens em uma pequena DIV lateral, em que exiba apenas uma imagem e uma legenda/descrição logo abaixo NÂO sobrepondo a imagem;
Com botão de Próximo e Anterior;
A legenda/descrição precisa ser atualizada junto a imagem;
Preciso saber como esconder as imagens e fazê-las aparecerem em determinado tempo;
Fiz pesquisas, mas não obtive conhecimento ou entendimento sobre;
Como se trata somente de Html e CSS, não se encontra muito na internet;
Num livro que estava lendo CSS - do iniciante ao profissional Li sobre Overflow e animation. Mas não sei  como aplicá-los;
E até agora não sei como devo construir a estrutura para tal;
Comment: Tem um exemplo na W3School muito bom
https://www.w3schools.com/howto/howto_js_slideshow.asp Trabalha com CSS e javascript puro, e não precisa instalar plugins ou jquery. O que ajuda no desempenho.
Answer: A criação de um slider apenas utilizando CSS sem requerer o uso de Javascript para nos dar um maior controlo de eventos consoante a interação do usuário, é um conceito um pouco complexo. Mas no entanto possível de se fazer.
Eis alguns plugins que encontrei após ter feito uma breve pesquisa:

PureCssSlides - Página de demonstração aqui
Responsive CSS3 Slider
Basic CSS Image Slideshow - Página de demonstração aqui

Aqui abaixo tens a maneira mais simples de criar um simples slider apenas com CSS, que se auto inicia, usando animations. (codepen)

*{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
body {
  background: #e9e1c1;
  margin: 0;
  font-family: monospace;
}
h2 {
  text-align: center;
}
a {color: #19838d;}

.container {
  margin: 50px auto;
  padding-bottom: 28%;
  width: 60%;
  overflow: hidden;
  border: 15px solid #fff;
  position: relative;
  display:block;
  margin: 40px auto 40px;
  box-shadow: 0 10px 10px #777;
}

.photoWrapper {
  position: absolute;
  animation: round 16s infinite;
  opacity: 0;
  top: 0;
  left: 0;
}
.photo {
  height:auto;
  width:100%;
}
p.photoDescr {
  background-color: #8e8e8e;
  margin: 0;
  padding: 5px;
}

@keyframes round {
  25% {
    opacity: 1;
  }
  40% {
    opacity: 0;
  }
}
.photoWrapper:nth-child(1) {
  animation-delay: 0s;
}

.photoWrapper:nth-child(2) {
  animation-delay: 4s;
}

.photoWrapper:nth-child(3) {
  animation-delay: 8s;
}

.photoWrapper:nth-child(4) {
  animation-delay: 12s;
}
@media (max-width: 728px) {
  .container {
    width: 90%;
    padding-bottom: 50%;
  }
}

Podes tambem ver outra solução funcional mais visual com botões prev, next etc exatamente como querias sem requerer o uso de Javascript e onde podes ter uma idea de como trabalhar o código CSS para criar tal funcionalidade: CSSdeck - Pure css slider

* {
    margin: 0;
    padding: 0;
    /*transition*/
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    transition: all 1s ease;
}
body {
    background: -webkit-radial-gradient(center, circle, #f0f0f0, #74a9ad);
    background: -moz-radial-gradient(center, circle, #f0f0f0, #74a9ad);
    background: -ms-radial-gradient(center, circle, #f0f0f0, #74a9ad);
    background: -o-radial-gradient(center, circle, #f0f0f0, #74a9ad);
    background: radial-gradient(center, circle, #f0f0f0, #74a9ad);
    padding: 50px;
}
/* Slider */
.slider {
    height: 250px;
    left: 50%;
    margin: -125px -225px;
    position: absolute;
    top: 48%;
    width: 450px;
    /*box-shadow*/
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
}
.slider .frames {
    height: 250px;
    position: relative;
}
.slider .frames .slide {
    height: 250px;
    list-style: none;
    position: absolute;
    width: 450px;
}
.slider .slide:target { z-index: 100 }
.slider .frames .slide img {
    height: 250px;
    width: 450px;
}
.slider .frames .slide nav a {
    background: hsla(0,0%,0%,.75);
    color: #fff;
    font-size: 16px;
    line-height: 50px;
    margin-top: -25px;
    opacity: 0;
    position: absolute;
    text-align: center;
    text-decoration: none;
    top: 50%;
    width: 50px;
    visibility: hidden;
    z-index: 10;
}
.slider:hover .frames .slide nav a {
    opacity: 1;
    visibility: visible;
}
.slider .frames .slide nav .prev {
    /*border-radius*/
    -webkit-border-radius: 0 25px 25px 0;
    -moz-border-radius: 0 25px 25px 0;
    border-radius: 0 25px 25px 0;
    left: 0;
}
.slider .frames .slide nav .next {
    /*border-radius*/
    -webkit-border-radius: 25px 0 0 25px;
    -moz-border-radius: 25px 0 0 25px;
    border-radius: 25px 0 0 25px;
    right: 0;
}
.slider .frames .slide nav a:hover { background: #000 }
.slider .quicknav {
    bottom: 0;
    font-size: 0;
    opacity: 0;
    position: absolute;
    text-align: center;
    width: 100%;
    z-index: 100;
}
.slider:hover .quicknav { opacity: .9 }
.slider .quicknav li { display: inline-block }
.slider .quicknav a {
    background: hsla(0,0%,100%,.9);
    border: 1px solid hsla(0,0%,0%,.9);
    /*border-radius*/
    -webkit-border-radius: 100%;
    -moz-border-radius: 100%;
    border-radius: 100%;
    display: block;
    height: 10px;
    margin: 10px 5px;
    text-decoration: none;
    width: 10px;
}
.slider .quicknav a:hover { background: hsla(0,0%,50%,.9) }
.slider #one:target ~ .quicknav a[href="#one"], .slider #two:target ~ .quicknav a[href="#two"], .slider #three:target ~ .quicknav a[href="#three"], .slider #four:target ~ .quicknav a[href="#four"], .slider #five:target ~ .quicknav a[href="#five"] {
    background: hsla(0,0%,0%,.9);
    border-color: hsla(0,0%,100%,.9);
    background: rgb(244,246,245);
    /*linear-gradient*/
    background: -webkit-gradient(linear,left top,left bottom,color-stop(rgba(244,246,245,1),0.01),color-stop(rgba(203,219,219,1),1),color-stop(rgba(216,216,216,1),1));
    background: -webkit-linear-gradient(top, rgba(244,246,245,1) 1%, rgba(203,219,219,1) 100%, rgba(216,216,216,1) 100%);
    background: -moz-linear-gradient(top, rgba(244,246,245,1) 1%, rgba(203,219,219,1) 100%, rgba(216,216,216,1) 100%);
    background: -o-linear-gradient(top, rgba(244,246,245,1) 1%, rgba(203,219,219,1) 100%, rgba(216,216,216,1) 100%);
    background: linear-gradient(top, rgba(244,246,245,1) 1%, rgba(203,219,219,1) 100%, rgba(216,216,216,1) 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,rgba(244,246,245,1)), color-stop(100%,rgba(203,219,219,1)), color-stop(100%,rgba(216,216,216,1)));
    background: -webkit-linear-gradient(top, rgba(244,246,245,1) 1%,rgba(203,219,219,1) 100%,rgba(216,216,216,1) 100%);
    background: -moz-linear-gradient(top, rgba(244,246,245,1) 1%,rgba(203,219,219,1) 100%,rgba(216,216,216,1) 100%);
    background: -o-linear-gradient(top, rgba(244,246,245,1) 1%,rgba(203,219,219,1) 100%,rgba(216,216,216,1) 100%);
    background: linear-gradient(top, rgba(244,246,245,1) 1%,rgba(203,219,219,1) 100%,rgba(216,216,216,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f6f5', endColorstr='#d8d8d8',GradientType=0 );
    /*box-shadow*/
    -webkit-box-shadow: inset 0 0 3px #000,0 0 2px rgba(0,0,0,.5),0 2px 3px #666;
    -moz-box-shadow: inset 0 0 3px #000,0 0 2px rgba(0,0,0,.5),0 2px 3px #666;
    box-shadow: inset 0 0 3px #000,0 0 2px rgba(0,0,0,.5),0 2px 3px #666;
}

                ←
                →

                ←
                →

                ←
                →

                ←
                →

                ←
                →

Comment: Nossa!! Meu amigo!!! Muito obrigado, Vou testar todos aqui.
Comment: Bom, muito obrigado. Funcionou bem os slides; Agora preciso descobrir como implementar, a descrição a DIV e atualiza-la junto a imagem
Comment: Um exemplo de como o fazer no ultimo exemplo: [jsFiddle demo](https://jsfiddle.net/shuffledPixels/ttga5953/)


Procmail multipart message / content type

Question: I have a procmailrc file that is collecting some variables from mail headers, then echo'ing those variables into the message body. Like this:
:0bfw
| echo Subject_ "${SUBJECT_}" ; echo From_ "${FROM_}" ; echo To_ "${TO_}" ; echo CC_ "${CC_}" ; echo "" ; cat

This works okay in general. It is correctly echo'ing what I want it to echo. But it's echoing those variables into a separate part of the message, like this:
Content-Type: multipart/alternative; boundary=001a11c1367a19ff420508126c21

Subject_  Subject variable is here
From_  variable@whatever
To_  variable@whatever
CC_

--001a11c1367a19ff420508126c21
Content-Type: text/plain; charset=UTF-8

The rest of the message body is here, in a separate message part.

How can I make procmail echo those variables into the same part of the message as the rest of the email body?
Answer: This is slightly tricky because not all messages are MIME messages, and not all MIME messages are multipart messages.  The following is thus probably a bit too simplistic, but works in my limited tests.
:0fbw
* ^MIME-version:
* ^Content-type:[   ]*multipart/[^-a-z0-9_]*;[  ]*boundary="?\/[^   "]*
| awk "!q&&/^--$MATCH/{h=1}h&&/^$/{h=0;p=1}\
    !q&&p&&!/^$/{print \"Subject_ $SUBJECT_\"; print \"From_ $FROM\";\
        print \"To_ $TO\"; print \"CC_ $CC\"; print \"\"; p=0; q=1 }1"
:0Efbw
| echo blah blah  # Your original attempt here

The Awk script locates the first MIME boundary, then the first empty line after that, then inserts the snippet, and sets a couple of state variables to prevent further processing.  Unfortunately, the script is slightly brittle; it will fail if one of the extracted values contains unpaired double quotes, and process paired double quotes incorrectly.
Furthermore, this will only work correctly if the first body part within the multipart is a text part; it will fail similarly to your current case if you have nested multiparts (top-level message multipart/related containing a multipart/alternative structure, for example).  It can be extended to cover more cases -- a simple tweak would be to skip up to the first Content-Type: text/plain instead --, but at some point, it will make more sense to do the MIME manipulation in a properly MIME-aware tool (a simple Python script, for example).


rsync script to nightly backup var

Question: Having trouble with making a backup script for automatically updating the var folder to another server nightly
BDATE=`date +%F`
 rsync --exclude=foldera/folderb -bavz --backup-dir=backup-$(BDATE) email@example.com:/path/to/var

This doesn't seem to be working when I run it, have I done something wrong?
Cheers
Answer: $( ) is command substitution, like the backticks:  `` If you are trying isolate a variable you use curly braces, e.g., ${foo}_bar will reference the var foo. In this case, $BDATE doesn't need any such isolation. FYI $(( )) is arithmetic evaluation.
Answer: At a first glance, your problem seems to be the --backup-dir flag. The $(BDATE) won't expand to the date. Just try this from a terminal:
BDATE="14-06-2011"
echo $BDATE  --> 14-06-2011
echo foo-$(BDATE) --> DATE: command not found  foo-
if you use this foo-$BDATE it will work:
echo foo-$BDATE --> foo-14-06-2011
Also, can you please post the output if it still doesn't work?

rsync script to nightly backup var


How long does a fielder have to wait before he can bat if he has missed the whole of his side's fielding session?

Question: I know if a fielder is absent for a period of more than 15 minutes, the current Law restricts when he may come on to bowl when he returns to the field of play. But does the Law mention anything about waiting time before batting if fielder has missed the whole of his side's fielding session.
If there is no Law for this situation, how do they deal with it?
Answer: There is nothing in the Laws of the Game about this, therefore there is no restriction in general: the player may bat as soon as their team's innings commences.
However, the standard ICC Test Match Playing Conditions contain the following clause (2.2.2):

The player [who has been off the field] shall not be permitted to bat in the match until his team's batting innings has been in progress for the length of playing time that is equal to the unexpired penalty time carried forward from the previous innings, subject to a maximum cumulative penalty time of 120 minutes. However, once his side has lost five wickets in its batting innings, he may bat immediately.

i.e. a player who was off the field for the whole innings can only bat once one of the following happens:

The batting team's innings has lasted as long as the previous innings
Two hours have elapsed
The fifth wicket has fallen

The ODI and Twenty20 International Playing Conditions contain the same clause, except that there is a maximum penalty of 40 minutes in T20 internationals.
Comment: sir, this will be covered by the new code of laws 25.3 which will be effective after 1 October 2017.

How long does a fielder have to wait before he can bat if he has missed the whole of his side’s fielding session?


Find all points in a closed convex shape drawn on a hexagonal lattice using chain codes (lengths of sides)

Question: Borrowing from Ohn (1999)1 and shortening the notation, it seems that a convex shape on a hexagonal grid can be produced by proceeding in the first of six directions an integer distance $e_0$, turning right by 60° and proceeding a distance $e_1$ and repeating to produce the six-tuple $e_0, e_1, e_2, e_3, e_4, e_5$ such that you return to the starting position.
 click for full size

Figure 3. Example HCSE (hexagonal convex structuring element) P. The chain code of the boundary of P is 051324334552 starting with point $S$.

If as shown in the image below ($e_0, e_1, e_2, e_3, e_4, e_5 = 5, 3, 4, 3, 5, 2$) the directions $\hat{x}$ and $\hat{y}$ form an acute 60° angle with $e_3$ counted in the $\hat{x}$ direction and $e_2$ counted in the $\hat{y}$ direction, and assuming we start at position (0, 0), the final position will be given by.
$$x=-e_0 - e_1 + e_3 + e_4$$
$$y=e_1 + e_2 - e_4 - e_5$$
If I want to generate all convex shapes with maximum side length $n_{max}$ (counting all six rotations of a given shape as distinct), I can first generate all six-tuples with $0 \le e_i \le n_{max}$ then keep only those that represent closed paths, i.e. that satisfy
$$e_0 + e_1 = e_3 + e_4$$
$$e_1 + e_2 = e_4 + e_5$$
If I don't want to consider the sixfold rotations of a shape as distinct, I (think that I) can discard any six-tuple that is a cyclic permutation of a previous six-tuple.
I can imagine how to reconstruct all of the lattice points on the perimeter2, but I don't know how to find all of the lattice points inside as well.
Question: Find all points in a closed convex shape drawn on a hexagonal lattice using chain codes (lengths of sides)
In other words, I want to plot all the filled circles (occupied lattice points) shown in the image, not just the $n = e_0 + e_1 + e_2 + e_3 + e_4 + e_5$ points on the edge.

1Syng-Yup Ohn (1999) Optimal Decomposition of Convex Structuring Elements
on a Hexagonal Grid The Jourmal of the Acoustical Society of Korea, Vol. 18. No. 3E
2For the example these would be $(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (-5, 0), (-6, 1), (-7, 2)... (-2, 4), (-1, 3), (0, 2), (0, 1)$
Comment: Can you use $e_i$ to determine the points on the perimeter? From there, you can easily figure out which points lie in the interior, like by fixing $y$ and considering when $x$ is valid.
Comment: potentially helpful: [Hierarchical Hexagonal Clustering and Indexing](https://doi.org/10.3390/sym11060731) Uher et al () Symmetry 2019, 11(6), 731, "robust hexagonal Node-Gosper space filling curve based on the Gosper fractal"
Answer: This is more a collection of hints than a fully-worked out answer, but here goes:
You can easily get the number of points on the boundary, and you can get the area enclosed as an integral around the boundary. Then you need a version of Pick's Theorem that holds for the hexagonal lattice to get an equation relating the number of boundary points, the area, and the number of internal points. The discussion at Pick's Theorem on a triangular (or hex) grid says there isn't any such version of Pick's Theorem, but there is an approximate version that may be good enough for your purposes.
Comment: If there aren't any zeros, then you're guaranteed to get a hexagon, aren't you? Now if you get a hexagon, like the one in your picture, you can extend the 2nd, 4th, and 6th sides until they intersect each other, and that gives you a big equilateral triangle, which consists of your hexagon plus a smaller equilateral triangle at each corner. I expect that in your quad and pent cases, similar extensions of sides will result in big equilateral triangles formed by the quad or pent and one or more small equilateral triangles.
Comment: @uhoh It's a very simple approach, very little mess from what I can tell. If you get stuck, show what you've tried and ping me to help you work it out.
Comment: I got stuck... dealing with other deadlines, not mathematically. I really want to accept this as I now see how this is going to work even though I haven't come back to implement it... yet. If I wait another month I may forget, so here goes! *Thanks!*
Comment: Thanks I will take a look. I just left a comment under the question about "space filling curve based on the Gosper fractal" which might (or might not) work here as well.
Comment: The number of interior points can easily be worked out by completing to the large equilateral triangle and subtracting accordingly. $\quad$ In the general case for the hexagonal board, there is no formula that depends only on those variables.
Comment: @CalvinLin ya I just need an *algorithm* for finding each of interior points, not a formula for the number of them.
Comment: I think the idea of @Calvin can work for finding the points, not just the number of points. Complete to a large equilateral triangle; it should be easy to list all the points in that triangle, and to list the points in the three small triangles that are outside the hexagon, and delete the second set of points from the first.
Comment: @GerryMyerson okay the convex shapes can be anything from a single row (0n00n0), to an equilateral triangle (0n0n0n), to irregular quads, pents or hexes. I wouldn't know how to begin to "complete to a large equilateral triangle" for such a variety of shapes much less know what to do next. While I'm faced with this challenge today, it's a whole new thing for me. Hopefully algorithmicly-minded individual will have mercy on me and find spelling out the procedure worthwhile :-)
Comment: @GerryMyerson Okay, yes I get the idea now. :-) I'll take a look in the morning, *thanks!*
Comment: ...but I think that's going to be fairly messy algorithm to write such that it covers all edge cases; I wish there was something that didn't involve constructions.


Website saved to homescreen (ios) force open in safari

Question: I am working on somewhat of a webapp, the client would like the ability to save to homescreen (default behavior) but when the end user opens the app saved to the homescreen it opens in safari rather then in "webapp" mode.
An example of such is on espn's mobile site:
http://m.espn.go.com/
Note by saving to homescreen, then accessing... It opens in safari.
Thanks!!
Answer: I believe the web app will always open in Safari, but you can change the behavior of how it opens so it might not feel like it's opening in Safari. Check out these page on how to use some apple-specific meta tags:
https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
https://code.tutsplus.com/tutorials/configuring-an-iphone-web-app-with-meta-tags--mobile-2133
Answer: <meta name="apple-mobile-web-app-capable" content="yes" />

Answer: IOS provides us the feature to open the app in StandAlone mode.
You use the HTML5 specs of Safari but remember this runs out of the safari sandbox ie. It will act as a native app and will stop javascript executions on sleep or screen off.
Just add the meta tag
<meta name="apple-mobile-web-app-capable" content="yes"   />

The latest Versions of Android Chrome also have this feature in them and are much closely related to the Chrome Environment.
Just add this meta tag for android chrome.
    <meta name="mobile-web-app-capable" content="yes">


SQL 2008 Find out what licensing it is using.

Question: How can I tell the licensing that is setup on a production SQL server?
Comment: This is not a dupe. The s/w licencing question you reference is for *legal* issues with licences, not how to carry out licence related sysadmin tasks.
Comment: possible duplicate of [Can you help me with my software licensing issue?](http://serverfault.com/questions/215405/can-you-help-me-with-my-software-licensing-issue)
Comment: This is going to get closed as a licensing issue.  It might be a better fit for dba.stackexchange.com, but check their FAQ first.
Comment: Its not a licensing issue really.
Answer: <code>SELECT CONVERT(char(20), SERVERPROPERTY('Edition'))
SELECT CONVERT(char(20), SERVERPROPERTY('NumLicenses'))
SELECT CONVERT(char(20), SERVERPROPERTY('LicenseType'))
</code>
PER_SEAT = Per-seat mode
PER_PROCESSOR = Per-processor mode
DISABLED = Licensing is disabled.
Comment: Please accept the answer if it was what you needed. Thanks. :)


How to make a theme hook suggestion for blocks according to region?

Question: Since Drupal 8 it is not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed"). But I need to have different html for blocks if placed in a certain region. How do I accomplish this?
I've thought about using MYMODULE_theme_suggestions_block_alter but I don't know how to get the current region.
Answer: You can get region if you get Block Entity.
.module or .theme file
<code>use Drupal\block\Entity\Block;

function MODULE_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }
  /* Use this 'else if' only if you are using page_manager module and want to know which region is the block */
  else if (isset($variables['elements']['#configuration']['region'])) {
    $suggestions[] = 'block__page_' . $variables['elements']['#configuration']['region'] . '__' . end(explode(':', $variables['elements']['#plugin_id']));
  }
  return $suggestions;
}
</code>
Edit 1: Cover page_manager module case.
Comment: Almost perfect. You need to add an isset() to make sure that the #id is really there. For example, if you use page_manager and place blocks in there, then you won't have an #id.
Comment: @Berdir thanks ;) . I think that in this case `isset()` is not required, because if there isn't an `#id`, then it pass `NULL` to `::load` function, and just return `NULL`. In the end, `$block` is `NULL` and nothing will happen. Tested in my dev env Drupal 8.0.4 - page_manager-1.0-alpha23 (never used this module before).
Comment: Yes, isset() is required. accessing an array key that doesn't exist results in a PHP notice. Check your logs and you'll see. I would recommend to always develop with error display on verbose, which is the default of the provided example settings.php.
Comment: You don't need `return $suggestions;` at the end since that variable is passed by reference.


Como inserir o WP previous_post_link(); ancorado em uma div

Question: Boa noite, estou querendo criar uma navegação personalizada entre single-posts no Wordpress, mas não sei como fazer, e não quero usar um plugin pra isso, vejam o que estou tentando fazer (Sem Nenhum Sucesso!):
*.php
<a href="<?php next_post_link();?>">

    <a href="<?php previous_post_link(); ?>">

*.css
.seta-prev{
    padding:15px 20px;
    border:6px solid #ccc;
    border-radius:50px;
    float:left;
    margin:0 10px;
    box-shadow: 0 0 4px rgba(0,0,0,0.7);
    transition:all linear 0.2s;
}
.seta-prev i{
    border-right: 20px solid #ccc;
    border-top: 15px solid transparent;
    border-bottom: 15px solid transparent;
    float:left;
}

.seta-prev:hover{
    transform: rotateX(180deg)
}

.seta-next{
    position: relative;
    padding:15px 20px;
    border:6px solid #ccc;
    border-radius:50px;
    top: 50%;
    float:right;
    margin:0 10px;
    box-shadow: 0 0 4px rgba(0,0,0,0.7);
    transition:all linear 0.2s;
}
.seta-next i{
    border-left: 20px solid #ccc;
    border-top: 15px solid transparent;
    border-bottom: 15px solid transparent; float:left;
}

.seta-next:hover{
    transform: rotateX(180deg)
}

Answer: Resolvi meu problema gente:
<?php $prev_post = get_previous_post(); ?>
<?php $next_post = get_next_post(); ?>
<a href="<?php echo esc_url( get_permalink( $prev_post->ID ) ); ?>">

<a href="<?php echo esc_url( get_permalink( $next_post->ID ) ); ?>">


Active Directory - Define logon hours from Group Policy (Windows 2003 R2)

Question: I have a bunch of computers in an OU in my Active Directory.
These computers are located on a theoretically less secure site (they are in a warehouse)
I want to stop these computers being logged in to (by anyone) between certain hours... Can I do this in Group Policy?
I've seen "Logon Hours" in the account tab in AD but this isn't quite what I want... I wan't to stop the computers from logging in using ANY account between certain times...
Answer: There isn't functionality built-in to Windows to do what you're looking for.
The idea below is a cheap hack and could easily be subverted, but it might get you what you want w/o using third-party software.
If I were going to do what you're trying to do, I'd build a security template that adds "Users" to the "Deny logon locally" user right assignment, and a second one that removes it (i.e. sets it back to the stock "Guest" only). Once those are built and tested (be careful testing it-- it'll stop even "Administrator" from being able to logon locally) I'd write a script to apply the security templates using a scheduled task. At the appropriate time, apply the template to prevent interactive logons, and then apply the template to restore the ability to logon interactively.


How to get all the likes of a twitter user using tweepy

Question: I'm using tweepy with 1.1 API and Elevated access.
I have been trying to request all the likes of a user but there seems to be a limit of about 1430 returned tweets. I've tried with a couple of test accounts and it seems to get 1430-1440 then a "Too Many Requests - Rate limit exceeded" error is returned.
This is the call:
tweepy.Cursor( api.get_favorites, screen_name=twitterUsername ).items( 3000 )
When I call rate_limit_status() the only out of limits value is '/favorites/list', but the limit appears to be 75:
Limit:75 Remaining: 0 Reset: {timestamp for 15 minutes later}.
Frustratingly, initially the rate limit seemed to be more generous (over 2500 tweets were returned)
Is there a way to work with Twitter's limits so that I can have access and work with all the likes of a user?
Or at least is there a way to ask for the likes before a certain date?
Answer: Pay careful attention to the word "rate" in that diagnostic.
It refers to "records per hour",
rather than "total number of records".
Twitter offer extensive documentation on this topic:
https://developer.twitter.com/en/docs/twitter-api/rate-limits#recovering
You obtained a 429 status because you ignored the
rate limit. Just sleep() a bit between requests.
Code that does a one-off query and fails to sleep
will more likely trigger a rate error
when querying many records back-to-back
than when querying few records.
Consider using the excellent tenacity back-off / retry library.
Comment: Thank you very much for your response. I'm not sure how to combine sleeping with the big api.get_favorites request. If I hit the limit and sleep, when I rerun the request I will get the same results (tweets starting from today and arranged according to descending date). The earliest tweets are not returned. Is there some way to request them? Or pickup where we left off before sleeping?


$\iint \sqrt{1-y^2}$ on a disk. Converges and satisfies Fubini, but doing it as an iterated integral diverges?

Question: I am trying to evaluate the integral:
$$\iint_D \sqrt{1-y^2} dx dy$$
Where D is the disk centered at $(1, 0)$ and with radius 1.
Notice that this integral clearly converges: in the disk, $y^2<1$, so $|\sqrt{1-y^2}|<1$. This also means the integral satisfies Fubini.
One change of variables $(x, y) \mapsto (x+1, y)$ moves the circle to the origin, and leaves the integrand unchanged. I then change to polar coordinates: $(\rho, \theta) \mapsto (\rho\cos \theta, \rho \sin \theta)$ obtaining:
$$ \int_0^{2\pi} \int_0^1 (1-\rho^2\sin^2\theta)^\frac12\rho \ d\rho d\theta $$
I found an antiderivative of the integrand as a function of $\rho$:
$$ -\frac 1 {3\sin^2\theta} (1-\rho^2\sin^2\theta)^\frac32 $$
Evaluating it at $0$ and $1$ reduces the inner integral to the following:
$$ \int_0^{2\pi} -\frac 1 {3\sin^2\theta} \left [ (1-\sin^2\theta)^\frac32-1 \right ] d\theta$$
This simplifies to:
$$ -\frac {1} 3 \int_0^{2\pi} \frac{\cos^3\theta-1}{\sin^2\theta}d\theta$$
But Wolframalpha says this does not converge.
Where did I go wrong?
Comment: Check your anti-derivative again.
Comment: More specifically, is $(1-\sin^2\theta)^{3/2}$ really $\cos^3\theta$?
Comment: Oh. Is it because $(x^2)^\frac32 = |x^3|$ and I forgot the absolute value?
Comment: That is correct. :)
Answer: Thanks to the helpful comments above, this is the problem:
$$ (\cos^2\theta)^\frac32 = | cos^3\theta|$$
Because $ \cos^2\theta$ is always positive.
The rest of the integral is as follows:
First, notice that both $\sin^2\theta$ and $|\cos\theta|$ have period $\pi$ and not just $2\pi$. Then further notice that they are even around $\pi/2$. With this, $\int_0^{2\pi} f(\theta)d\theta = 4\int_0^\frac\pi2 f(\theta)d\theta$. More specifically, the integral becomes:
$$ -\frac43 \int_0^\frac\pi2 \frac {\cos^3\theta -1}{\sin^2\theta}d\theta $$
Where I dropped the absolute value because $\cos(\theta)$ is always positive on this new domain anyways.
I have an antiderivative of the integrand:
$$ \frac {-1-\sin^2\theta+\cos\theta} {\sin\theta} $$
Which evaluates as $-2$ at $\frac\pi2$ and as $0$ at $0$ (taking the limit).
Therefore the integral evaluates as $-\frac43[-2-0]=\frac83$.


Vaadin SpringBoot Autowire a @SpringView annotated class -> instantiation of ViewCache fails

Question: As topic says: shouldn't I be able to autowire a @SpringView annotaed class with vaadin and spring boot addon. I get an unsatisfied dependency exception. Adding @SpringComponent does not do the trick. Help appreciated
Edit:
I just want to Autowire a class that is annotaed @SpringView (autowireing @SpringCOmponent works apperently)
I dug deeper and found that it has Failed to instantiate [com.vaadin.spring.internal.ViewCache]
Code would be:
<code>@SpringView
Foo{
}
</code>
full Exception is:
<code>Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [cuscus.client.ui.presenter.LoginPresenter]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'viewCache' defined in com.vaadin.spring.VaadinConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.vaadin.spring.internal.ViewCache]: Factory method 'viewCache' threw exception; nested exception is java.lang.NullPointerException] with root cause
</code>
regards Chris
Comment: Hi and welcome to SO. If you did not already have the chance, take a minute to familiarize yourself with the [_How do I ask a good question?_](https://stackoverflow.com/help/how-to-ask) topic. Afterwards, if posting a [sscce](http://sscce.org) is not possible, please share at least a description of your scenario (what you're trying to achieve), the stacktrace of your exception and the relevant code. As your question stands now, there is little information to go by...
Answer: Usually this null pointer exception happens because the current UI instance is not initialized at the time of the bean instantiation. To solve this issue use @SpringComponent and @UIScope annotation together on views which are (for example) injected into your UI class.


Spam domains in error log

Question: I can see a strange domain request in my error log:

2011/11/03 09:04:18 [error] 1203#0: *4044 FastCGI sent in stderr:
  "Successfully fetched
  'http://jeannie733.2itb.com/oxycodonepricesideef.html': GET response
  code 200" while reading response header from upstream, client:
  126.96.36.199, server: contra.net.au, request: "POST /wp-comments-post.php HTTP/1.1", upstream:

Does this indicate my site has been hacked?
Answer:
Does this indicate my site has been hacked?

No, it means that a spam bot is trying to bypass the comments form. You can stop it by adding the belows config to server context in nginx.conf:
    set $poster "";
    if ($request_method = POST) {
        set $poster "${poster}P";
    }
    if ($request_uri = /wp-comments-post.php) {
        set $poster "${poster}W";
    }
    if ($http_referer !~ ^(jeannie733.2itb\.com) ) {
        set $poster "${poster}R";
    }
    if ($http_user_agent = "") {
        set $poster "${poster}U";
    }
    if ($poster = PWRU) {
        return 444;
    }

The 444 status code makes Nginx returns no information to the client and closes the connection.

Spam domains in error log


Lógica de Fila - Python

Question: Estou com uma dúvida em uma questão, e espero que vocês possam me ajudar, a dúvida em si não é na forma de desenvolver a questão, isso não é o problema, o problema está na lógica da questão que eu não estou conseguindo entender, a questão é a seguinte:

A legislação em vigor obriga os bancos a iniciarem o atendimento a um
  cliente em no máximo 20 minutos após a entrada do cliente na fila
  única da agência bancária. A fila é única, assim um caixa livre
  solicita ao primeiro cliente da fila que venha ao seu guichê para ser
  atendido. (Vamos ignorar aqui o problema dos clientes prioritários,
  idosos, gestantes, portadores de necessidades especiais, etc.) Estamos
  supondo também que nenhum caixa atende dois clientes ao mesmo tempo.
Seu programa receberá o número de caixas ativas na agência, o número
  de clientes e, para cada cliente, duas informações, a saber, o momento
  de entrada do cliente na fila, e a duração do atendimento daquele
  cliente. Inicialmente todos os caixas estão vazios, já que a agência
  acabou de abrir. Seu problema é determinar o número de clientes que
  esperarão mais de 20 minutos para ter seu atendimento iniciado.

Entrada:

A primeira linha da entrada contém dois inteiros separados por um
  espaço em branco. O primeiro, C, é o número de caixas ativas na
  agência bancária. O segundo, N, o número de clientes que procurarão
  atendimento na agência naquele dia.  As próximas N linhas terão cada
  uma informações sobre um cliente, consistindo de dois inteiros, T e D,
  separados por um espaço em branco. O inteiro T fornece o momento em
  que o cliente entra na fila, em minutos, a partir do instante de
  abertura da agência. O inteiro D fornece, em minutos, o tempo
  necessário para atender o cliente. As linhas estão ordenadas por
  entrada dos clientes na fila.
Suponha:
1 <= C <= 10 1 <= N <= 1000 0 <= T <= 300 1 <= D <= 10

Saída:

A saída deverá conter apenas uma linha, contendo um único inteiro, o
  número de clientes cujo atendimento será iniciado mais do que 20
  minutos após sua entrada na fila.

A entrada que ele dá é a seguinte:
1 5 - 0 10 - 0 10 - 1 10 - 2 10 - 30 10
Sendo o 1 o total de caixas ativos, 5 o total de clientes, e o demais a hora de chegada do cliente e o tempo que ele vai levar pra ser atendido respectivamente.
E a saída nesse caso é 1.
Então, vamos lá, pelo que eu entendi nesse caso o primeiro elemento da fila não teria tempo de espera, seria atendido diretamente, o segundo iria esperar os 10 primeiros do primeiro, por terem entrado juntos, o terceiro iria esperar os 10 minutos do primeiro, porém por ter chegado no minuto 1 iria esperar apenas 9 do segundo, totalizando 19 correto?
A partir daqui eu começo a me enrolar, o quarto, iria esperar os 30minutos dos 3 primeiros, porém por ter chegado no minuto 2 iria esperar 28min? No caso ele seria o cliente que iria estourar?
O ultimo iria chegar no minuto 30 porém como o tempo estaria em 28min ele iria esperar apenas 2min? e se por um caso chegasse um outro cliente no minuto 36 por exemplo como ficaria?
E nesse exemplo, está sendo usado apenas 1 caixa ativo, sendo que é possível ter até 10.
Será que vocês podem me da uma luz na lógica dessa questão, em como essa conta deve ser feita porque to meio perdido.
Answer: Veja a seguinte linha do tempo.
<code>(12)-(123)-(1234)--------( 234)----------( 34)----------( 45)----------( 5)----------( )
 ^^     ^      ^          1               2              3 ^            4              5
</code>

Cada traço é um minuto que se passou
Entre parênteses está a fila de clientes (o mais à esquerda está sendo atendido)
A linha de baixo indica quem entrou (com <code>^</code>) e quem saiu (baixando o número)

Analisando os eventos:

No minuto zero, o primeiro e o segundo cliente entraram e o primeiro começou a ser atendido
Passou-se 1 minuto
No minuto 1, o terceiro cliente entrou
Passou-se 1 minuto
No minuto 2, o quarto cliente entrou
Passou-se 8 minutos
No minuto 10, o primeiro cliente saiu e o segundo começou a ser atendido
Passou-se 10 minutos
No minuto 20, o segundo cliente saiu e o terceiro começou a ser atendido
Passou-se 10 minutos
No minuto 30, o terceiro cliente saiu, o quarto começou a ser atendido e o quinto entrou
Passou-se 10 minutos
No minuto 40, o quarto cliente saiu e o quinto começou a ser atendido
Passou-se 10 minutos
No minuto 50, o quinto cliente saiu

Calculando o tempo de espera:

Cliente 1 esperou 0 minutos (entrou no minuto 0, foi atendido no minuto 0)
Cliente 2 esperou 10 minutos (entrou no minuto 0, foi atendido no minuto 10)
Cliente 3 esperou 19 minutos (entrou no minuto 1, foi atendido no minuto 20)
Cliente 4 esperou 28 minutos (entrou no minuto 2, foi atendido no minuto 30)
Cliente 5 esperou 10 minutos (entrou no minuto 30, foi atendido no minuto 40)

Ou seja, o cliente 4 foi o único que esperou mais de 20 minutos, por isso a saída do programa é 1.

Lógica de Fila - Python