text:
Q: Eigenvalues of $aI + bJ$ Just as context, this problem arose when I was looking at the adjacency matrices of moore graphs of diameter 2.
Given that $I$ is the identity matrix and $J$ is the all 1 matrix. I have constructed some matrix $aI + bJ$. I am completely stuck in terms of how to find the eigenvalues of this matrix. I have considered trying to find the characteristic polynomial, but I have no idea how I would find the determinant of such a matrix.

A: Write $A = aI+ bJ$. Note that $A-aI = bJ$ has rank 1, so the eigenvalue $a$ has geometric multiplicity $n-1$.
So all that's left to do is find the other eigenvalue. Trying $\lambda=a+nb$ gives that $A-\lambda I$ has diagonal entries $(1-n)b$ and all other entries $b$. In particular, the sum of all the rows is the zero vector, so this matrix is singular.
Edit: I should note it is assumed here that $b\ne 0$. If $b=0$, then $A-aI=bJ$ is the zero matrix, which has rank 0, so $A$ has eigenvalue $a$ with multiplicity $n$.

A: here is a matrix that shows a basis of the eigenvectors as columns, these being perpendicular to each other as well. Below is the 10 by 10 case. In smaller dimension, take the upper left square corner.
$$
 \left(  \begin{array}{rrrrrrrrrr}
  1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1   \\
  1  &  1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1   \\
  1  &  0  &  2  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1   \\
  1  &  0  &  0  &  3  &  -1  &  -1  &  -1  &  -1  &  -1  &  -1   \\
  1  &  0  &  0  &  0  &  4  &  -1  &  -1  &  -1  &  -1  &  -1   \\
  1  &  0  &  0  &  0  &  0  &  5  &  -1  &  -1  &  -1  &  -1   \\
  1  &  0  &  0  &  0  &  0  &  0  &  6  &  -1  &  -1  &  -1   \\
  1  &  0  &  0  &  0  &  0  &  0  &  0  &  7  &  -1  &  -1   \\
  1  &  0  &  0  &  0  &  0  &  0  &  0  &  0  &  8  &  -1   \\
  1  &  0  &  0  &  0  &  0  &  0  &  0  &  0  &  0  &  9
\end{array}
  \right).
  $$


text:
Q: How to get left mouse click event in Tree View I have implemented a QTreeview with QAbstractItemModel how can i be notified if i click on the tree view item with left mouse click.Do we have any function like  OnLButtonDown() avalible for the tree view.
WavefrontRenderer::WavefrontRenderer(TreeModel* model , QWidget *parent) :
QMainWindow(parent)
 {
    setupUi(this);
    treeView->setModel(model);
    treeView->setDragEnabled(true);
    treeView->setAcceptDrops(true);
    treeView->installEventFilter(this);
    connect(pushButtonAddGroup, SIGNAL(clicked()), this, SLOT(insertRow()));
     connect(pushButtonAddChild , SIGNAL(clicked()), this,
    SLOT(insertChild()));
    connect(pushButtonDeleteGroup , SIGNAL(clicked()), this,
    SLOT(removeRow()));
    connect( ButtonSphere, SIGNAL(clicked()), this, SLOT(AddSphere()));
    connect(treeView , SIGNAL(clicked()), this, SLOT(message()));
 }

I tried to connect the treeview to clicked slot but this did not work for me.
Since i am new to qt i am not sure if we connect the treeview same way as we connect buttons to the clicked slots.

A: You should always check your connections:
bool ok = connect(...);
Q_ASSERT(ok);

If you do that, you'll find that connecting to the clicked() signal doesn't work.
If you then take a look at your error console you'll see a Qt message that the signal clicked() is not found in QTreeView.
That's because the parameters need to be included in the SIGNAL(...) macro.
Either put them there but just the type without the parameter name:
bool ok = connect(treeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(message()));

or avoid this pitfall by using the new connect syntax:
bool ok = connect(treeView, &QAbstractItemView::clicked, this, &WavefrontRenderer::message);

This will give you a compiler error if the signal or slot doesn't exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select Layer By Location (Management) gives different result in ArcPy and ArcMap? I have two line Shape files. When I use the Select layer by location tool to select two intersecting lines, it works fine and selects only lines which are actually intersecting.
But when I use this in Python Script by below code, it select extra lines which are not actually intersecting the Source layer line.
arcpy.SelectLayerByLocation_management("Split_Line","INTERSECT","Line")

Why this tool works different in Python script?
I am actually trying to make an offset of a given Shape line. For this I created a buffer in memory, converted it into lines, split at vertices and delete the intersecting Feature to original line.
 #specifying buffer distance
    buffer_feaure = "in_memory" + "\\" + "buffer" # temporary feature
    line_lyr = "in_memory" + "\\" "line" # temporary feauture
    #Make buffer along line
    arcpy.Buffer_analysis(InputLine, buffer_feaure, "20 Meters", "LEFT", "FLAT", "ALL")
    #Convert buffer to polyline
    arcpy.PolygonToLine_management(buffer_feaure, line_lyr)
    #Line Layer Split at vertices
    Splitline_lyr = "in_memory" + "\\" "Splitline" # temporary feauture
    arcpy.SplitLine_management(line_lyr,Splitline_lyr )
    # Selecting layer to intersecting to the line inpput
    arcpy.SelectLayerByLocation_management(Splitline_lyr,"INTERSECT",InputLine)
    # Deleting Selected Features
    if int(arcpy.GetCount_management(Splitline_lyr).getOutput(0)) > 0:
        arcpy.DeleteFeatures_management(Splitline_lyr)

It runs until it split lines at vertices and give below output.

A: You need to set your output coordinate system (in geoprocessing environment settings) to "Same As Display". This question was answered and discussed in more detail here:
Getting different results using Select by Location with ArcPy vs ArcMap?


text:
Q: Which is the equation of the trajectory of a particle? The solution to this question has left me rather confused...
Question: A particle moves with the known constant speed $v = |d\vec{r}/dt|$ on a helix. Its position is given by $$\vec{r}(t)=\begin{pmatrix} v_0t\\ r\sin(\omega t)\\r\cos(\omega t) \end{pmatrix}$$
Calculate the acceleration $\vec{a}(t)$ which is normal to the trajectory.
This is what I got:
Differentiating with respect to time gives us:
$$\vec{\dot{r}}(t)=\begin{pmatrix} v_0\\ r\omega\cos(\omega t)\\-r\omega\sin(\omega t) \end{pmatrix}$$
Differentiating again with respect to time gives us:
$$\vec{\ddot{r}}(t)=\begin{pmatrix} 0\\ -r\omega^2\sin(\omega t)\\-r\omega^2\cos(\omega t) \end{pmatrix}$$
Now, the solution says that because $\vec{\dot{r}} \cdot \vec{\ddot{r}}=0$, $\vec{\dot{r}} $and$ \vec{\ddot{r}}$ are perpendicular (I understand this). Hence $\vec{a}(t)=\vec{\ddot{r}}(t)$.
But in here, we've shown that the velocity is perpendicular to the acceleration. Are we not looking for the acceleration perpendicular to the trajectory? Shouldn't we use the equation for $\vec{r}$ instead of $\vec{\dot{r}}$?
Thanks in advance.

A: The velocity is always tangent to the trajectory so if $\vec{a}\cdot\vec{v}=0$ then $\vec{a}$ is normal to the trajectory ($\vec{a}$ is the normal acceleration).
In general, we have $\vec{a}=\vec{a}_t+\vec{a}_n$


text:
Q: Django request.user modification not happening in test I have a view that is changing a field of request.user:
def test(request):
    request.user.is_provider = False
    request.user.save()
    print(request.user.is_provider)
    return HttpResponse(status=200)

Now I am testing the function and I have the following test:
class RoleSwitchTests(TestCase):
    def test_switch_to_customer(self):
        User = get_user_model()
        user = User.objects.create_user(
            username='test',
            email='test',
            password='test',
            first_name='test',
            last_name='test',
            is_provider=True,
            is_admin=False,
        )
        self.client.login(username='test', password='test')
        response = self.client.post('/test/', follow=True)
        print(user.is_provider)
        self.assertEqual(response.status_code, 200)
        self.assertFalse(user.is_provider)

self.assertFalse(user.is_provider) fails here. For some reason, request.user.is_provider is False in test, but in test_switch_to_customer, user.is_provider is True. I know these refer to the same user because they have the same id, so why is the modification not being preserved here?

A: The view and the test are working on different User objects, that both have the same primary key. Hence changes made by the view are not done in the user in the test.
You can refetch the User object, for example with:
class RoleSwitchTests(TestCase):
    def test_switch_to_customer(self):
        User = get_user_model()
        user = User.objects.create_user(
            username='test',
            email='test',
            password='test',
            first_name='test',
            last_name='test',
            is_provider=True,
            is_admin=False,
        )
        self.client.login(username='test', password='test')
        response = self.client.post('/test/', follow=True)
        user = User.objects.get(pk=user.pk)  # fetch from database
        print(user.is_provider)
        self.assertEqual(response.status_code, 200)
        self.assertFalse(user.is_provider)

A: You should use refresh_from_db to reload the updated user from the database after the post
user.refresh_from_db()


text:
Q: Confusion in probability calculation I was referring to this wiki article related to forward and backward algorithm
Actually, I didn't get this part
$$
\frac{P(o_1,o_2..o_T,X_t=x_i|\pi)}{P(o_1,o_2..o_T|\pi)} = \frac{f_{0:t}(i)*b_{t:T}(i)}{\prod_{s=1}^{T}c_s}
$$
where f denotes the forward algorithm and b denotes the backward algorithm. I didn't get how the probability became the factor of the two. I couldn't derive it. I tried to use chain rule of probability but somehow couldn't derive it. Any suggestions?

A: Let $o_i^j=\{o_i,o_{i+1},\ldots,o_j\}$. By the chain rule for probability,
\begin{align*}
\frac{P(o_1^T,X_t|\pi)}{P(o_1^T|\pi)}&=\frac{P(o_1^t,X_t|\pi)}{P(o_1^t|\pi)}\frac{P(o_{t+1}^T|\pi,o_1^t,X_t)}{P(o_{t+1}^T|\pi,o_1^t)}\\
&=\frac{P(o_1^t,X_t|\pi)}{P(o_1^t|\pi)}\frac{P(o_{t+1}^T|\pi,o_1^t,X_t)}{\sum_xP(X_t=x)P(o_{t+1}^T|\pi,o_1^t,X_t=x)}\\
&=\frac{P(o_1^t,X_t|\pi)}{P(o_1^t|\pi)}\frac{P(o_{t+1}^T|X_t)}{\sum_xP(X_t=x)P(o_{t+1}^T|\pi,X_t=x)}\\
&=\frac{P(o_1^t,X_t|\pi)}{P(o_1^t|\pi)}\frac{P(o_{t+1}^T|X_t)}{P(o_{t+1}^T|\pi)}\\
&=\frac{f_{0:t}(i)}{\prod_{s=1}^tc_s}\frac{b_{t:T}(i)}{\prod_{s=t+1}^Tc_s},
\end{align*}
by definition. The third equality follows from the conditional independence of $o_{t+1}^T$ and $\{\pi,o_1^t\}$ given $X_t$.


text:
Q: ASP.NET MVC JQuery - flexible alghoritm for calling asp.net mvc methods Greetings,
i would like to prepare some good "machine" for calling asp.net mvc methods from jquery.
The concept is as follows:
The concept is to have a one method each requests will be calling. By using visitor pattern I will be able to determine what kind of operation i should do.
public interface IRequestVisitor
{
    void VisitRequest_GetPersons(CRequest_GetPersons request);
    void VisitRequest_RemovePerson(CRequest_RemovePerson request);
}

Creating some abstract request:
public abstract class CRequest
{
    public abstract void AcceptVisitor(IRequestVisitor visitor);
}

and the implementation of concrete request:
public class CRequest_GetPersons: CRequest
{
    public CRequest_GetPersons(Guid schoolROWGUID)
    {
        SchoolROWGUID = schoolROWGUID;
    }
    public Guid SchoolROWGUID={get;private set;}

    public override void AcceptVisitor(IRequestVisitor visitor)
    {
        visitor.VisitRequest_GetPersons(this);
    }
}

And the implemetation of visitor:
public void CRequestVisitor : IRequestVisitor
{
    public CResponse ResponseResult {get;private set;}

    public void IRequestVisitor.VisitRequest_GetPersons(CRequest_GetPersons request)
    {
        //code responsible for getting persons
        Result = new CResponse_GetPersons_Success(List<Person>)
    }
    public void VisitRequest_RemovePerson(CRequest_RemovePerson request)
    {
        //code responsible for removing person
        Result = new CResponse_RemovePerson_Success();
    }
}

The action each js methods will execute is as follows:
public ActionResult AjaxRequest(CRequest request)
{
    CRequestVisitor visitor = new CRequestVisitor();
    request.AcceptVisitor(visitor);
    return JSON(visitor.Result);//return some result

}

I have also found how asp.net mvc methods can be called using jquery
<script type="text/javascript">
   $(document).ready(function() {
     $("#GetPerson").click(function() {
         $.getJSON("/Test/Request",
        function(data){
            //what should be here to display all persons ?
        //how can i pass guid of school?
          });
        });

        });
    });

</script>

I would like to know how can I pass the rowguid of currently selected school.
And how can I access list of persons returned as JSON object?

A: You can pass parameters, that will be passed to parameters of the action method, by adding it to the URL:
/Test/Request?school=1
Replace 1 with the guid, and the guid will be passed back.


text:
Q: Intercepting Grails GSP actions on either client or server side Grails 2.4.5 here. I am trying to implement the following UX behavior for my GSPs:

*

*If a user has permission to click a button, then they may do so; however

*If the user doesn't have permission to click a button, then when they click the button, a banner message (flash?) appears across the top of the screen with an rose/pinkish/red background stating 'You don't have permission to take this action'

To determine whether the user has the required permission, I have access to functionality from both the Groovy and GSP/taglib layers.
From the Groovy/controller layer:
SecurityUtils.hasPermission(String permission)
Ex: SecurityUtils.hasPermission('UPDATE_BUZZ')

From the GSP/taglib layer:
<sec:hasPermission permission="<permission name>">???</sec:hasPermission>
Ex: <sec:hasPermission permission="UPDATE_BUZZ">???</sec:hasPermission>

So, given those two available access checking mechanisms, and given the following controller:
class FizzController {
    BuzzService BuzzService

    def buzz() {
        SomeData dataModel = buzzService.getModel(params)
        render(view: 'buzz', model: [ dataModel: dataModel ])
    }
}

...where buzz.gsp is:
<!-- Lots of HTML/GSP here -->
<g:submitButton name="update" value="Update" />
<!-- Lots more HTML/GSP down here -->

Given all that, my question is: How/where should I: (1) respond to the 'update' button's click handler, (2) perform the access check, and (3) render the error/banner/flash message? Code example (even pseudo-code) would be most awesome!

A: Here is what I would suggest:

*

*Make sure your controller method is role based

*Remove permission check in GSP, if the button should be visible to everyone

*Create an AJAX call upon submission, if the response status is 403, display the banner.

A: If I were you, I'd probably try to use before-action filter in this case. In this filter I'd make a checking if current user has permissions to such an action (checking permissions should always be done in server-side, because of security reasons) and than:

*

*if security check passes - just return true (controller will continue it's flow)

*if security check fails - you can use default flash.message and return false (with propriate css style flasheed message could appears across the top of the screen with an rose/pinkish/red background)
Example code:
class UserFilters {
   def filters = {
      // ... other filters ...
      permissionAllCheck(controller: '*', action: '*') {
         before = {
            doPermissionCheck(delegate)
         }
      }
   }

   private boolean doPermissionCheck(filters) {
         if (! YourService.checkForPermissionForCurrentlyLoggedUser()) {
            filters.flash.message = "You don't have permission to take this action"
            return false
         }
      true
   }
}

If you want to use filter only to specific controller/action, check applying section. Remember also, that you can use invert rule filter.
More info about different filterTypes.
You should also remember to add flash.message section to your layout (or selected views). You can always specify type of flash message and it's css style.

A: Best way would be to hide the button if the user has no permission to use it. That could be easily achieve through <sec:hasPermission permission="UPDATE_BUZZ">button</sec:hasPermission>
If you want button to be displayed even for user without permission, you could use the same hasPermission to add an extra class to the button. Now capture the clock event for that class using jQuery and show your message.

A: I am assuming by your question that you don't want a page refresh and perhaps not even an ajax call. Because if you did that then showing a banner is not difficult. You just want this to behave like JavaScript client-side validation (UX wise). If this assumption is wrong then don't read and use Aramiti's solution. Otherwise go ahead.
First solution
You can create a tag which takes a permission as input. Something like
<myTagLib:flashOnNoPermission permission="PERM" name="name" value="value">
</myTagLib:flashOnNoPermission>

This tag's definition can check the permission using sec:hasPermission. Then this tag can just render a template containing something like this
<hidden flash message>
<g:submitButton name="name" value="value" onclick="<unhide flash if no permission>"/>

Basically create a wrapper over grails button so that you can have flash messages alongwith buttons.
Problem

*

*What if user's permissions are changed when user is on screen? Ajax takes care of that but this does not. Once screen is loaded then everything is fixed.

*The banner is alongwith the button

Second solution
Add a common div at the top of your layout for displaying flash messages. Then create a tag similar to the above. Just don't add the flash message in the rendered template. Something like
    <g:submitButton name="name" value="value" onclick="<unhide flash at top of layout if no permission>"/>

Problem

*

*What if user's permissions are changed when he is on the screen?

Not sure why you need things onclick handler but if there is no reason just Aramiti's solution.


text:
Q: Access point has no internet connected from Pfsense I've already

*

*configured my firewall rules to accept my guest network(AP) to access the internet in pfsense

*added vlan (10) for my ap in pfsense

*From my ap settings, i've already created the same vlan 10

Am i missing out anything? Please refer to the images to see my configuration
Guest Interface
Firewall Guest Rule
VLAN interface
DHCP Server
DHCP Server Gateway for Guest
Guest Cannot Ping
WAN Ping
Network topology diagram


text:
Q: How To Put Back Button in Fragment Class in android I want to put back button on Fragment class. I want to put back button on left ShoppingMazza text .

nav_drawer_row.xml:-
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/log" />

   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="30dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:onClick="shopByCategory"
            android:text="Shop By Category"/>

    <!--   <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

           <ImageView
               android:id="@+id/imageView1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/electronic1" />

           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_centerVertical="true"
               android:layout_gravity="center_horizontal"
               android:layout_toEndOf="@+id/imageView1"
               android:layout_toRightOf="@+id/imageView1"
               android:gravity="center_vertical"
               android:text="Hello" />

       </RelativeLayout>  -->

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

           <ImageView
               android:paddingLeft="60dp"
               android:id="@+id/imageView1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/electronic1" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView1"
            android:layout_toRightOf="@+id/imageView1"
            android:gravity="center_vertical"
            android:text="Electronic"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="60dp"
           android:id="@+id/imageView2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/fashion" />

           <TextView
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:paddingTop="10dp"
               android:paddingBottom="10dp"
               android:textSize="15dp"
               android:textStyle="bold"
               android:layout_centerVertical="true"
               android:layout_gravity="center_horizontal"
               android:layout_toEndOf="@+id/imageView2"
               android:layout_toRightOf="@+id/imageView2"
               android:gravity="center_vertical"
               android:text="Fashion & Lifestyle "/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView3"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/deal" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView3"
            android:layout_toRightOf="@+id/imageView3"
            android:gravity="center_vertical"
            android:onClick="deal"
            android:text="@string/today_deals"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView4"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/track" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView4"
            android:layout_toRightOf="@+id/imageView4"
            android:gravity="center_vertical"
            android:onClick="home"
            android:text="@string/track_your_order"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView5"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/track" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView5"
            android:layout_toRightOf="@+id/imageView5"
            android:gravity="center_vertical"
            android:onClick="legal"
            android:text="@string/legal"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView6"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/rate1" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView6"
            android:layout_toRightOf="@+id/imageView6"
            android:gravity="center_vertical"
            android:text="@string/rate_this_app"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView7"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/query" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView7"
            android:layout_toRightOf="@+id/imageView7"
            android:gravity="center_vertical"
            android:onClick="query"
            android:text="@string/any_other_query"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView8"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/twitter" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView8"
            android:layout_toRightOf="@+id/imageView8"
            android:gravity="center_vertical"
            android:text="@string/follow_us_on_twitter"/>

       </RelativeLayout>

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <ImageView
           android:paddingLeft="25dp"
           android:id="@+id/imageView9"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/fb" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@+id/imageView9"
            android:layout_toRightOf="@+id/imageView9"
            android:gravity="center_vertical"
            android:text="@string/follow_us_on_facebook"/>

       </RelativeLayout>

        </LinearLayout>

 <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="30dp"
        android:paddingTop="10dp"
        android:text=""
        android:paddingBottom="10dp"
        android:textSize="15dp"
        android:textStyle="bold" />

</LinearLayout>

When click on back button drawer layout is closed.Anyone can hep me how i solved my problem.

A: I think that it is very strange to put a back button here.because you can close drawer by slide it .But any way just put your back button like this .

<RelativeLayout
               android:layout_width="match_parent"
               android:layout_height="60dp">

               <ImageView
                   android:layout_marginLeft="60dp"
                   android:id="@+id/imageView1"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:src="@drawable/electronic1" />

             <ImageView
                android:layout_marginLeft="10dp"
                android:id="@+id/imageView"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_alignParentLeft="true"
                android:src="@drawable/back" />

           </RelativeLayout>

A: First put a back button here is a bad idea, try to take a look to the google layout design.
But for your pb, you wants help for the layout ?
in your case juste create an horizontal Linear Layout, and add your button and then your image.
For the close operation we lack of information. Does you want to close the activity ?
does you want to go back to the main fragment ?
I'm a bit confused cauz it seems that you never touched android development.


text:
Q: HTTP Status 406 with spring mvc jqgrid i am trying to load the model data into jqgrid in spring mvc application. Its working fine in another Spring MVC Application with the following code and dependencies,but its not working for me,i am getting the following error.
 406 error(HTTP Status error):The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
Please do the needful.
     **more data:**

       Spring Version :<spring.version>4.1.0.RELEASE</spring.version>

      Spring Security Version:
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>3.2.4.RELEASE</version>
            </dependency>
      Java Version:<java.version>1.8</java.version>

       **Controller:**

          @RequestMapping(value = "/getPackageList", method = RequestMethod.GET)
                    public @ResponseBody CustomResponse getPackageList( ) {
                        List<Customize> customize = Customize.findAllCustomize();
                        System.out.println("Comes here to fetch list");
                        CustomResponse response = new CustomResponse();
                        response.setCustomize(customize);
                        response.setRecords(String.valueOf(customize.size()));
                        response.setPage("1");
                        response.setTotal("10");
                        //System.out.println("response::::"+response);
                        return response;
                    }

        **pom.xml**

        <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.9.13</version>
                <scope>compile</scope>
                </dependency>
                <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>1.9.13</version>
                <scope>compile</scope>
                </dependency>
                <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.2.3</version>
                </dependency>
                <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.2.3</version>
                </dependency>
                <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                 <artifactId>jackson-core</artifactId>
                 <version>2.2.3</version>
                </dependency>

    **JQGrid:**

             Reviewed Patches

A: Since your Controller is returning json your request to the server has to contain header Accept:application-json. Make sure it is set by the caller.

A: Try adding <mvc:annotation-driven/> to your dispatcher servlet.xml


text:
Q: Extracting a value from an XML column in SQL Server I am trying to extract the data values present in the FirstName and LastName from the below XML which is present as a string in a column in a SQL Server table.
<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>

This is the query I tried:
select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact)[1]', 'varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

This query returns the data in all the sub-nodes from the XML node <AccountHolderContact>.
999-01-02T12:00:00-05:00ABCFABC9999-9999-9999AASIndividual999999999999 ABC SthomeAAAAAABC MMMAAAddress1Person

When I change my query to the below, I get no data in my output column FirstName:
select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact/entity-Person/FirstName)[1]','varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

Is there a reason why I cannot extract from the sub-nodes of AccountHolderContact? If not, what is the easiest way to do this?

A: Your XML has multiple namespaces - 17 total. Just two of them should be taken into account. It is better not to use namespace wildcards due to performance reasons.
Here is how to shred your XML and retrieve what you need.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, payload NVARCHAR(MAX));
INSERT INTO @tbl (payload) VALUES
(N'<?xml version="1.0"?>
<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel"
             xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel"
             xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel"
             xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel"
             xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel"
             xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel"
             xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel"
             xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel"
             xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel"
             xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel"
             xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel"
             xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel"
             xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel"
             xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel"
             xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>');
-- DDL and sample data population, end

;WITH XMLNAMESPACES (DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel'
    , 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns14) ,rs AS
(
   SELECT id, TRY_CAST(payload AS XML) AS xmldata
   FROM @tbl
)
SELECT ID
   , c.value('(FirstName/text())[1]','VARCHAR(50)') AS FirstName
   , c.value('(LastName/text())[1]','VARCHAR(50)') AS LastName
FROM rs CROSS APPLY rs.xmldata.nodes('/ns14:Account/ns14:AccountHolderContact/entity-Person') AS t(c);

Output

+----+-----------+----------+
| ID | FirstName | LastName |
+----+-----------+----------+
|  1 | ABC       | ABC      |
+----+-----------+----------+

A: Assuming that the XML can only contain 1 AccountHolderContact entity (or similar), then you can use WITHXMLSPACES and the XML operator value to get the information:
DECLARE @XML xml = '<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>';

WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X);

If, however, you might have more than one person in the data, then you can use nodes to get 1 row per person (this will still bring back one with with the same sample data). If AccountHolderContact is the repeating item it'll look like this:
WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT A.AHC.value('(entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       A.AHC.value('(entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X)
    CROSS APPLY V.X.nodes('ns6:Account/ns6:AccountHolderContact')A(AHC);


text:
Q: Latest BottomNavigtionView I am creating an Android app and I stumbled upon the fact that the previous way to create a bottom navigation view has been deprecated.
This is the error I am getting:
'setOnNavigationItemReselectedListener(com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemReselectedListener)' is deprecated

I am searching everywhere for this, but there is no website that shows the latest & updated way to do this.
What is the latest way to create a proper BottomNavigtionView? Thanks in Advance

A: Yes setOnNavigationItemReselectedListener is deprected now. To perform click operation on Google Bottom navigation you have to use the bottomNavigation.setOnItemSelectedListener(this) and extend NavigationBarView.OnItemSelectedListener in your actvity/fragment
bottomNavigation.setOnItemSelectedListener(this) and then override onNavigationItemSelected(item: MenuItem)
Example Kotlin:
bottomNavigation.setOnItemSelectedListener(this)
override fun onNavigationItemSelected(item: MenuItem): Boolean {

    when(item.itemId){
        R.id.your_menu_id->{
            Toast.makeText(this,"Click",Toast.LENGTH_SHORT).show()
        }
        ///
    }
    return true
}

or
bottomNavigationView.setOnItemSelectedListener{
        when (it.itemId) {
            R.id.your_menu_id-> {
               Toast.makeText(this,"Click",Toast.LENGTH_SHORT).show()
                return@setOnItemSelectedListener true
            }
           ///
        }
        false
    }

And for reselection use bottomNav.setOnItemReselectedListener(this) and extend NavigationBarView.OnItemReselectedListener and override  onNavigationItemReselected(item: MenuItem)


text:
Q: On Windows, how can I kill all processes having files open in a directory? One really frustrating "feature" of windows is that processes lock up files and prevent the removal of directories.
I'm looking for a way to locate all processes which have files open in that directory, something like "lsof" on unix. I'm looking for some powershell magic, and I'd rather not have to buy some custom maintenance tool.

A: So I have good news and bad news. I'll start with the bad news... I haven't found a way to close locked files strictly within PowerShell. The good news is that it can be done with a PowerShell script, and a little help from a free utility from SysInternals called Handle.exe. Here's the script I have on hand to do this:
Function Close-LockedFile{
Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)][String[]]$Filename
)
Begin{
    $HandleApp = 'C:\sysinternals\Handle.exe'
    If(!(Test-Path $HandleApp)){Write-Host "Handle.exe not found at $HandleApp`nPlease download it from www.sysinternals.com and save it in the afore mentioned location.";break}
}
Process{
    $HandleOut = Invoke-Expression ($HandleApp+' '+$Filename)
    $Locks = $HandleOut |?{$_ -match "(.+?)\s+pid: (\d+?)\s+type: File\s+(\w+?): (.+)\s*$"}|%{
        [PSCustomObject]@{
            'AppName' = $Matches[1]
            'PID' = $Matches[2]
            'FileHandle' = $Matches[3]
            'FilePath' = $Matches[4]
        }
    }
    ForEach($Lock in $Locks){
        Invoke-Expression ($HandleApp + " -p " + $Lock.PID + " -c " + $Lock.FileHandle + " -y") | Out-Null
    If ( ! $LastexitCode ) { "Successfully closed " + $Lock.AppName + "'s lock on " + $Lock.FilePath}
    }
}
}

Now, if you want to do that for all files in a directory just get all the files, and run a ForEach loop on the file's FullName property. You should then be able to delete the directory without issues.
Edit: Here's the link to Handle.exe's web page: https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx (thanks to Kev because I was too lazy to look it up myself.. Thanks Kev!)


text:
Q: Saving value in "$data" from AJAX output just wondering how i save the value from the "var vname" to "$data" so that i can use the value in my php. Assuming this is pretty easy, but i'm new to this :P
<script id="source" language="javascript" type="text/javascript">

        //Call the yourAjaxCall() function every 1000 millisecond
        setInterval("yourAjaxCall()",1000);
        function yourAjaxCall()
      {
        //-----------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-----------------------------------------------------------------------
        $.ajax({
          url: 'api.php',                  //the script to call to get data
          data: "",                        //you can insert url argumnets here to pass to api.php
                                           //for example "id=5&parent=6"
          dataType: 'json',                //data format
          success: function(data)          //on recieve of reply
          {
            var id = data[0];              //get id
            var vname = data[1];           //get name

            $data = vname; //HOW AND WHERE??????? :P
          }

        });
      };
</script>

/EDIT - want my var vname which is a color, to be placed in the style.
<body>
<div id="kvadrat1" style="width:200px; height:200px; position:relative; background-color:'HERE I WANT MY VALUE'">
</div>

Greatful for quick answers! :)

A: Take a read here : Pass javascript variable to php with ajax and the result doesn't show anything
This will explain you to use javascript varaiables with PHP. Great answer from Zladuric.

A: You can not save it in php.
You can save it to HTML element
If you need it in php variable send it to other page using ajax or header redirection

A: PHP code is executed once when a page is loaded by the user. JS is executed while the user is on the page. This is why it is impossible to bind values generated by JS to PHP variables.

A:
You cant use php code when page loaded or in js.
javascript works only browser base. php works only server before
  loading page.

// you can
var name = "<?=echo $name?>";

//you CANT!
var name = "joe";

$name = name;

A: Seems to me like you're just trying to fetch a name and an ID, but can't imagine why you'd need to do that every 1000 milliseconds - just seems like a lot of requests for data that isn't going to change?
Personally I'd just suggest making the API call in your PHP before the page loads and you can var name = "<?=echo $name?>"; as avalkab has said in order to access the variables in JavaScript after the page has been loaded.
Should be able to use
$data = json_decode(file_get_contents("api.php?id=5&parent=6")); // Specify or build query however you intended

If you are waiting for the user to interact (onclick or something) to call your javascript then if you expect to use data retrieved by AJAX to change data on the whole page - you might just want to reload the page, or revise your AJAX to make use of the data returned?
EDIT:
Since you are trying to change a colour you can simply use this line with jQuery
$("#kvadrat1").css({"background-color": vname});

So your code would be like so:
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall() {
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    $.ajax({
        url: 'api.php',                  //the script to call to get data
        data: "",                        //you can insert url argumnets here to pass to api.php
                                       //for example "id=5&parent=6"
        dataType: 'json',                //data format
        success: function(data)          //on recieve of reply
        {
            var id = data[0];              //get id
            var vname = data[1];           //get name

            $("#kvadrat1").css({"background-color" : vname});
        }
    });
};

A: you can not store it in php rather than you can use any html element to store it
you can keep data in html element by using $("#id").html(data[0]);


text:
Q: Tensor product of preordered rings All rings in this post are commutative, unital, and contain $\frac{1}{2}$.
To study "real" properties of a ring $R$, one is often interested in the orderings which exist on  fraction fields of quotients of $R$ by prime ideals. This naturally leads to the definition of a preordering on a ring.
A preordering on a ring $R$ is a subset $T \subseteq R$ such that $T + T \subseteq T, T \cdot T \subseteq T$ and $\lbrace x \in R \mid \exists y \in R : x = y^2 \rbrace \subseteq T$. The support of a preordering $T$ is defined to be $T \cap -T$; one can show that this is an ideal of the ring $R$. A preordering can be extended to an ordering on the fraction field of $R/(T \cap -T)$.
If $(R_1, T_1)$ and $(R_2, T_2)$ are preordered rings extending a common preordered subring $(R, T)$, their push-out in the category of preordered rings is the ring $(R_1 \otimes_R R_2, T_1 \otimes T_2)$ where
$$
T_1 \otimes_R T_2 = \left\lbrace \sum_{i=1}^m (t_i \otimes_R t_i')x_i^2 \middle| m \in \mathbb{N}, t_i \in T_1, t' \in T_2, x_i \in R_1 \otimes_R R_2 \right\rbrace.
$$
Question: What can one say about the support of $T_1 \otimes_R T_2$? Certainly it contains the ideal $\text{supp}(T_1) \otimes_R R_2 + R_1 \otimes_R \text{supp}(T_2)$, but do we have equality? In the case $R$ is a field it follows from standard results on the amalgamation of ordered fields that $\text{supp}(T_1 \otimes_R T_2)$ is contained in some minimal prime ideal lying over $\text{supp}(T_1) \otimes_R R_2 + R_1 \otimes_R \text{supp}(T_2)$ (assuming the latter is not equal to $R_1 \otimes_R R_2$), but even in this caseù where $R$ is a field, I would like to have a more explicit description.


text:
Q: How to customize series fill in area chart via BIRT chart API? I am trying to create a gradient fill for a series in an area chart that I am building through the BIRT chart API, but the book "Integrating and Extending BIRT" and the Interwebs seem curiously silent about how to get it to work. It seems no matter what I do, I always get a flat color from the default palette. I've tried using SeriesDefinition.getSeriesPalette().update(Gradient) and even creating my own Palette with the gradient fill in it and setting that on the SeriesDefinition, but to no avail. I've also noticed that if I do not perform a shift() on the Palette, even if it's shift(0), which the Javadocs claim will do nothing, I get NullPointerException when I try to generate the chart:
Caused by: java.lang.NullPointerException
at org.eclipse.birt.chart.render.Area.renderDataPoints(Area.java:521)
at org.eclipse.birt.chart.render.Line.renderSeries(Line.java:570)
at org.eclipse.birt.chart.render.AxesRenderer.renderPlot(AxesRenderer.java:2181)
at org.eclipse.birt.chart.render.AxesRenderer.render(AxesRenderer.java:314)
at org.eclipse.birt.chart.factory.Generator.render(Generator.java:1368)
... 108 more

Here's the latest (non-working) code that I've tried:
Gradient gradient = FillUtil.createDefaultGradient(BirtReportBuilder.COLOR_WHITE);
gradient.setStartColor(ColorDefinitionImpl.WHITE());
gradient.setEndColor(ColorDefinitionImpl.create(76, 116, 131));
gradient.setDirection(90);
SeriesDefinition sdY = SeriesDefinitionImpl.create();
sdY.getQuery().setDefinition("\"Quantity\"");
Palette pal = PaletteImpl.create(gradient);
pal.shift(0);
sdY.setSeriesPalette(pal);
sdY.getSeries().add(as1);
yAxisPrimary.getSeriesDefinitions().add(sdY);

So what's the magic incantation to get the BIRT charting API to use my Gradient as the area fill?

A: This code works for me, I get a ugly coloured serie...
sdY.getSeriesPalette().update(GradientImpl.create(ColorDefinitionImpl.create(255,255,255), ColorDefinitionImpl.create(200,0,0,150), 90, false));

Hope it will help you ;p


text:
Q: React this.props.children.apply is not a function I'm making a react app with unstated to manage the state of my app, the application is a simple CRUD of notes.
I have a NoteList component to render the list of Notes.
This is my render() function in NoteList Component:
render() {
        return (
            <Subscribe to={[NoteContainer]}>
                {noteContainer => (
                    noteContainer.state.isLoaded ?
                        (
                            noteContainer.state.notas.map((note, i) => {
                                return (<Note note={note} index={i} onRemoveNote={this.removeNote} onEditNote={this.saveEditNote} key={i}></Note>)
                            })
                        )
                        :
                        (

Loading Notes...

                        )
                    )}
                )}
            </Subscribe>
        )
}

However, when i load the page, i get the following error:

this6.props.children.apply is not a function

And in the chrome console the next description:

The above error occurred in the  component:
      in Consumer (created by Subscribe)
      in Subscribe (at NoteList.js:19)
      in NoteList (at App.js:160)
      in Provider (created by Consumer)
      in Consumer (created by Provider)
      in Provider (at App.js:159)
      in App (at src/index.js:7)

I have no clue on what could be the source of this error, if anyone can give me any help i would appreciate it!
Thanks in advance, have a nice day!

A: The children of <Subscribe /> is a function that returns array of childrens, thats why the error.
To check it, inside <Subscribe />, you could do console.log(this.props.children)and you will see that it's an array, you can't use apply in an array, you need to loop through and apply it to each children
this.props.children.map(children => children.apply())


text:
Q: Does a randomly chosen series diverge? Pick a point at random in the interval $[0,1]$, call it $P_1$.
Pick another point at random in the interval $[0,P_1]$, call it $P_2$.
Pick another point at random in the interval $[0,P2]$, call it $P_3$.
Etc...
Let $S = P_1+P_2+P_3+\cdots$
What is the probability that $S$ is divergent?
Any thoughts?
P.S. random, in this particular case, means equidistributed. I.e. $P(a<P_1<b)=b-a$.

A: For every $k$, $\mathbb E(P_k)=1/2^k$ thus: $$\mathbb E(S) = \mathbb E(P_1)+\mathbb E(P_2)+\cdots = 1/2 + 1/4 + \cdots= 1$$
Since $\mathbb E(S)$ is finite it follows that $P(S=\infty) = 0$,
otherwise the expectation $\mathbb E(S)$ would be infinite.


text:
Q: Report an Error Problem: Point $X$ is on $\overline{AC}$ such that $AX = 3 CX = 12$. If $\angle ABC = \angle BXA = 90^\circ$, then what is $BX$? Point $X$ is on $\overline{AC}$ such that $AX = 3 CX = 12$. If $\angle ABC = \angle BXA = 90^\circ$, then what is $BX$?

A: This is simple geometry. The triangles $ABC,BXC,AXB$ are all similar. You are given $AX=12,XC=4$. So it is easy to find the other lengths. Eg $\frac{XC}{BC}=\frac{BC}{AC}$, so $BC=8$ and hence $BX=4\sqrt3$.


text:
Q: How to create an instance of a class from a String in Swift I have tried creating an instance of a class using a string in numerous ways with none of them working in Swift 3.
Below are pre-Swift 3 solutions I have tried that are not working
- Making class an objective-c class
@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
let c: customClass = NSClassFromString("customClass")

- Specifying class using NSString value (both with and without using @objc attribute)
@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
var className = NSStringFromClass("customClass")

let c: customClass = NSClassFromString(className)

I'm not doing something right but have not found any solutions online.
How do I create an instance of a class using a string in Swift 3?

A: If you project contains space you should replace space with '_'
Something like this
let namespace = (Bundle.main.infoDictionary!["CFBundleExecutable"] as! String).replacingOccurrences(of: " ", with: "_")
let cls = NSClassFromString("\(namespace).\(className)")! as! AnyClass

A: You can try this:
func classFromString(_ className: String) -> AnyClass! {

    /// get namespace
    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String

    /// get 'anyClass' with classname and namespace
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!

    // return AnyClass!
    return cls
}

use the func like this:
class customClass: UITableView {}

let myclass = classFromString("customClass") as! UITableView.Type
let instance = myclass.init()

A: Apple provides a way to achieve this without having to use NSClassFromString.
Bundle.main.classNamed("MyClassName")
https://developer.apple.com/documentation/foundation/bundle/1407299-classnamed

A: Typed Extension
You can have a typed class from a string like:
let loadedClass = try! Bundle.main.class(ofType: MyClass.self)

using this simple extension:
extension Bundle {
    func `class`<T: AnyObject>(ofType type: T.Type, named name: String? = nil) throws -> T.Type {
        let name = name ?? String(reflecting: type.self)

        guard name.components(separatedBy: ".").count > 1 else { throw ClassLoadError.moduleNotFound }
        guard let loadedClass = Bundle.main.classNamed(name) else { throw ClassLoadError.classNotFound }
        guard let castedClass = loadedClass as? T.Type else { throw ClassLoadError.invalidClassType(loaded: name, expected: String(describing: type)) }

        return castedClass
    }
}

extension Bundle {
    enum ClassLoadError: Error {
        case moduleNotFound
        case classNotFound
        case invalidClassType(loaded: String, expected: String)
    }
}

Of course you can try catch the error ;)


text:
Q: INSERT - EXEC problem. Empty output from stored procedure I need to SELECT specific data from stored procedure output so I am trying to insert the stored procedure's output into a table. I am very newbie in SQL.
So here is the code:
Declare @result table
(
    row_id int,
    quarry nvarchar(400),
    interval nvarchar(100),
    vskr_plan decimal(30,1),
    vskr_fact decimal(30,1),
    vskr_diff decimal(30,1),
    ruda_plan decimal(30,1),
    ruda_fact decimal(30,1),
    ruda_diff decimal(30,1),
    gpr_plan decimal(30,1),
    gpr_fact decimal(30,1),
    gpr_diff decimal(30,1),
    gm_plan decimal(30,1),
    gm_fact decimal(30,1),
    gm_diff decimal(30,1)
)

INSERT INTO @result
    EXEC [report].[DISP_KPI_QUARRY] @datet = N'2018-10-11'

SELECT *
FROM @result

I have no errors with this code but it returns an empty table!
However if I execute:
EXEC [report].[DISP_KPI_QUARRY] @datet = N'2018-10-11'

I see all the data.
What is my mistake, guys?

A: You may try to include your columns in INSERT statement in the same order as they are returned from your stored procedure. When you insert results from stored procedure, you need to be sure, that the count, datatype and order of the columns, that stored procedure returns match your @result table definition.
DECLARE @result table
(
    row_id int,
    quarry nvarchar(400),
    interval nvarchar(100),
    vskr_plan decimal(30,1),
    vskr_fact decimal(30,1),
    vskr_diff decimal(30,1),
    ruda_plan decimal(30,1),
    ruda_fact decimal(30,1),
    ruda_diff decimal(30,1),
    gpr_plan decimal(30,1),
    gpr_fact decimal(30,1),
    gpr_diff decimal(30,1),
    gm_plan decimal(30,1),
    gm_fact decimal(30,1),
    gm_diff decimal(30,1)
)

INSERT INTO @result (row_id, quarry, interval, vskr_plan, vskr_fact, vskr_diff, ruda_plan, ruda_fact, ruda_diff, gpr_plan, gpr_fact, gpr_diff, gm_plan, gm_fact, gm_diff)
EXEC [report].[DISP_KPI_QUARRY] @datet = N'2018-10-11'

SELECT *
FROM @result


text:
Q: How can I put variables inside fopen? I'm trying to save an image inside a folder. To get this folder I need to pass three directories: Images, id from the user, id from the gallery and the generated name for the image.
$directory = "../images/" . $id . "/" . $row[0] . "/" . $new_url;

I would like to pass the directory variable to the fopen, I tried this way but is not working.
$file = fopen($directory, 'wb');

Full code:
function uploadimg_func($base, $id){

    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');

    $selectgallery = db_queries("SELECT id FROM `galleries` WHERE name = 'Fotos de perfil' AND user_id =  '".$id."' ");

    $row = mysqli_fetch_array($selectgallery);

    $new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . "jpg";

    $directory = "../images/" . $id . "/" . $row[0] . "/" . $new_url;

    $file = fopen($directory, 'wb');

    fwrite($file, $binary);
    fclose($file);

    $createphoto = db_queries("INSERT INTO photos (`name`, `title`, `description`, `gallery_id`,`created_at`)
    VALUES ('".$new_url."', '', '', '".$row[0]."', now())");

}

Thanks.

A: Instead of:
$file = fopen($directory, 'wb');

Do:
$file = fopen($_SERVER['DOCUMENT_ROOT'] . $directory, 'wb');

Also, make sure that you have the correct folder and file permissions setup.  The images path should be 0775.  If something still goes wrong, check if the folders containing the image files exist....
It's working on my machine perfectly fine.


text:
Q: My terminal shows only a blank screen--How can it? I recently installed Ubuntu 13.10. in the process of editing bash.bashrc file something went wrong and all of a sudden all i'm getting when I open my terminal is a blank screen. No directory names or $. So I can't execute any commands to update, install, fix or anything. All the help out I come across assume I can use the command line.
.
Anyone knows how to fix this? or how maybe how I can recover the default bashrc file (without using the command line)? Is my only option uninstalling and reinstalling Ubuntu? I don't even know how to do that without the command line.

A: rajagenupula's answer would do the job... If you could get to a terminal. The problem is your default shell is bash (even in a TTY) so you're going to struggle to run those commands.
To get a working console, I'd press Alt+F2 and run:
xterm -e sh

That should drop you into a nasty super-basic shell. And from there you can fix/rescue/etc your .bashrc using nano (to edit) or rajagenupula's suggested commands, which should also work (you could skip the source and just go back to your traditional terminal.

If you don't have graphical access, you could drop into recovery mode (using Grub at boot), run mount -o remount,rw / and then fix/replace the file.

A: No Problem , you can restore it easily.
Just press CTRL+ALT+F1 & login there
then paste as
cp /etc/skel/.bashrc ~/
source .bashrc

Then type CTRL+ALT+F7 to reverse to GUI desktop.


text:
Q: Every year I'll withdraw $10 from the bank where I've a 2.5% interest rate. I've no money left after 10 years. How much did I have from the beginning? Ok, I will try to explain my problem in plain text:

Every year I'll withdraw $\$10$ from the bank where I have a $2.5\%$ interest rate. I have no money left after $10$ years. How much did I have from the beginning?

I've tried to come up with some kind of differential equation. But I'm probably just making in harder than it is.

A: If you had $X$ dollar at the beginning you will have
$$(X- c) \cdot p $$ after one year , where p=1 +2.5/100 and c=10.
Iterating this 10 times leaves you with
$$0 = (X-c)\cdot p^{10} - c \cdot \sum_{i=1}^9p^i $$
therefore you had
$$X = c \cdot \sum_{i=1}^9 p^{i-10} +c$$
in the beginning.
Edit: This solution works if you take 10$ at the beginning of each year.

A: Note: This calculation assumes interest payment at the end of the year, and one withdrawal at the end of the year.
Calling your unknown initial sum $x_0$, the interest rate $p$, the withdrawal sum $d$, the growth factor $f$ defined as
$$
f = 1 + \frac{p}{100}
$$
one gets for the sum after the first year $x_1$:
$$
x_1 = f x_0 - d
$$
and for the sum after the second year $x_2$:
$$
\begin{align}
x_2 &= f x_1 - d \\
    &= f\left(f x_0  - d\right) - d \\
    &= f^2 x_0 - f d - d
\end{align}
$$
and for the sum after the following years:
$$
\begin{align}
x_3 &= f x_2 - d \\
    &= f\left(f^2 x_0 - f d - d \right) - d \\
    &= f^3 x_0 - f^2 d - fd - d \\
\\
    &\vdots \\
x_{10} &= f^{10} x_0 - d \sum_{k=0}^9 f^k \\
    &= f^{10}x_0 - d \frac{f^{10}-1}{f-1} \quad (*)
\end{align}
$$
where the result
$$
\sum_{k=0}^N q^k = \frac{1 - q^{N+1}}{1-q}
$$
for a geometric sum is used. After 10 years the money is exactly gone: $x_{10} = 0$. We therefore get
$$
x_0 = d \frac{f^{10}-1}{f^{10}(f-1)}
$$
as initial sum. With $p = 2.5$% and $d=10$\$ this results in $x_0 = 87.52$\$.
In regard of Robert's answer:
At what initial sum the sum stays constant? Just checking this with equation $(*)$ gives:
$$
(f^{10} - 1) x_0 = d \frac{f^{10} - 1}{f - 1} \iff
x_0 = \frac{d}{f - 1}
$$
which is independent from the number of iterations and gives $x_0 = 400$\$ too.

A: That $\$10$  would be $2.5\%$ interest on a $\$400$ investment, i.e. if you had $\$400$ in the bank you could go on forever in this manner and your bank account would stay constant.  Since your account is actually depleted, you must have started with less.
But let's say your friend has an account earning the same interest rate, and together you have $\$400$: you start with $A$ and your friend with $\$400 - A$.  Your friend never withdraws any money.  Since your $\$10$ withdrawal represents the total interest on the two accounts, as time goes on
the sum of your fortune and your friend's stays constant.  After $10$ years your account has $0$ and your friend's has grown to $\$400$.  Now at a $2.5\%$ interest rate, your friend's account was multiplied by $1.025$ every year,
so your friend started out with $$ \dfrac{400}{1.025^{10}} = \$312.48$$
and so you must have started with
$$ 400 - 312.48 = 87.52$$
This works for any type of compounding as long as the $2.5\%$ is the effective annual rate rather than the nominal rate, and withdrawals happen at the same time as interest is paid.


text:
Q: JSONDecoder can't handle null response Context
I am working with the Firebase Database REST API and JSONDecoder / JSONEncoder. It's been working pretty well so far.
However for removing data the expected returned response is null, and JSONDecoder doesn't seem to like that very much.
This is the type of query I am sending via Postman and what I am getting back (sensitive data excluded).
DELETE /somedata/-LC03I3oHcLhQ/members/ZnWsJtrZ5UfFS6agajbL2hFlIfG2.json
content-type: application/json
cache-control: no-cache
postman-token: ab722e0e-98ed-aaaa-bbbb-123f64696123
user-agent: PostmanRuntime/7.2.0
accept: */*
host: someapp.firebaseio.com
accept-encoding: gzip, deflate
content-length: 39

HTTP/1.1 200
status: 200
server: nginx
date: Thu, 02 Aug 2018 21:53:27 GMT
content-type: application/json; charset=utf-8
content-length: 4
connection: keep-alive
access-control-allow-origin: *
cache-control: no-cache
strict-transport-security: max-age=31556926; includeSubDomains; preload

null

As you can see the response code is 200 and the body is null.
Error
When I receive the response this is the error I get :

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath:
  [], debugDescription: "The given data was not valid JSON.",
  underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
  "JSON text did not start with array or object and option to allow
  fragments not set." UserInfo={NSDebugDescription=JSON text did not
  start with array or object and option to allow fragments not set.}))))

I tried creating a custom type (NoReply) to handle this as per a previous post but to no-avail.
Code
This is where the error happens :
        resource: {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601
            return try decoder.decode(Resource.self, from: $0)
        },
        error: {
            let decoder = JSONDecoder()
            return try decoder.decode(FirebaseError.self, from: $0)
        }

So apparently even if I feed a custom NoReply type (as per the post mentioned above) JSONDecoder doesn't like null.
Any suggestions ?

As a side note this is what their documentation says about the response for a DELETE operation :

A successful DELETE request is indicated by a 200 OK HTTP status code
  with a response containing JSON null.

A: Quick follow up
After a few successful hacks, the most elegant solution I came up with was the combination of :

*

*using NoReply (as described by Zoul)

*converting the null string to an empty JSON object structure ({})

So first, the conversion :

            if "null" == String(data: data, encoding: .utf8) {
                let json = Data("{}".utf8)

which is then fed back to the closure handling the request's response :

        resource: {
            let decoder = JSONDecoder()
            return try decoder.decode(Resource.self, from: $0)
        },

where the Resource is none other than :

public struct NoReply: Decodable {}

This works great now and allows me to handle the DELETE cases and GET cases on a non-existent object where it returns null.
Thanks for the help !

A: Unfortunately JSONDecoder does not expose the underlying JSONSerialization option (.allowFragments) that would support JSON fragments like a solo null value. You could try transforming the response or just using JSONSerialization directly. Unfortunately there's nothing elegant to be done here.


text:
Q: jQuery doesn' t work for AngularJS directive I have to resize the column width of my table that is located inside my directive. I found a valid framework to do that:
Resizable table columns with jQuery. However, I have the following problem. Make the resize column works is quite simple, just add this jQuery code inside my Angular controller :
$("#normal").colResizable({
                liveDrag:true,
                gripInnerHtml:"

",
                draggingClass:"dragging",
                resizeMode:'fit'
            });

Where normal is the ID of my table, which is the following :

                header	header	header

                cell	cell	cell

                cell	cell	cell

                cell	cell	cell

Now the problem is that jQuery is not working for the table inside a directive, i mean , if i put the table inside a normal html page the resize of column width it works, but if i put the table code inside an AngularJs directive it doesn't work.
I have just the table inside my page, there is no other code that could influence the function of it.
I guess that the problem is the jQuery, but I'm not completely sure about it. I'm new to Angular and maybe there is something that I should do configure in my directive?

A: I would suggest you try to utilize Angular only if you are not sure how DOM works and how to have a clean code of jquery within angular.
Try referring Resizable columns with Angularjs


text:
Q: Can a complete bipartite graph $K_{3,3}$ really be embedded on the Mobius strip? I read the blog below and it says that $K_{3,3}$ can be embedded on the Mobius strip.

*

*https://www.cut-the-knot.org/blue/JCT/K33onTorus.shtml
In this blog, the author says $K_{3,3}$ can be drawn on the figure as shown:

First encountering such a statement, I believe that it is true.
But when I discussed it with my friends, we realized something might be wrong. Since a Mobius strip is readily available, we created one from paper strips. But I can't draw it in the above way, because edges $a$ and $b$ always cross once.

I cut the mobius strip, and no matter what, $a$ and $b$ have to cross once, right.

Mobius strip seems a little different from the projective plane. We only use the back of the long paper.
I may have misunderstood or misdrawn it. I looked at similar discussions and still found it strange.

*

*can graph $K_5$ be embedded in a Möbius band?

A: Your problem is "we only used the back of the long paper".  If you use both sides of the long paper you take advantage of the half twist.  The twist inverts the arrow in the diagram.  You can draw the diagram you show in a small area, then extend the horizontal lines at one end of the diagram around the band twice.  You can then identify the two sides of your diagram and are there.


text:
Q: Prevent jquery from reseting background image after fadeOut() I'm doing a number of fadeIn's and fadeOut's with jquery. The final fade (fadeOut()) fades out the entire css table and goes to the css body background image. I have set the background-position to center center. Jquery is resetting the image after the animation is complete to a position of left bottom. I'm looking to prevent this and keep the background image as center center.
I tried putting everything in a figure wrapper instead of in the body, that's the reason for the
 tag. When I tried this, the screen went completely white after the animation was finished.
HTML & jquery:

    <link type="text/css" rel="stylesheet" href="site.css" media="screen">

    <meta charset="UTF-8">

some text

some text

some text

CSS:
* {
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  padding: 0;
}

#pathImg {
  margin: 0;
  padding: 0;
  background-image: url(images/sunnySkies.jpg);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.hidden {
  display: none;
}

#table {
  display: table;
  height: 100vh;
  width: 100vw;
  text-align: center;
  background-color: #ffffff;
}

.containerRow {
  display: table-row;
}

.containerCell {
  display: table-cell;
}

#tableCell {
  height: 20vh;
}

#tableCell2 {
  height:   15vh;
  vertical-align: middle;
}

#tableCell3 {
  height: 10vh;
  vertical-align: top;
}

#tableCell4 {
  height: 5vh;
  vertical-align: top;
}

#tableCell3Text {
  font-family: 'Tangerine', cursive;
  font-size: 300%;
  color: #444444;
}

#tableCell4Text {
  font-family: arial;
  color: #444444;
}

#tableCell5Text {
  font-family: arial;
  color: #444444;
}

#img1 {
  margin: 5vh 0 0 0;
  padding: 5px;
  border: 2px solid #444444;
  border-radius: 5px;
  background-color: gray;
}

A: It actually seems like it's working fine for me without the figure. But if you're using the figure then the problem is that you're fading out the .container which sets it to display:none which is taking out all of the height. You need to leave something on the page so that everything doesn't collapse. At the end, the body has no height and that's why you're getting a white screen. So what we'll do is get the height of the largest image and set the body to the height before you fade out.
Change your JQuery to this
 $(".firstFade").fadeIn(5000).delay(10000).fadeOut(7000);
 $(".secondFade").delay(6000).fadeIn(5000).delay(3000).fadeOut(1000);
 $("#tableCell5Text").delay(14500).fadeOut(1000);
 var $height = $("#table").height();
 $("body").height($height);
 $(".container").delay(15000).fadeOut(7000);


text:
Q: SQL Returning More Results When Optionals are commented out got a bit of a situation here with sql, i am changing a piece of sql for a stored procedure, i have written what is below so far and i am now hitting a wall,
when i run the query AS is, it will return me 19 results, comment out everything that is showing as a optional module, and it returns 31 results,
The idea behind this is to basically read from a xml file, determine the values in the file and then match the values we have in this sql, so it will say if a is yes then 1, if b is no then 0,
So its a yes its licensed or no its not licensed scenario,
However i dont think its functioning as it should.
   -- Grab our license
 DECLARE @xml XML
 SELECT TOP 1 @xml = CAST(LicenceKey AS xml) FROM Organisation

 -- Calculate our licensed modules
 DECLARE @LicensedModules TABLE (moduleid INT)

 Declare @optionalmodules table (moduleid INT,description varchar (100))

 INSERT INTO @optionalmodules (moduleid, description) values (1,'R9')
 INSERT INTO @optionalmodules (moduleid, description) values (2,'S8')
 INSERT INTO @optionalmodules (moduleid, description) values (6,'S7')
 INSERT INTO @optionalmodules (moduleid, description) values (8,'A6')
 INSERT INTO @optionalmodules (moduleid, description) values (9,'C5')
 INSERT INTO @optionalmodules (moduleid, description) values (10,'S4')
 INSERT INTO @optionalmodules (moduleid, description) values (11,'A2')
 INSERT INTO @optionalmodules (moduleid, description) values (12,'P4')
 INSERT INTO @optionalmodules (moduleid, description) values (13,'PSL')
 INSERT INTO @optionalmodules (moduleid, description) values (14,'H4')
 INSERT INTO @optionalmodules (moduleid, description) values (15,'F2')
 INSERT INTO @optionalmodules (moduleid, description) values (16,'C1')
 INSERT INTO @optionalmodules (moduleid, description) values (17,'H2')
 INSERT INTO @optionalmodules (moduleid, description) values (18,'P3')
 INSERT INTO @optionalmodules (moduleid, description) values (20,'G1')
 INSERT INTO @optionalmodules (moduleid, description) values (21,'E2')
 INSERT INTO @optionalmodules (moduleid, description) values (22,'R1')
 INSERT INTO @optionalmodules (moduleid, description) values (23,'H1')
 INSERT INTO @optionalmodules (moduleid, description) values (24,'S2')
 INSERT INTO @optionalmodules (moduleid, description) values (25,'i1')
 INSERT INTO @optionalmodules (moduleid, description) values (26,'G1')
 INSERT INTO @optionalmodules (moduleid, description) values (27,'S1')
 INSERT INTO @optionalmodules (moduleid, description) values (28,'E1')
 INSERT INTO @optionalmodules (moduleid, description) values (29,'F1')
 INSERT INTO @optionalmodules (moduleid, description) values (31,'T2')
 INSERT INTO @optionalmodules (moduleid, description) values (32,'A1')
 INSERT INTO @optionalmodules (moduleid, description) values (33,'P2')
 INSERT INTO @optionalmodules (moduleid, description) values (16016,'P1')

INSERT INTO @LicensedModules

    SELECT CAST(sl.LookupReference AS INT)--,
        --sl.LookupReference,
        --sl.Description,
        --m.*,
        --cast(case license.value('.', 'varchar(3)') when 'Yes' then 1 else 0 end as bit) as optModLicenced,
        --case WHEN m.moduleid IS NULL THEN 1 ELSE cast(case license.value('.', 'varchar(3)') when 'Yes' then 1 else 0 end as bit) END AS isLicenced
    FROM SystemLookup sl
        LEFT JOIN @optionalmodules m ON sl.LookupReference = m.moduleid
        Left Join @xml.nodes('//Modules/*') as organisation(license) on m.description = organisation.license.value('local-name(.)', 'varchar(50)')
    WHERE sl.LookupTypeId = 1
        AND case WHEN m.moduleid IS NULL THEN 1 ELSE cast(case license.value('.', 'varchar(3)') when 'Yes' then 1 else 0 end as bit) END = 1

Select * FROM @LicensedModules

A: Seems like in the WHERE clause, if @optionalmodules is not present or not matched, then it will always include the row (m.moduleid IS NULL in the CASE statement).
If the @optionalmodules table has a value that matches sl.LookupReference, then it will only include items where the license is 'Yes', which may result in fewer rows being returned.


text:
Q: C# read json data from url without using api We are getting yammer data using yammer api however in our scenario we want a notification data but there is no api support for that, as an alternative we thought of reading the json content from a url, when we type this url in browser "https://www.yammer.com/******/notifications.json" we are getting data in the browser however through C# we are getting 406 error as there is no api support.
For api we use token id as oauth authenticating medium but to get content from a url in the form of json what authentication is available, in short please help with some code
Code we have used:
                HttpWebRequest Request = HttpWebRequest.Create(URL) as HttpWebRequest;
                Request.Method = "GET";
                Request.ContentType = "application/json; odata=verbose";
                Request.Accept = "application/json; odata=verbose";
                string Token = ConfigurationManager.AppSettings["Token"];
                Request.Headers.Add(HttpRequestHeader.Authorization, Token);

                var wResp = (HttpWebResponse)Request.GetResponse();

If you have any alternative solution please help.


text:
Q: Given a list of [string, number] tuples, create a dictionary where keys are the first characters of strings and the values are sums of the numbers I have a list of tuples, where first object is a string and second one is a number. I need to create a dictionary with using first letter of the string as a key and number (or I need to add some numbers if keys will be the same) as a value.
for example:
input
lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]

output
dct = {'A': 14, 'B': 6, 'C': 12}

A: The most simple, straightforward and naive way is:
dct = {}
for k, v lst:
    if k in v:
        dct[k] += v
    else:
        dct[k] = v

There are ways to progressively be more clever, the first is probably to use .get with the default:
dct = {}
for k, v in lst:
    dct[k] = dct.get(k, 0) + v

Finally, you can use a collections.defaultdict, which takes a "factory" function which will be called if the key is not there, use int as the factor:
from collections import defaultdict
dct = defaultdict(int)
for k, v in lst:
    dct[k] += v

NOTE: it is usually safer to create a regular dict out of this, to avoid the default behavior:
dct = dict(dct)

Or even
dct.default_factory = None

Finally, one of the more flexible ways is to create your own dict subclass and use __missing__, this is useful if need access to the key when you are making the default value, so not particularly more helpful here, but for completion's sake:
class AggDict(dict):
    def __missing__(self, key):
        return 0

dct = AggDict()
for k, v in dct:
    dct[k] += v

A: Use a defaultdict:
dct = defaultdict(int) # default to 0

for name, val in lst:
    dct[name[0]] += val

dct = dict(dct) # get rid of default value

A: You could use Counter from collections to convert the tuples to countable key/values, then use reduce from functools to add them together:
from collections import Counter
from functools   import reduce

lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]

dst = reduce(Counter.__add__,(Counter({k[:1]:v}) for k,v in lst))

# Counter({'A': 14, 'C': 12, 'B': 6})


text:
Q: WCF calling service method with an Interface argument results in SocketException I have a WCF Service where I have implemented a service method with an out argument of a type which is an Interface like this
bool GetFoo(out IFoo foo)
{
    foo = new AFoo();
    return true;
}

Here IFoo is the interface & AFoo is the concrete type that inherits.
Then on the Client Side I am calling this method using the service reference & receving the following error

System.ServiceModel.CommunicationException: 'An error occurred while
  receiving the HTTP response to
  http://localhost:4504/MyService. This could be due to the
  service endpoint binding not using the HTTP protocol. This could also
  be due to an HTTP request context being aborted by the server
  (possibly due to the service shutting down). See server logs for more
  details.'

What is Interesting is that when I remove the interface argument from the service method, everything works just fine. For example
bool GetFoo()
{
    IFoo foo = new AFoo();
    return true;
}

The AFoo type is already a known type on the Client side and I can use it normally.

Update 1
Adding a Base Class Foo such that Afoo inherits from Foo & Foo inherits from IFoo
ex: AFoo : Foo : IFoo (logically) has the same error when the service method is modified as
bool GetFoo(out Foo foo)
{
    foo = new AFoo();
    return true;
}

Again I kept all Classes & Interfaces empty (meaning they have nothing inside them)

Update 2
The following seems to work perfectly fine
bool GetFoo(out AFoo foo)
{
    foo = new AFoo();
    return true;
}

Why did not the Base Class Foo worked? Any Ideas?

A: Take a look at this other question: DataContract and inheritance?
It seems like you need to decorate the base class with KnownType of the sub-class to do this kind of thing, and have them both under DataContract of course.

A: I have seen this because the type contained a reference to an enum type that was not marked with the DataContract attribute. The error you're seeing is most likely hiding an inner error like that. Sometimes you can catch these by going to Debug -> Exceptions and turning on 'break on all thrown exceptions'.

A: Workaround:

Note: this is not an answer, since it forces to create a Base Class.

I got it working finally and I am gonna share what I did. In short, I was missing the KnownType in the DataContract.
Firstly, I had to Add a Base Class Foo as described in the question section. Next I had
to Add the KnownType attributes with all the Child(inherited) classes, in my case it was only AFoo.
Here is what the code looks like
public interface IFoo
{
}

[DataContract]
[KnownType(typeof(AFoo))]
public class Foo : IFoo
{ // this is the Base Class
}

public class AFoo : Foo
{
}

Now the service method looks like this
bool GetFoo(out Foo foo)
{
    foo = new AFoo();
    return true;
}

All Good!!
It would be nice if instead it was possible to have the service method like thie following (without needing a Base Class)
bool GetFoo(out IFoo foo)
{
    foo = new AFoo();
    return true;
}


text:
Q: ListView changing views during scrolling after adjusting them programmatically I spent all last evening to find any solution about my problem but I didn't, so it's not duplicate.
I have a listView and simple ArrayAdapter. I want each time when I click on item its textView field becomes bold, and previous if it exists becomes normal. It's very simple problem, but I have caught a lot of troubles.
My device can show 13 items at once. So, if I don't scroll everything works. But if I try to scroll, I find some next items become also bold and the click event works unproperly. In debug I see listView has only first 13 elements. I understand that adapter loads others asyncronically but how to solve my problem in these conditions?
Here is my code:
ListView listLibrary;
int posPrev;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_info);

    listLibrary = findViewById(R.id.listSongs);
    listLibrary.setOnItemClickListener(this);

    fillList();
    posPrev = -1;
}

private void fillList() {
    String[] arrList = {"New York", "San Francisco", "Los Angeles", "Dallas", "Houston", "Tucson", "Phoenix", "Denver", "Las Vegas", "Kansas City", "Chicago", "Detroit", "Atlanta", "Miami", "Philadelphia", "Baltimore", "Washington", "Boston", "Pittsburg", "Columbus", "Cincinnati", "Indianapolis", "St. Louis", "Seattle", "Portland", "San Jose", "San Diego", "San Antonio"};
    ArrayList<String> cities = new ArrayList<String>();
    for (String s : arrList)
        cities.add(s);

    if (listLibrary != null) {
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities);
        listLibrary.setAdapter(adapter);
    }
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    if (posPrev != -1) {
        ((TextView)listLibrary.getChildAt(posPrev)).setTypeface(null, Typeface.NORMAL);
    }

    ((TextView)listLibrary.getChildAt(i)).setTypeface(null, Typeface.BOLD);
    posPrev = i;
}

EDIT
So as you had suggested I added custom adapter. If tvCaption.setTypeface(null, Typeface.NORMAL) is removed I get randomly bold items next of list. Actually I understand the problem I don't know how to solve it.
 ArrayList<String> cities;
Context context;
int resource;
TextView tvCaption;
int posClicked;

public CustomArrayAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
    super(context, resource, objects);

    this.context = context;
    this.resource = resource;
    cities = (ArrayList) objects;

    posClicked = -1;
}

@NonNull
@Override
public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {
    if (view == null) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        view = layoutInflater.inflate(resource, null);
    }

    tvCaption = view.findViewById(R.id.tvCaption);
    tvCaption.setText(cities.get(position));

    if (posClicked != -1) {
        if (posClicked == position)
            tvCaption.setTypeface(null, Typeface.BOLD);
    } else
        tvCaption.setTypeface(null, Typeface.NORMAL);

    LinearLayout llCity = view.findViewById(R.id.llCity);
    llCity.setTag(position);
    llCity.setOnClickListener(this);

    return view;
}

@Override
public void onClick(View view) {
    posClicked = (int)view.getTag();
    notifyDataSetChanged();
}

EDIT LAST: THERE IS WORKING CODE!
After all editing I got this code:
Activity:
ListView listLibrary;
CustomArrayAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_info);

    listLibrary = findViewById(R.id.listSongs);
    listLibrary.setOnItemClickListener(this);

    fillList();
}

private void fillList() {
    String[] arrList = {"New York", "San Francisco", "Los Angeles", "Dallas", "Houston", "Tucson", "Phoenix", "Denver", "Las Vegas", "Kansas City", "Chicago", "Detroit", "Atlanta", "Miami", "Philadelphia", "Baltimore", "Washington", "Boston", "Pittsburg", "Columbus", "Cincinnati", "Indianapolis", "St. Louis", "Seattle", "Portland", "San Jose", "San Diego", "San Antonio"};
    ArrayList<String> cities = new ArrayList<String>();
    for (String s : arrList)
        cities.add(s);

    if (listLibrary != null) {
        adapter = new CustomArrayAdapter(this, R.layout.list_custom_item, cities);
        listLibrary.setAdapter(adapter);
    }
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    adapter.setCurClickedPos(i);
    adapter.notifyDataSetChanged();

}

And CustomAdapter:
ArrayList<String> cities;
Context context;
int resource;
int curClickedPos;

public CustomArrayAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
    super(context, resource, objects);

    this.context = context;
    this.resource = resource;
    cities = (ArrayList) objects;

    curClickedPos = -1;
}

@NonNull
@Override
public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {
    if (view == null) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        view = layoutInflater.inflate(resource, null);
    }

    TextView tvCaption = view.findViewById(R.id.tvCaption);
    tvCaption.setText(cities.get(position));

    if (curClickedPos != -1) {
        if (curClickedPos == position)
            tvCaption.setTypeface(null, Typeface.BOLD);
        else
            tvCaption.setTypeface(null, Typeface.NORMAL);
    } else
        tvCaption.setTypeface(null, Typeface.NORMAL);

    LinearLayout llCity = view.findViewById(R.id.llCity);
    llCity.setTag(position);

    return view;
}

public void setCurClickedPos(int curClickedPos) {
    this.curClickedPos = curClickedPos;
}

A: if your getView() function, you are reusing your views. So while creating views you will have to check if the item was clicked or not. When you check if posClicked is not equal to -1, in that if block you need to add an else statement as well like below:
public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {
    // your logic here
    if (posClicked != -1) {
        if (posClicked == position)
            tvCaption.setTypeface(null, Typeface.BOLD);
        else
            tvCaption.setTypeface(null, Typeface.NORMAL);
    } else
        tvCaption.setTypeface(null, Typeface.NORMAL);
    }
}

A: If I'm right you want have a bold text inside a touched/clicked itemview.
Assuming that posPrev represent the index of the touched item,

*

*first you should call notifyDataSetChanged() (after on click event)

*then add under getView method of your custom adapter this piece of code:
public View getView(int position, View convertView, ViewGroup parent)  {

    yourTextView.setTypeface(null, Typeface.NORMAL);

    if(posPrev == position){
        yourTextView.setTypeface(null, Typeface.BOLD);
    }

}