text:
Q: How to align ImageView & TextView align right in a Linear Layout I would like show my Page view header like below,

I'm using the following layout using, but the image and second textview not moving to right, its all align center.
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="6"
        android:background="@drawable/transbg"
        android:gravity="center"
        android:orientation="vertical" >
            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="fill_parent"
                android:layout_height="0dip"
                android:layout_weight="6"
                android:gravity="center"
                >
               <TextView
               android:id="@+id/txtName"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="Magasin"
               android:textColor="#FFF"
               android:textSize="18sp"
               android:textStyle="bold" />

               <LinearLayout
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_weight="0"
                   android:orientation="horizontal">

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

                   <TextView
                       android:id="@+id/tvCredits"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:gravity="right"
                       android:text="test"
                       android:textColor="#fff"
                       android:textSize="16sp" />
               </LinearLayout>

            </TableRow>
    </LinearLayout>
</LinearLayout>

how I can align one image view and textview right aligned.

A: Check out this one and let me know if it is what you want.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="6"
    android:background="@drawable/ic_launcher"
    android:gravity="center"
    android:orientation="vertical" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="6"
        android:background="@android:color/black"
        android:gravity="center" >

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

            <TextView
                android:id="@+id/txtName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:text="Magasin"
                android:textColor="#FFF"
                android:textSize="18sp"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:src="@drawable/ic_launcher"
                android:layout_toLeftOf="@+id/tvCredits" />

            <TextView
                android:id="@+id/tvCredits"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:text="test"
                android:textColor="#fff"
                android:textSize="16sp" />
        </RelativeLayout>
    </TableRow>
</LinearLayout>

EDIT :  If you want to make the same layout with easier and more efficient way, you can use this one.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/black" >

<TextView
    android:id="@+id/txtName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:text="Magasin"
    android:textColor="#FFF"
    android:textSize="18sp"
    android:textStyle="bold" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/tvCredits"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/tvCredits"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:text="test"
    android:textColor="#fff"
    android:textSize="16sp" />

</RelativeLayout>

A: // try this way
<?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:gravity="center"
    android:padding="5dp"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/txtName"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Magasin"
        android:textColor="#FFF"
        android:gravity="center"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

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

        <TextView
            android:id="@+id/tvCredits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="test"
            android:textColor="#fff"
            android:textSize="16sp"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>
</LinearLayout>

A: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="right">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal" >

<LinearLayout
    android:layout_width="0dip"
    android:layout_height="fill_parent"
    android:layout_weight="6"
    android:background="@drawable/transbg"
    android:gravity="center"
    android:orientation="vertical" >
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="6"
            android:gravity="center"
            >
           <TextView
           android:id="@+id/txtName"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Magasin"
           android:textColor="#FFF"
           android:textSize="18sp"
           android:textStyle="bold" />

           <LinearLayout
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="0"
               android:gravity="right|center"
               android:orientation="horizontal">

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

               <TextView
                   android:id="@+id/tvCredits"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:gravity="right"
                   android:text="test"
                   android:textColor="#fff"
                   android:textSize="16sp" />
           </LinearLayout>

        </TableRow>
       </LinearLayout>
      </LinearLayout>

      </LinearLayout>


text:
Q: Surface integral in a non-centered circle. I am working in a problem of fluxes of vector maps, and after having applied the divergence theorem I have obtained the following integral:
$\Phi =  \int_{x=-R}^{x=R} \int_{y=-\sqrt{R^2-x^2}}^{y=\sqrt{R^2-x^2}} \exp\left(-\frac{\sqrt{(x-x_i)^2+(y-y_i)^2}}{\delta}\right)\left(\frac{1}{\sqrt{(x-x_i)^2+(y-y_i)^2}}-\frac{1}{\delta}\right) dydx$
This integral is the surface integral over a circle of radius $R$ centered at $(0,0)$ of the function:
$f(x,y)= \exp\left(-\frac{\sqrt{(x-x_i)^2+(y-y_i)^2}}{\delta}\right)\left(\frac{1}{\sqrt{(x-x_i)^2+(y-y_i)^2}}-\frac{1}{\delta}\right)$
This function have rotation symmetry but is centered at $(x_i,y_i)$. I have tried to different approaches to solve this integral:
METHOD 1:
using the changes of variables $x = \bar{x}+x_i$ and $y = \bar{y}+y_i$ we obtain the integral
\begin{equation}
\Phi =  \int_{\bar{x}=-R-x_i}^{\bar{x}=R-x_i} \int_{\bar{y}=-\sqrt{R^2-(\bar{x}+x_i)^2}-y_i}^{\bar{y}=\sqrt{R^2-(\bar{x}+x_i)^2}-y_i} \exp\left(-\frac{\sqrt{\bar{x}^2+\bar{y}^2}}{\delta}\right)\left(\frac{1}{\sqrt{\bar{x}^2+\bar{y}^2}}-\frac{1}{\delta}\right) d\bar{y}d\bar{x}
\end{equation}
now let's use polar coordinates $\bar{x} = r\cos\theta$ and $\bar{y} = r\sin\theta$
\begin{equation}
\Phi=  \int_{\bar{x}=-R-x_i}^{\bar{x}=R-x_i} \int_{\bar{y}=-\sqrt{R^2-(\bar{x}+x_i)^2}-y_i}^{\bar{y}=\sqrt{R^2-(\bar{x}+x_i)^2}-y_i} \exp\left(-\frac{r}{\delta}\right)\left(\frac{1}{r}-\frac{1}{\delta}\right) rd\theta dr
\end{equation}
but now I don't know how to change the integration limits and I'm stuck here.
METHOD 2:
using directly the change to polar coordinates $x = r\cos\theta$ and $y = r\sin\theta$
$
\begin{aligned}
\Phi =  \int_{r=0}^{r=R} \int_{\theta=0}^{\theta=2\pi} \exp&\left(-\frac{\sqrt{r^2+r_i^2-2r(x_i\cos\theta+y_i\sin\theta)}}{\delta}\right)\\
&\left(\frac{1}{\sqrt{r^2+r_i^2-2r(x_i\cos\theta+y_i\sin\theta)}}-\frac{1}{\delta}\right)rdrd\theta
\end{aligned}
$
where I have defined $r_i = \sqrt{x_i^2+y_i^2}$. In this case I am also stuck and I don't know how to continue.
So my question is: which is the correct method to compute this integral, 1 or 2, and how I have to continue the computations? In the case that nor method 1 nor method 2 are correct, which is the correct way to do it?
Thanks for your attention and your help!
PD: I have also looked for this integral in the Gradshteyn bu I have not found it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $a$ and $b$ are relatively prime integers then prove that ($a$ ,$b^2$) =1 From the title I've stucked in this question for half an hour. Could anyone help me?

A: Consider the prime factors of $a$ and those of $b$. The fact that $a$ and $b$ are relatively prime means that $a$ and $b$ have no common prime factors. But then $a$ and $b^2$ have no common prime factors either; that is, $a$ and $b^2$ are relatively prime. QED.
(We have used the observation that $b^2$ has the same prime factors as $b$, with each prime factor in $b^2$ repeated twice as many times as in $b$.)

A: If some integer $d$ divides $b$, then we can write $b = dx$ for some $x \in \mathbb{Z}$.  From this, we have $b^2 = (dx)^2 = d(dx^2)$, so $d$ also divides $b^2$.
Now look back to the definition for $\gcd$.  What if $d|a$ and $d|b^2$ wherein $d \neq 1$?

A: We have
$$
(a,b)=1 \iff  ax+by=1 \text{   for  some integer $x,y$}
$$
Then
$$
(ax+by)^2=1 \implies a(ax^2+2bxy)+b^2 y^2=1 \implies (a,b^2)=1.
$$

A: Proof by contraposition.
Let $d:= \gcd (a,b^{2}) \geq 2$. Then $d \mid a$ and $d \mid b^{2}$. Note that $d \mid b^{2}$ implies $\gcd (d, b) \geq 2$. So $\gcd (a,b) \geq 2$.


text:
Q: Where is the Cave entrance? When you become Green, the Fellowship and the Illuminati factions will arrive at your room to ask which faction will you join.
If you choose Fellowship, you will end up in a mission to find the Grindstone.
Per the description of the mission, you have to find the cave entrance.

Where is the entrance of the cave? I already searched everything past PAL and everything... still can't find it.

A: I just found it way past PAL room, thru the door to the next map.
Here is a picture of the location:

Go to the next map where PAL is, continue thru the scaffolding and check the room named Reactor Officer Office. The green arrows point to the room where the cave entrance is.
Ignore the blue arrow room because those exclamation marks seems to be a bug since you can't interact with them.


text:
Q: Is it possible for Doxygen to exclude undocumented functions from generated XML? I want to generate documentation only for code that has Doxygen comments. I have created a Doxyfile via Doxygen version 1.8.9.1 and configured it to output only XML and to hide all undocumented code:
GENERATE_HTML          = NO
GENERATE_LATEX         = NO
GENERATE_XML           = YES
HIDE_UNDOC_MEMBERS     = YES
HIDE_UNDOC_CLASSES     = YES

After that I created a simple C header test.h with one documented and one non-documented function declaration:
void foo(int a);

/**
 * "bar" function description
 * @param b sample param
 */
void bar(int b);

By executing doxygen I expected only documentation for bar to be included in the resulting XML. Unfortunately, documentation for both functions is generated. Is it possible to generate documentation only for code that has Doxygen comments? Or will Doxygen always include everything in the XML output regardless of settings?

A: Before reading any further make sure EXTRACT_ALL is set to NO.
I'm not a fan of the following solution but it does work. Use doxygen's preprocessor
#ifdef PROJECT_NO_DOC
void foo(int a);
#endif /* PROJECT_NO_DOC */

/**
 *  * "bar" function description
 *   * @param b sample param
 *    */
void bar(int b);

Note, in their docs you have to set a PREDEFINED macro but at least in my version of doxygen this was not required. Their docs specify to do it this way set a predefined macro in the config to do it for you
#ifndef DOXYGEN_SHOULD_SKIP_THIS

 /* code that must be skipped by Doxygen */

#endif /* DOXYGEN_SHOULD_SKIP_THIS */

around the blocks that should be hidden and put:
PREDEFINED = DOXYGEN_SHOULD_SKIP_THIS

in the config file then all blocks should be skipped by doxygen as long as
ENABLE_PREPROCESSING = YES

There are other methods but they come with additional constraints ie to make sure no static method appear in your public docs you can set EXTRACT_STATIC to NO.

A: You can use \cond to hide parts of the source code from Doxygen. This avoids the need to use the preprocessor as in Harry's answer.
For example, here foo will not be seen by Doxygen, and hence not documented:
/** \cond */
void foo(int a);
/** \endcond */

/**
 * "bar" function description
 * @param b sample param
 */
void bar(int b);

Furthermore, it is possible to add section labels to \cond, and control which sections are included by listing them in the ENABLED_SECTIONS configuration option.
For example:
/// \cond CLASS_A
/// This function foos `a`.
void foo(int a);
/// \endcond

/// \cond CLASS_B
/// This function bars `b`.
void bar(int b);
/// \endcond

By setting ENABLED_SECTIONS = CLASS_A CLASS_B, both functions will show up in the documentation. Leaving one of the labels out will hide the corresponding function.


text:
Q: Populate spinner upon clicking it I am trying out this simple program where I try to send a POST request to the server and fetch the response and store them into the spinner. This is my code;
    fetchcolonynames("code");  //sending POST request
    if (spin1 != null) {
        //spin.setAdapter(adapter) doesn't work here
        spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                spin1.setAdapter(adapter); //doesn't work spinner shows nothing on clicked
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

This is my fetchcolonynames() method:
private void fetchcolonynames(String input){
        call=api.fetchcolonynames(input);
        if(call!=null){
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.body() != null) {
                        JSONArray array = null;
                        try {
                            array = new JSONArray(response.body());
                            for(int i=0;i<array.length();i++){
                                arr.add(array.getString(i));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Collections.sort(arr); //data is correct here
                        adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {

                }
            });
        }
    }

All my variables are globally declared. I want to populate the spinner, when the user clicks it. How do I accomplish this?


text:
Q: How to get the calendar type by locale string As you know ICU supports the following calendars:
Japanese
Buddhist
Chinese
Persian
Indian
Islamic
Hebrew
Indian
Coptic
Ethiopic

However IntlDateFormatter only convert the Gregorian format of date to a locale and does not convert the calendar automatically, yet it is possible to send to it the calendar and it will do the trick. The problem is I have to figure out the calendar system manually for each locale.
How to get the calendar type from locale string. for example sending fa_IR I need to get 'persian', so send it to IntleDateFormatter to generate a data string for that locale.

A: In short; you can't. Why?
Let's take a look at what both objects are:
IntlDateFormatter is part of the Internationalization extension built for performing various locale-aware operations. Amongst these operations are Date formatters and a locale-aware calendar.
Locale class is an identifier used to get language, culture or regionally-specific behaviour.
Even though they are part of the same extension, they are orthogonal as described here. That means that you cannot determine one from the other. This statement is further proven in the user guide provided by the ICU project.

... At present, all locales default to a Gregorian calendar, except for the compatibility locales th_TH_TRADITIONAL and ja_JP_TRADITIONAL. If the "calendar" keyword is supplied, this value will override the default for that locale.

Source: User guide ICU project
As the quote states any locale defaults to the Gregorian calendar unless the "calendar" keyword is provided. They cannot derive the calendar from the locale provided automatically.
The solution to your problem is most likely found in building a wrapper yourself. There are some packages on the internet that help you with this but it's nowhere near what you exactly want. If you need to save the date, save it as a timestamp and show it in the format desired by the user, the latter being if you have the freedom to implement some account settings or anything alike.
One module where I found inspiration in my quest for the answer is GlobalizeJS. There's an open open issue that paints an interesting picture of how difficult it is to get right. Take for example the United Arab Emirates (AE), they have five calendar preferences; Gregorian, Islamic Um al-Qura, Islamic, Islamic Civil and Islamic Tabular. I would let the user determine which calendar they prefer so it's most usable for them.
Good luck!


text:
Q: Transform multiple elements with same attribute name to a new element with those attribute values as child-elements I am almost there, but stuck at the last part. I am trying to transform this:
<record>
    <title language="en">title EN</title>
    <title language="nl">title NL</title>

    <technique language="en">tech EN</technique>
    <technique language="nl">tech NL</technique>
</record>

to
<record>
    <title>
      <en>title EN</en>
      <nl>title NL</nl>
    </title>
    <technique>
      <en>tech EN</en>
      <nl>tech NL</nl>
    </technique>
</record>

I have a stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <!-- identity transform for otherwise-unmatched nodes and attributes -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

<!-- transform for title elements at any depth -->
  <xsl:template match="title">
            <xsl:element name="{@language}">
            <!-- transform this node's non-attribute children -->
           <xsl:apply-templates select="node()" />
           </xsl:element>
  </xsl:template>

 <xsl:template match="technique">
            <xsl:element name="{@language}">
            <!-- transform this node's non-attribute children -->
           <xsl:apply-templates select="node()" />
           </xsl:element>
  </xsl:template>

</xsl:stylesheet>

but that produces this:
<record>
      <en>title EN</en>
      <nl>title NL</nl>

      <en>tech EN</en>
      <nl>tech NL</nl>
</record>

so almost there, But I can't figure out how to get the new elements nested in the <title> and <technique> elements
I hope somebody can help me out, thanks in advance!
Wouter

Edit:
here is the complete XML (well, only 2 elements, but this should give a better idea of what I want to achieve. Only the elements that are there twice (with the language attribute) should be transformed...the rest of the doc should remain intact
<?xml version="1.0" encoding="UTF-8"?>
<resultset>
   <records>
      <record>
         <metadata>
            <dcls />
            <recordnumber>1</recordnumber>
            <publisher>XXX</publisher>
         </metadata>
         <data>
            <records>
               <objectid>12</objectid>
               <objectnumber>1212</objectnumber>
               <artist>
                  Bob
                  <alphasort>Bob</alphasort>
                  <displaydate>1937</displaydate>
               </artist>
               <title language="NL">Title in NL</title>
               <title language="EN">Title in EN</title>
               <category language="NL">Schilderkunst</category>
               <category Language="EN">Paintings</category>
               <dated>1972</dated>
               <datebegin>1972</datebegin>
               <dateend>1972</dateend>
               <technique language="NL">olieverf op doek</technique>
               <technique language="EN">oil on canvas</technique>
               <dimensions>150 x 150 cm</dimensions>
               <webtext language="EN">Some EN text</webtext>
               <webtext language="NL">Some NL text</webtext>
               <standplaats>Amsterdam</standplaats>
            </records>
         </data>
      </record>
      <record>
         <metadata>
            <dcls />
            <recordnumber>2</recordnumber>
            <publisher>XXX</publisher>
         </metadata>
         <data>
            <records>
               <objectid>33</objectid>
               <objectnumber>3333</objectnumber>
               <artist>
                  Saskia
                  <alphasort>Saskia</alphasort>
                  <displaydate>1982</displaydate>
               </artist>
               <title language="EN">title in EN</title>
               <title language="NL">title in NL</title>
               <Series>1 / 2</Series>
               <category language="NL">Fotografie</category>
               <category Language="EN">Photography</category>
               <dated>2016</dated>
               <datebegin>2016</datebegin>
               <dateend>2016</dateend>
               <technique language="NL">C-print op aluminium</technique>
               <technique language="EN">C-print on aluminum</technique>
               <dimensions>A2 (2x)</dimensions>
               <webtext language="NL">Some NL text</webtext>
               <webtext language="EN">Some EN text</webtext>
               <standplaats>Amsterdam</standplaats>
            </records>
         </data>
      </record>
   </records>
</resultset>

A: It is not mandatory to use identity transform template.
Two simple loops (pull style) do the job.
XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes"/>

    <xsl:template match="/record">
        <record>
            <title>
                <xsl:for-each select="title">
                    <xsl:element name="{@language}">
                        <xsl:value-of select="."/>
                    </xsl:element>
                </xsl:for-each>
            </title>
            <technique>
                <xsl:for-each select="technique">
                    <xsl:element name="{@language}">
                        <xsl:value-of select="."/>
                    </xsl:element>
                </xsl:for-each>
            </technique>
        </record>
    </xsl:template>
</xsl:stylesheet>

A: If (as it seems) you know in advance the names of the elements with the language attribute, you could do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/record">
    <xsl:copy>
        <title>
            <xsl:apply-templates select="title"/>
        </title>
        <technique>
            <xsl:apply-templates select="technique"/>
        </technique>
    </xsl:copy>
</xsl:template>

<xsl:template match="title | technique">
    <xsl:element name="{@language}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Otherwise you would need to group them by name first.

A: Or this could also be done in a completely generic way :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="*">
    <xsl:copy>
        <xsl:for-each-group select="*" group-by="name()">
          <xsl:element name="{current-grouping-key()}">
            <xsl:for-each select="current-group()/@*">
              <xsl:element name="{.}">
                <xsl:value-of select="../."/>
              </xsl:element>
            </xsl:for-each>
          </xsl:element>
        </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

See it working here : https://xsltfiddle.liberty-development.net/93nwMoz


text:
Q: How to avoid multiple http access to a wave resource file from a java program? I used the following code to get the data from a wav file on a web server.  The getFormat(), getFormatLength(), totallength and reading the bytes, each performed an http access and the server log showed that there are 3 accesses.  Is there a way to make it one trip?
try {
    audioInputStream = AudioSystem.getAudioInputStream(url);//soundFile);
    format = audioInputStream.getFormat();
    totallength = audioInputStream.getFrameLength()*format.getFrameSize();
    waveData = new byte[(int)totallength];
    int total=0;
    int nBytesRead = 0;
    try {
        while (nBytesRead != -1 && total<totallength) {
            nBytesRead = audioInputStream.read(waveData, total, (int) totallength);
            if (nBytesRead>0)
                total+=nBytesRead;
            }
    ...

A: As it looks that you are reading first the entire file, into memory, why not reading reading all first in.
    // Read the audio file into waveData:
    BufferedInputStream in = new BufferedInputStream(url.openStream());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (;;) {
        int b = in.read();
        if (b == -1) {
            break;
        }
        bos.write(b);
    }
    in.close();
    bos.close();
    byte[] waveData = bos.toByteArray();

    // Create the AudioInputSteam:
    ByteArrayInputStream bis = new ByteArrayInputStream(waveData);
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bis);


text:
Q: jQuery is removed when reload Im hiding a few elements with jquery. My website's filter is using ajax reloading and when its reloaded jquery is removed.
$(document).ready(function(){
    $('.sf-label-radio').text('');
    $('.sf-item-0').css('display', 'none');
});


text:
Q: new python user..printing txt file with .read, not working I'm reading How to Learn Python the Hard Way by Zed Shaw and I can't get this part right. I'm trying to rewrite the contents of a txt file and then print it, my last line wont work(nothing shows up after I print "I'm going to write these to the file."), it seems like it works until I add the .read command...
from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that hit CTRL-C (^C)."
print "If you do want that, hit RETURN"

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print open(filename).read()

A: You need to call target.close() or target.flush() so that the newly written content would be available for .read().

A: from reviewing the website that you got this code from you didnt properly complete typing in the last 2 lines that zed shaw had typed from http://learnpythonthehardway.org/book/ex16.html:
print "And finally, we close it."
target.close()


text:
Q: .ie9 css selector I came across a css selector in the form .ie9 in a css file:
.ie9 .fc-calendar .fc-row > div, .ie9 .fc-calendar .fc-head > div

I guessed it's a IE9-specific selector, but I can't find reference about it anywhere. So is it something built-in or just some custom class made for the site?
If it's something built-in, is there an equivalence for IE10?

A: They are using Modernizr. It adds classes to the html tag, so that you can cater your CSS to fit different versions of ie. Also, modernizr tests what features of javascript are available on the browser that has loaded your page and adds these as classes as well.

A: No, that's just a class selector.

foo

A: You can specify different stylesheets for IE based on the version in use by placing this in your  area:

The above, for instance, will only call the stylesheet if the browser is IE9 or above, hence the "gte" for "Greater Than or Equal to".
It doesn't require javascript and is technically valid HTML, as it is simply a comment block that is interpreted by Internet Explorer.


text:
Q: django table of model data; trying to save items selected from a list outside of the model I have the following model in a project:
class CarAssignment(models.Model):
    leg = models.ForeignKey(Leg, null=True, blank=True)
    driver = models.ForeignKey(Driver, null=True, blank=True)
    riders = models.ManyToManyField(Rider, null=True, blank=True)

I'm trying to create a page with a table where an admin user can edit the driver and riders items for all of the car assignments in a specific group. I can't use a formset because I also need to add data from another model, and because the choices in each list come from a different subset of riders and drivers, those that belong to a specific group. Driver is a select list and Riders is a multiselect list.
I have successfully built the page and table to represent the data, with correctly working drop-down lists.  However, I can't figure out how to save the items.  Here's a specific problem scenario:
for row 1 in the table (representing CarAssignment object #1), I pick a new driver from the list in the select dropdown.  I'm assigning custom name tags in the html to identify them, as follows:
<option selected name="select.driver.{{ car_assignment.id }}">{{ driver }}</option>

Then in the view, I'm trying to see if it matches anything, as follows:
        for car_assignment in CarAssignment.objects.filter(leg__in=legs):
            driver_tag = "select.driver." + str(car_assignment.id)
            if driver_tag in request.POST:
                car_assignment.driver = driver
                car_assignment.save()

The problem is that when it finds a matching driver tag, all it returns is a string of the First Name and Last Name.  I can't do the car_assignment.driver = driver because it's trying to equate a driver object to a string.
I'm not sure how to do this.  I guess I could parse out the first and last names and try to match them against the Driver model to get the Driver objects I need, but that seems inefficient and possibly error-prone.
Any help is appreciated (I'm a programming and Django newbie). Thanks.

A: I'm not sure where your that driver field is coming from, but if it's a String, you could then do another query to get the driver object like so:
for car_assignment in CarAssignment.objects.filter(leg__in=legs):
    driver_tag = "select.driver." + str(car_assignment.id)
    if driver_tag in request.POST:
        # Get the driver object
        driver = Driver.objects.filter(name=driver_name)[0]

        car_assignment.driver = driver
        car_assignment.save()

I'd also highly recommend that you read the Django tutorial Working with forms. The logic that you're writing in the view should be moved to a form object. Your view can then instantiate the form and pass the post data. The form can then be validated and will handle saving your new objects. This is the best way to do this.
The updated flow for your view would be simplified to something like this:
def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()

            # Do something here like redirect the user
            # to acknowledge that the form was submitted successfully.
    else:
        form =  MyForm()

    return render_to_response('form.html', {
        'form': form,
    })

By passing the form to your template you can generate the form doing nothing but this:
{{ form.as_ul }}


text:
Q: Select nth h3 element of body How do I select (for instance) the 2nd h3 element of my body without affecting the elements between them?
nth-of-type doesn't work because it will select the first parent!
Here's my jsfiddle (sorry because it's foreign and the code is not shortened)
<http://jsfiddle.net/tg7of5sp/>

A: nth-of-type()

The :nth-of-type(n) selector matches every element that is the nth
  child, of a particular type, of its parent.n can be a number, a
  keyword, or a formula.

See Refrence
Working Demo  Selecting 2nd h3 of body

body>h3:nth-of-type(2){
    color:red;
    }

1st Heading h3

div 1st Heading h3

div 2nd Heading h3

2nd Heading h3


text:
Q: Passing a model to a different controller from a view I have this button:
<button type="button" onclick="location.href='@Url.Action("Index", "Registration">Register</button>

Its on a sign-in page that has this link which goes to a registration page. I'd like to preserve the username and password entered on this page when the user clicks the link to go to the registration page, so is there a way to pass it a new model such that the user goes to the registration page and already has their ID and password entered?
For example, I am trying to do something like this:
<button type="button" onclick="location.href='@Url.Action("Index", "Registration", new RegistrationModel { ID = Model.ID, Password = Model.Password })'">Register</button>

A: All you need to do is just post your values to which ever controller you want to handle it and share the same textbox names.
Say you have a view like so, containing your form:
@model LoginFormViewModel

@* Form element defaults to posting to Login controller, but has an attribute containing the URL to the Registration controller should we need it *@
<form id="login_form" method="post" action="@Url.Action("Index", "Login")" data-registration-url="@Url.Action("Index", "Registration")">

    @* Username field *@
    @Html.TextBoxFor(x => x.Username)

    @* Password field *@
    @Html.PasswordFor(x => x.Password, new { value = Model.Password })

    @* Hidden value that we can check in the controller *@
    <input type="hidden" name="FromLoginPage" value="true" />

    <input type="submit" value="Register" id="register_submit" />
    <input type="submit" value="Login" />
</form>

I would use jQuery to control the submitting of the forms:
// User clicked regstration button, not login button
$(document).delegate('input#register_submit', 'click', function(e) {

    // Prevent default submitting of the form to the login controller
    e.preventDefault();

    // Get registration URL from the attribute
    var registerActionUrl = $('form#login_form').attr('data-registration-url');

    // Submit the form to the registration controller
    $('form#login_form').attr('action', registerActionUrl).submit();
});

Here's the model LoginViewModel and RegistrationViewModel that share properties with the same names (Username and Password), this will come in handy for binding up depending on which controller we submit the form to:
// Login model
public LoginViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

// Registration view model
public RegistrationViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
    public bool FromLoginPage { get; set; }

    // ... other fields that won't get bound when submitted from login page
    public string ConfirmPassword { get; set; }
}

In the Login controller we handle things normally, but within the registration form we can do a quick check on FromLoginPage submitted from the login page to return the registration page back to the user with the fields populated:
// Login controller
[HttpPost]
public LoginController : Controller
{
    public Index(LoginViewModel requestmodel)
    {
        // Validate login
        // Process login

        // Return the view
        return View(requestmodel);
    }
}

// Registration controller
[HttpPost]
public RegistrationController : Controller
{
    public Index(RegistrationViewModel requestModel)
    {
        // Submitted from the login page?
        if (requestModel.FromLoginPage)
        {
            // Clear any model validation errors so far
            this.ModelState.Clear();

            // Just load the registration page with the values populated
           return View(requestmodel);
        }

        // A normal registration request from registration page, perform validation on entire model

        // Process login here
        return View(requestmodel);
    }
}


text:
Q: Laravel Storage not syncing with public Storage folder When I was working locally I could save files in a storage and they would automatically appear in public/storage directory. Now I've transferred the same project to a shared server, but the storage doesn't seem to be in sync with public/storage directory.
This is how I store a file:
$path = 'app/public/images';
$img->save(storage_path($path.'/photo.jpg'));

And this is how I retrieve it:
Storage::url('public/images/photo.jpg);

NB: I linked the storage using php artisan storage:link locally, I don't know if I need to do that again (which may prove to be difficult if possible because I'm on a shared host) now that I'm on a different server or not.

A: All I had to do was to symlink the storage directory. However, I couldn't use php artisan storage:link because my host doesn't support SSH. Instead I used this solution.

A: I deployed some projects on shared hosting, and i found the same error, and the issue with store images with path is bacause the index root is different in share hosting. You can fix like this:
$my_public = 'home/username/public_thml/your_project_laravel/'
$path = 'app/public/images';
$img->save($my_public.$path.'/photo.jpg'));

You need specifc the path of your share hosting, other way is change the root of public html in your share hosting but it will change all the references paths in your account, if you have other websites in the same hosting is not a good solution.


text:
Q: Riak: how are queries using secondary indices implemented? Consider a query that uses secondary indices. Does this cause the node that received the query to send out a request to all other nodes? That is, does the use of secondary indices require communicating with all other nodes to find data that matches the index lookup?

A: The best source for information on how querying of secondary indexes works can be found here:
http://docs.basho.com/riak/latest/dev/advanced/2i/
I believe that the portion of the explanation that is relevant to your question is:
"When issuing a query, the system must read from a "covering" set of partitions and then merge the results. The system looks at how many replicas of data are stored—the N value or n_val—and determines the minimum number of partitions that it must examine (1 / n_val) to retrieve a full set of results, also taking into account any offline nodes."
Also note that: "For all 2i queries, the R parameter is set to 1," - http://docs.basho.com/riak/latest/dev/using/2i/#Querying


text:
Q: ArcGIS 10.1 using Repast's Agent Analyst Extension - refresh.exe does not work I have installed the agent analyst extension for ArcGis. The refresh.exe, however, does not work. I have made a direct reference to the folder where refresh.exe is.

A: Try building the following C# program with Visual Studio; this should be a drop-in replacement. I am not sure what is wrong with the included refresh.exe but it crashes with a generic APPCRASH on my 10.1 installation:
using System;
using ESRI.ArcGIS;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Framework;

namespace Refresh
{
    internal class Program
    {
        [STAThread]
        private static void Main(string[] args)
        {
            RuntimeManager.BindLicense(ProductCode.EngineOrDesktop);
            IAppROT appROT = new AppROTClass();
            if (appROT.Count > 0)
            {
                for (int i = 0; i < appROT.Count; i++)
                {
                    if (appROT.Item[i] is IMxApplication)
                    {
                        IMxDocument mxDocument = (IMxDocument)appROT.Item[i].Document;
                        mxDocument.ActiveView.Refresh();
                    }
                }
            }
        }
    }
}

Update: The issue seems to be that at ArcGIS 10.0+, ESRI no longer provides policy files allowing for assembly redirection (so you have to re-compile for each new version). See this ESRI forum thread for more info. A possible alternative solution to recompiling the program would be to create a publisher policy file that redirects the 10.0 assemblies to the 10.1 assemblies.
Update 2: Instead of recompiling, you can create an application configuration file to redirect the 10.0 assembly dependencies to the 10.1 assemblies. Copy/paste the following into a text editor and save it as Refresh.exe.config alongside Refresh.exe. Worked for me anyways:
<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="ESRI.ArcGIS.ArcMapUI" publicKeyToken="8fc3cc631e44ad86" />
                <bindingRedirect oldVersion="10.0.0.0" newVersion="10.1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="ESRI.ArcGIS.Carto" publicKeyToken="8fc3cc631e44ad86" />
                <bindingRedirect oldVersion="10.0.0.0" newVersion="10.1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="ESRI.ArcGIS.Framework" publicKeyToken="8fc3cc631e44ad86" />
                <bindingRedirect oldVersion="10.0.0.0" newVersion="10.1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="ESRI.ArcGIS.System" publicKeyToken="8fc3cc631e44ad86" />
                <bindingRedirect oldVersion="10.0.0.0" newVersion="10.1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="ESRI.ArcGIS.Version" publicKeyToken="8fc3cc631e44ad86" />
                <bindingRedirect oldVersion="10.0.0.0" newVersion="10.1.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>


text:
Q: iOS app files that the user can download from the app The idea is that i will create a file in the app and store some data in it.
I want for the end user to be able to download that file from the iOS device to his mac/pc.
Is this somehow possible? Where should i put the file for the user to be able to download it via itunes?

A: Here is good tutorial you can use:
Tutorial
It is important to know, that in iOS, when your user needs to create file, you do not need to care where to save it.
Another possibility for you might be to avoid saving data as file. For example, if your data is picture:
UIImage send to email


text:
Q: can i change appearence of the netbeans IDE 6.5.1 i would like to change the netbeans IDE 6.5.1 from default white into dark theme ,unfortunately the are no plugins to my knowledge to change it into dark theme ,
have i missed out any other way ?and if there is a plugin  available for the same pls share .
thanking anybody who answers in advance.

A: you can install a Plugin to do this for you, in your Netbeans toolbar navigate to :
Tools > Plugins > Available Plugins > search for Darcula LAF for Netbeans

Hope this can do the work for you .


text:
Q: How is my clojure import of a class from a local jar file not working? I've been trying to import a class from a local jar file into a Clojure program (this is a cli project and my dev environment is Calva in VSCode in Windows 10). My project file is at C:\Users\fadrian\Projects\motive-cql-builder\mercator-server. My deps.edn file is in this folder and looks like this:
{:paths
 ["src"
  "C:\\Users\\fadrian\\Projects\\motive-cql-builder\\mercator-server\\resources\\jars\\apelon\\dtscore-4.6.1-838.jar"
  ]

 :deps
 {org.clojure/clojure {:mvn/version "1.10.3"}
  compojure/compojure {:mvn/version "1.6.2"}
  http-kit/http-kit {:mvn/version "2.5.3"}
  ring/ring-json {:mvn/version "0.5.1"}
  ring-cors/ring-cors {:mvn/version "0.1.13"}
  org.clojure/data.json {:mvn/version "2.4.0"}
  mercator/mapper {:local/root "../mercator"}
  mercator/expander {:local/root "../mercator"}
  mercator/primitives {:local/root "../mercator"}
  mercator/templates {:local/root "../mercator"}
  cheshire/cheshire {:mvn/version "5.0.2"}
   }

 :jvm-opts ["-XX:-OmitStackTraceInFastThrow"]

  :aliases {;; build an uberjar (application) with AOT compilation by default:
            :dev {}

            :uberjar {:replace-deps {com.github.seancorfield/depstar {:mvn/version "2.1.303"}}
                      :exec-fn hf.depstar/uberjar
                      :exec-args {:aot true}}
  ;; build a jar (library):
            :jar {:replace-deps {com.github.seancorfield/depstar {:mvn/version "2.1.303"}}
                  :exec-fn hf.depstar/jar
                  :exec-args {}}}}

The class I'm trying to include is in the file resources\jars\apelon\dtscore-4.6.1-838.jar in the jarfile folder \com\apelon\dts\client. It is called ServerConnectionEJB.class. I have verified that the file is in this location in the jarfile.
The ns statement in my code file is this:
(ns mercator-server.core
  (:gen-class)
  (:require [compojure.core :refer [defroutes GET POST]]
            [mercator.expander :refer [ednize-json-keywords]]
            [mercator.mapper :refer [translate json-template-sets]]
            [org.httpkit.server :refer [run-server]]
            [ring.middleware.cors :refer [wrap-cors]]
            [ring.middleware.json :refer [wrap-json-body wrap-json-response]])

  (:import  [com.apelon.dts.client ServerConnectionEJB]
            [java.util Base64]))

However, when I try to execute this statement in the clj command line, it throws the following error:
Execution error (ClassNotFoundException) at java.net.URLClassLoader/findClass (URLClassLoader.java:445).
com.apelon.dts.client.ServerConnectionEJB.

I've checked the classpath using clj -Spath and the .jar file I am loading is in the classpath. I have unzipped the jar file and verified that the files are where they should be for the :import directive in the ns declaration. I have tried every incarnation of the filepath to the jar in my deps.edn file - local path, global path, forward slashes, backward slashes, etc. So far nothing has worked.
Does anyone have any idea what could cause the executor to not find the class and throw this error? I'm past the point of hoping for a solution (though that would be nice) - I'm just looking for more theories to follow up on at this point

A: I use lein, not clj, but I can't imagine putting a jar file in a path named src could be correct. A quick look at the clj guide confirms that you're supposed to put it in deps, with a coordinate that specifies a local jar:

{:deps
 {db/driver {:local/root "/path/to/db/driver.jar"}}}


text:
Q: TPL How to Perform a 'Call-Back' I have a small application that needs to test SQL connection strings for a number of connections (each done one-at-a-time). To do this I set the ConnectionTimeout = 5 temporarily to avoid a long wait if the connection is not valid and ConnectionTimeout = 0 (wait forever), say.
To avoid the UI hanging whilst we attempt to Open() a bad connection (even with ConnectionTimeout = 5 the wait for the SqlException can be up to twenty seconds), I want to run the test on a separate thread using Task Parallel Library (TPL). So I spin-off my new thread like:
Task<bool> asyncTestConn = Task.Factory.StartNew<bool>
    (() => TestConnection(conn, bShowErrMsg));
return asyncTestConn.Result;

The problem is that this is still locking the UI (clearly), as it is waiting for the result before returning to the caller. How do I allow the code to return control to the UI (freeing up the GUI) whilst getting the eventual result from the asynchronous Task?
Also, from within a Task can I legitimately do MessageBox.Show("Some message")? This does not work for BackgroundWorkers and this pooled-thread is a background thread by default; yet it does not seem to be a problem. Thanks for your time.

A: For the TPL, ContinueWith is exactly what you want. Expanding on Henk's answer:
var asyncTestConn = Task.Factory.StartNew(() => TestConnection(conn, bShowErrMsg));
// Henk's "MyFinishCode" takes a parameter representing the completed
// or faulted connection-testing task.
// Anything that depended on your "return asyncTestConn.Result;" statement
// needs to move into the callback method.
asyncTestConn.ContinueWith(task =>
    {
        switch (task.Status)
        {
            // Handle any exceptions to prevent UnobservedTaskException.
            case TaskStatus.Faulted: /* Error-handling logic */ break;
            case TaskStatus.RanToCompletion: /* Use task.Result here */ break;
        }
    },
    // Using this TaskScheduler schedules the callback to run on the UI thread.
    TaskScheduler.FromCurrentSynchronizationContext());

A: You are right, this is where the waiting happens:
 return asyncTestConn.Result;

You could simply build the finish-up code in the tail of TestConnection() or use a Continuation:
// untested
//Task<bool> asyncTestConn = Task.Factory.Create<bool> (
Task<bool> asyncTestConn = new Task<bool> (
    () => TestConnection(conn, bShowErrMsg));
asyncTestConn.ContinueWith(MyFinishCode);
asyncTestConn.Start()

can I legitimately do MessageBox.Show("Some message")?

Actually Yes, the MessageBox is thread-safe. Should be possible from a Bgw as well.
But you are prolonging the life of the Task by a lot, it's not a good idea.


text:
Q: Retrofit 2 - delayed response I have a problem with retrofit 2. I'm sending some data to Microsoft EAS server but a response is received after 20 sec. Why I know that this is a retrofit problem? Because without retrofit it is working correctly.
my logs:
D/OkHttp: --> POST https://{my_host}/Microsoft-Server-ActiveSync?Cmd=Provision&User={myuser}&DeviceId=837bc6c5690b40b98ab55f7a2231e50c&DeviceType={mydevicetype} http/1.1
D/OkHttp: Content-Type: application/vnd.ms-sync.wbxml
D/OkHttp: Content-Length: 456
D/OkHttp: Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
D/OkHttp: MS-ASProtocolVersion: 14.1
D/OkHttp: Connection: keep-alive
D/OkHttp: User-Agent: MyUserAgent
D/OkHttp: X-MS-PolicyKey: 0
D/OkHttp: [3,1,106,0,0,14,[...more here...],88,77,76,0,1,1,1,1] // <--- body
D/OkHttp: --> END POST (456-byte body)

after 20 sec (it seems like I receive response after 20 + normal receive time - in this case: 20596ms):
D/OkHttp: <-- 200 OK https://{my_host}/Microsoft-Server-ActiveSync?Cmd=Provision&User={myuser}&DeviceId=837bc6c5690b40b98ab55f7a2231e50c&DeviceType={mydevicetype}  (20596ms)
D/OkHttp: Content-Type: application/vnd.ms-sync.wbxml
D/OkHttp: request-id: {request_id}
D/OkHttp: Set-Cookie: {cookie_data}
D/OkHttp: X-CalculatedBETarget: {target}.local
D/OkHttp: X-MS-BackOffDuration: L/-470
D/OkHttp: X-DiagInfo: EXCHANGEHA
D/OkHttp: X-BEServer: EXCHANGEHA
D/OkHttp: Set-Cookie: {cookie_data}
D/OkHttp: X-FEServer: EX01
D/OkHttp: Date: Fri, 07 Oct 2016 10:30:08 GMT
D/OkHttp: <-- END HTTP (binary 15-byte body omitted)

If I'm requesting it without retrofit, it sends me response immiedetaly.
My code:
Init:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(chain -> {
            Request original = chain.request();

            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Authorization", getAuth(account))
                    .addHeader("MS-ASProtocolVersion", getProtocolVersion())
                    .addHeader("Connection", getConnectionType())
                    .addHeader("User-Agent", getUserAgent())
                    .addHeader("X-MS-PolicyKey", getPolicyKey());

            Request request = requestBuilder.build();
            return chain.proceed(request);
        });
        if (EasConfig.isDebug()) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(logging);
        }

        httpClient.readTimeout(30, TimeUnit.SECONDS);
        httpClient.writeTimeout(30, TimeUnit.SECONDS);

        OkHttpClient client = httpClient.build();

        retrofit = new Retrofit.Builder()
                .baseUrl(getBaseUrl(account))
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

Call:
ActiveSyncService service = retrofit.create(ActiveSyncService.class);
service.getData(getContentType(), command, getUser(account), getDeviceId(), getUserAgent(), serializer.toByteArray());

Endpoint:
@POST("Microsoft-Server-ActiveSync")
Call<ResponseBody> getData(@Header("Content-Type") String contentType, // <--- it has to be here -- it's not woking if I set it in incerteptor (don't know why)
                           @Query("Cmd") String command,
                           @Query("User") String user,
                           @Query("DeviceId") String deviceId,
                           @Query("DeviceType") String deviceType,
                           @Body byte[] data);


text:
Q: In observational studies, how can unconfoundedness, $(Y(1), Y(0)) \perp T \mid X$, hold if $(Y(1), Y(0))$ are fixed and non-random? In observational studies, one can use the Rubin Causal Model to retrieve unbiased estimates, which usually there is a statement that is usually required which states that:
$$
(Y(1), Y(0)) \perp T \mid X
$$
where $(Y(1), Y(0))$ are the potential outcomes, $T$ the treatment variable, and $X$ being the covariates. The theory behind this assumption usually takes the potential outcomes to be fixed and known ahead of time. The Rubin book mentions that fact explicitly here. That is, they are non-random or non-stochastic. Given this, how would one interpret the independence statement above? If $(Y(1), Y(0))$ are non-random and, say, scalar, how does the stochastic relation above even make sense?

A: Potential outcomes are features of units $U$, so it helps in our case to index them:
$$Y_u(1), Y_u(0)$$
The usual statement is that potential outcomes are fixed for a specific unit $u$, but may of course vary across $U$. The conditional independence assumptions then becomes
$$Y_u(1), Y_u(0) \perp T_u | X_u$$

A: Because this is a property that holds for the population, not for the individual. The potential outcome of any individual is fixed. The conditional independence claim holds in the population.
Say we have 6 individuals with potential outcomes, $Y(1) = \{1, 2, 3,4,5,6\}$ and $Y(0) = \{1,2,3,4,5,6\}$. Note the potential outcomes are fixed. Now say you randomly sample 3 individuals for the treatment group and 3 individuals for the control group. Let the treatment indicator be $T$. Clearly, $\{Y(1),Y(0)\} \perp T$, since you treated them at random we have that $P(T = 1|Y(1), Y(0)) = P(T = 1) = 1/2$. This independence is a property of the population.

A: You cited the Imbens & Rubin book in a comment...
From the introduction of chapter 7:
"The most important difference between the methods discussed in Chapters 5 and 6 and the ones discussed here is that they rely on different sampling perspectives. Both the Fisher approach discussed in Chapter 5 and the Neyman methods discussed in Chapter 6 view the potential outcomes as fixed and the treatment assignments as the sole source of randomness. In the regression analysis discussed in this chapter, the starting point is an infinite super-population of units. Properties of the estimators are assessed by resampling
from that population, sometimes conditional on the predictor variables including the treatment indicator. From that perspective, the potential outcomes in the sample are random..."
From the introduction of chapter 8:
"As discussed in Chapters 5 and 6, both Fisher's and Neyman's approaches for assessing treatment effects in completely randomized experiments viewed the potential outcomes as fixed quantities, some observed and some missing. The randomness in the observed outcomes was generated primarily through the assignment mechanism, and sometimes also through random sampling from a population. In this chapter, as in the preceding chapter on regression methods, we consider a different approach to inference, where the potential outcomes themselves are also viewed as random variables, even in the finite sample."
So it seems this is just a misunderstanding. Or where else did you read Rubin making this assumption of fixed potential outcomes (other than in explaining Fisher's and Neyman's work)?


text:
Q: Compare the values between 2 cells, with one cell having Custom Number Format Given the following code...
If [a2].Value = [b2].Value Then
    [c2] = "yes"
Else
    [c2] = "NO !!!"
End If

On the spreadsheet, both A2 and B2 display AA-100
The value of B2 is also "AA-100".  However, the value that is typed into A2 is actually "100" since it's formatted using the Custom field for a cell, using this format...
"AA"-000
I thought the .Value was supposed to extract what the user sees, but it turns, out that's not the case.

A: The .Value is what you would see in the formula bar. If you want what is displayed in the cell with a custom number format, use the .Text property.
If [a2].Text = [b2].Text Then
...

Note that the .Text property picks up the cell's value as it is displayed in the cell so using left indentation will also add leading space(s). It isn't the most reliable method of direct comparison.


text:
Q: Copy and Rename Files from sub-directories to different sub-directories based on two lists? I have small problem to solve with python. I have 50k images stored within 20k folders. I have to move them into new folder structure that I created and rename these images. Here is the test environment with C:\TEST\SOURCE and C:\TEST\DESTINATION folder structure:

I have Src.csv that has one column with image paths like this:
C:\TEST\SOURCE\1\a.png
C:\TEST\SOURCE\2\b.jpg
C:\TEST\SOURCE\3\c.jpg
C:\TEST\SOURCE\4\d.jpg
C:\TEST\SOURCE\5\e.jpg

And I have Dest.csv that has one column with path where each image should go:
C:\TEST\DESTINATION\6\a.png
C:\TEST\DESTINATION\7\b.jpg
C:\TEST\DESTINATION\8\c.jpg
C:\TEST\DESTINATION\9\d.jpg
C:\TEST\DESTINATION\10\e.jpg

Here is what I have tried to do:
import csv
from shutil import copyfile

def load_paths(filename):
    pathdict = {}
    with open(filename) as csvfile:
        filereader = csv.reader(csvfile, delimiter=' ')
        a = 0
        for row in filereader:
           pathdict[a] = ''.join(row)
           a += 1
        csvfile.close()
        return pathdict

srcpaths = load_paths('srcfile.csv')
dstpaths = load_paths('dstfile.csv')

for a in range(len(srcpaths)):
    copyfile(srcpaths[a],dstpaths[a])

I am able to make this to copy the files, however I am not sure how to rename them now. I am assuming I will need another list to reference to what name I will use. For example, I will have one csv with two column one with path and original name and second with new name? Would that work? And how would I rename these images in addition to code I have up there?
Update - The copying does not work properly. It is copying the images from 1 to 6, 2 to 7, 3 to 8, 4 to 9, 5 to 10 folders. So regardless how i specify it in my destination folder the script for some reason is copying the images as it reads first line for source and paste it to first line in destination folder.
What do i need to change?

A: Simply put the new names in the destination csv file:
C:\TEST\DESTINATION\6\aaa.png
C:\TEST\DESTINATION\7\bcc.jpg
...

The files are renamed as they are copied.
If you prefer not to have to clean up the source folder, use the move function which also allows for renaming as the file is moved:
import csv
from shutil import move  # import move in place of copyfile
...
for a in range(len(srcpaths)):
    move(srcpaths[a],dstpaths[a])

Update in response to your comment:
Your code loads the two files in to separate lists, using an index to get the source and destination file paths. The only link between the files is the line number of the file. If I add line numbers to the files shown in your question:
"Src.csv"
[1] C:\TEST\SOURCE\1\a.png
[2] C:\TEST\SOURCE\2\b.jpg
[3] C:\TEST\SOURCE\3\c.jpg
[4] C:\TEST\SOURCE\4\d.jpg
[5] C:\TEST\SOURCE\5\e.jpg

"Dest.csv"
[1] C:\TEST\DESTINATION\6\a.png
[2] C:\TEST\DESTINATION\7\b.jpg
[3] C:\TEST\DESTINATION\8\c.jpg
[4] C:\TEST\DESTINATION\9\d.jpg
[5] C:\TEST\DESTINATION\10\e.jpg

Once read in they are "matched" using the list index (line number) so the source --> destination mapping will be:
[1] C:\TEST\SOURCE\1\a.png --> [1] C:\TEST\DESTINATION\6\a.png
[2] C:\TEST\SOURCE\2\b.jpg --> [2] C:\TEST\DESTINATION\7\b.jpg
[3] C:\TEST\SOURCE\3\c.jpg --> [3] C:\TEST\DESTINATION\8\c.jpg
[4] C:\TEST\SOURCE\4\d.jpg --> [4] C:\TEST\DESTINATION\9\d.jpg
[5] C:\TEST\SOURCE\5\e.jpg --> [5] C:\TEST\DESTINATION\10\e.jpg

If you want to move the file C:\TEST\SOURCE\1\a.png to the folder 10 you need to change the first line of your destination file to C:\TEST\DESTINATION\10\a.png. The linking is not based on the filenames.
To take it a step further, lets say you want to move all the files to folder 10. Your Dest.csv file would contain:
[1] C:\TEST\DESTINATION\10\a.png
[2] C:\TEST\DESTINATION\10\b.jpg
[3] C:\TEST\DESTINATION\10\c.jpg
[4] C:\TEST\DESTINATION\10\d.jpg
[5] C:\TEST\DESTINATION\10\e.jpg


text:
Q: Information and the difference between Loacal Area Networks and Personal Area Networks I've been googling for hours, and I cant seem to find a SIMPLE answer for this question..
I'm doing some research on Local and Personal area networks.
Could someone please explain the difference between the two different types of network, what protocols are used and the good and point the bad of each type. All in language for a NEWBIE?

A: The personal area network is going to refer to very short range connections such as connecting your phone to your computer via usb or bluetooth while local area network (LAN) generally refers to a network of computers in a single organization in a small geographic area. For example if you work at a car dealership, all of the computers in that car dealership are connected together in a local area network. If that car dealership is connected to the internet, this connection would be considered leaving the local area network and connecting to the wide area network (WAN)


text:
Q: How to extract string from column scala? I have a datafram with values like List[INTERSTED_FIELD:details]. I am trying to get just the interested fields from that. How do I remove the non interesting fields ?
Example :
val df = Seq(
  "TESTING:Testing(2,4, (4,6,7) foo, Foo purchase count 1 is too low",
  "PURCHASE:BLACKLIST_ITEM: Foo purchase count (12, 4) is too low ",
   "UNKOWN:#!@",
   "BLACKLIST_ITEM:item (mejwnw) is blacklisted",
   "BLACKLIST_ITEM:item (1) is blacklisted, UNKOWN:#!@"
).toDF("raw_type")

df.show(false)

+-----------------------------------------------------------------+
|raw_type                                                         |
+-----------------------------------------------------------------+
|TESTING:Testing(2,4, (4,6,7) foo, Foo purchase count 1 is too low|
|PURCHASE:BLACKLIST_ITEM: Foo purchase count (12, 4) is too low   |
|UNKOWN:#!@                                                       |
|BLACKLIST_ITEM:item (mejwnw) is blacklisted                      |
|BLACKLIST_ITEM:item (1) is blacklisted, UNKOWN:#!@               |
+-----------------------------------------------------------------+

I am trying to get :
+-----------------------------------------------------------------+
|raw_type                                                         |
+-----------------------------------------------------------------+
|TESTING                                                          |
|PURCHASE,BLACKLIST_ITEM                                          |
|UNKOWN                                                           |
|BLACKLIST_ITEM                                                   |
|BLACKLIST_ITEM, UNKNOWN                                          |
+-----------------------------------------------------------------+

A: Check this UDF solution
scala> val df = Seq(
     |   "TESTING:Testing(2,4, (4,6,7) foo, Foo purchase count 1 is too low",
     |   "PURCHASE:BLACKLIST_ITEM: Foo purchase count (12, 4) is too low ",
     |    "UNKOWN:#!@",
     |    "BLACKLIST_ITEM:item (mejwnw) is blacklisted",
     |    "BLACKLIST_ITEM:item (1) is blacklisted, UNKOWN:#!@"
     | ).toDF("raw_type")
df: org.apache.spark.sql.DataFrame = [raw_type: string]

scala> def matchlist(a:String):String=
     | {
     | import scala.collection.mutable.ArrayBuffer
     | val x = ArrayBuffer[String]()
     | val pt = "([A-Z_]+):".r
     | pt.findAllIn(a).matchData.foreach { m => x.append(m.group(1)) }
     | return x.mkString(",")
     | }
matchlist: (a: String)String

scala> val myudfmatchlist = udf( matchlist(_:String):String )
myudfmatchlist: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,StringType,Some(List(StringType)))

scala> df.select(myudfmatchlist($"raw_type")).show(false)
+-----------------------+
|UDF(raw_type)          |
+-----------------------+
|TESTING                |
|PURCHASE,BLACKLIST_ITEM|
|UNKOWN                 |
|BLACKLIST_ITEM         |
|BLACKLIST_ITEM,UNKOWN  |
+-----------------------+

scala>

A: val p = "[A-Z_]+(?=:)".r
df.rdd.map(x=>p.findAllIn(x.mkString).mkString(",")).toDF(df.columns:_*).show(false)

In spark-shell:
scala> df.rdd.map(x=>p.findAllIn(x.mkString).mkString(",")).toDF(df.columns:_*).show(false)
+-----------------------+
|raw_type               |
+-----------------------+
|TESTING                |
|PURCHASE,BLACKLIST_ITEM|
|UNKOWN                 |
|BLACKLIST_ITEM         |
|BLACKLIST_ITEM,UNKOWN  |
+-----------------------+


text:
Q: Laravel - How can i display what has been sorted This is my controller
if ($request->input('sort')) {
    $sort = $request->input('sort');
}

if ($sortBy == "asc") {
    $image_ = Image::where('property_id', $id)
              ->orderBy($sort,'asc')
              ->get();
 }

return view('settings.photos', ['image_' => $image_]);

This is my blade file
@if( isset($image_))
    @foreach ($image_ as $images)

            filename}}"
                 style="width:100px;height:100px;">

            {{$images->description}}

    @endforeach
@endif

It doesn't display the $images_ variable, how can i display it?

A: You have to pass two variables to your controller

1) SortBy : the column by which , you want to do sorting
2) SortOrder : sort order ascending or descending

You can pass these two variables to request query string parameters :

like :  http://yourdomain.com/products?sortBy=name&sortOrder=-1

get these query parameters in your controller
 public function sort_products(Request $request){
    $id, $sortBy , $sortOrder ;

    $id=$request->input('id');

    // check request has sortBy

    if($request->has('sortBy')){
      $sortBy=$request->query('sortBy');
    }else{
       //request has no sort by  , set default sort by
        $sortBy='name';
     }

     // check request has sortOrder

    if($request->has('sortOrder')){
       $sortOrder=$request->query('sortOrder');
    }else{
       //request has no sort order  , set default sort order
       $sortOrder='asc';
    }

    $images = Image::where('property_id',$id)->orderBy($sortBy,$sortOrder)->get();

    return view('yourview',compact('images','sortBy','sortOrder'));
 }

in your blade view use font aweasome icons to display up and down arrow for sort order :
http://fontawesome.io/icons/
@if( count($images)>0 )

                 FileName
                     @if($sortBy=='name')
                         @if($sortOrder=='asc')

                         @else

                         @endif
                     @endif

                 Description
                   @if($sortBy=='description')
                         @if($sortOrder=='asc')

                         @else

                         @endif
                     @endif

        @foreach ($images as $image)

                   filename}}" style="width:100px;height:100px;">

                     {{$image->description}}

        @endforeach

@else

NO IMAGES FOUND.

@endif

for more info : https://laravel.com/docs/5.6/requests


text:
Q: where and when will it call email order_new.html file My Simple question is:
When and where call this order_new.html file in core file ?
this file in app/locale/en_US/template/email/sales/order_new.html
 {{layout handle="sales_email_order_items" order=$order}}

If call order_new.phtml file then it automatically call this above handle ?
this code located in app/design/frontend/base/default/layout/sales.xml
   <!--
    Email layouts section
    -->
        <sales_email_order_items>
            <block type="sales/order_email_items" name="items" template="email/order/items.phtml">
                <action method="addItemRender"><type>default</type><block>sales/order_email_items_order_default</block><template>email/order/items/order/default.phtml</template></action>
                <action method="addItemRender"><type>grouped</type><block>sales/order_email_items_order_grouped</block><template>email/order/items/order/default.phtml</template></action>
                <block type="sales/order_totals" name="order_totals" template="sales/order/totals.phtml">
                    <action method="setLabelProperties"><value>colspan="3" align="right" style="padding:3px 9px"</value></action>
                    <action method="setValueProperties"><value>align="right" style="padding:3px 9px"</value></action>
                    <block type="tax/sales_order_tax" name="tax" template="tax/order/tax.phtml">
                        <action method="setIsPlaneMode"><value>1</value></action>
                    </block>
                </block>
            </block>
            <block type="core/text_list" name="additional.product.info" />
        </sales_email_order_items>

A: app/code/core/Mage/Sale/Model/Order.php line 1313 on this line he is calling the email template.
the template are define are app/code/core/Mage/Sale/etc/config.xml line 1.96
 <sales_email_order_template translate="label" module="sales">
                    <label>New Order</label>
                    <file>sales/order_new.html</file>
                    <type>html</type>
                </sales_email_order_template>


text:
Q: NetworkStream.Read did not get all the bytes after a null byte/s I'm making an application that will able to control remotely a device such as a Camera(Scopia XT5000 - Radvision). I need to send an initialization command to the device for me to be able to send AT commands that will control the device.
Once I send the Initialization Commands, the server should reply this:
In String

??\0\0\0 AT[<IP400C9XT5000-03.01.00.0028\r??\0\0\0OK\r

In Bytes

170 170 0 0 0 32 65 84 91 60 73 80 52 48 48 67 57 88 84 53 48 48 48 45 48 51 46 48 49 46 48 48 46 48 48 50 56 13 170 170 0 0 0 3 79 75 13

I tried to debug and got those values when I put a break in here

serverStream.Read(inStream, 0, inStream.Length);

But every time I run the program without debugging or putting a break, it will give me different string and bytes. Just like this
In String

??\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0

In Bytes

170 170 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

What could be the problem?
Is it:
 - the Null bytes?
 - the carriage return? "\r"?
 - the multiple lines?
Whole Code:
{
    TcpClient clientSocket = new System.Net.Sockets.TcpClient();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        msg("Client Started");
    }

    public void openSocket()
    {
        if (clientSocket.Connected)
        {
            clientSocket.Close();
        }
        clientSocket = new System.Net.Sockets.TcpClient();
        clientSocket.Connect("10.0.3.202", 55003);
        label1.Text = "Client Socket Program - Server Connected ...";

    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        openSocket();
        //header bytes and initAT bytes are the initialization command for me to send AT commands
        msg("Init: ");
        NetworkStream serverStream = clientSocket.GetStream();
        //header bytes to enable AT command
        byte[] header = {170,170,0,0,0,8 };
        serverStream.Write(header, 0, header.Length);
        serverStream.Flush();
        //Initialize the Interface
        byte[] initAT = System.Text.Encoding.ASCII.GetBytes("AT[&IPV\r");
        serverStream.Write(initAT,0, initAT.Length);
        serverStream.Flush();

        byte[] inStream = new byte[10025];
        serverStream.Read(inStream, 0, inStream.Length);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);
        msg("Data from Server : " + returndata);
    }

    private void btnRight_Click(object sender, EventArgs e)
    {
        msg("Right : ");
        NetworkStream serverStream = clientSocket.GetStream();
        //AT Command to move the main camera to right
        byte[] outStream3 = System.Text.Encoding.ASCII.GetBytes("AT[&SY011R\r");
        serverStream.Write(outStream3, 0, outStream3.Length);

        byte[] inStream2 = new byte[48];
        serverStream.Read(inStream2, 0,inStream2.Length);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream2);
        msg(returndata);
    }

    public void msg(string mesg)
    {
        textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
    }

}

A: Read returns the number of bytes read.  You have a 10025-byte buffer, but it is not full after Read.  You may want to loop until all of the bytes you want are read.
It works when you debug because with the extra time spent, the network stream has time to fully receive the result, so when Read is called, all of the data is available and is put into the buffer.
Reference: http://msdn.microsoft.com/en-gb/library/system.io.stream.read.aspx


text:
Q: this.attribute is not defined after being constructed Hi there I made a very small jquery plugin:
$mandarina = {
    mainCnt: $('#main'),
    header: $('header.site-header'),
    init: function () {
        this.onScroll();
    },
    onScroll: function () {
        $(window).scroll(function(e){
            var scrollTop = $(window).scrollTop();
            if(scrollTop > this.header.height()){
                this.mainCnt.addClass('fixed-header');
            }else{
                this.mainCnt.removeClass('fixed-header');
            }
        });
    }
}
$(function () {
    $mandarina.init();
});

But when I scroll I get this error in console:
TypeError: this.header is undefined
[Parar en este error]

if(scrollTop > this.header.height()){

Any idea why?
weird thing is that this.header in the init function it does exist..

A: Inside the scroll callback, this is the window element rather than your $mandarina object. You need to save a reference to $mandarina via;
onScroll: function () {
    var that = this;

    $(window).scroll(function(e){
        var scrollTop = $(window).scrollTop();
        if(scrollTop > that.header.height()){
            that.mainCnt.addClass('fixed-header');
        }else{
            that.mainCnt.removeClass('fixed-header');
        }
    });
}

... i.e. store the value of this in that, and use that instead of this inside the event handler.

A: try this
$mandarina = {
mainCnt: $('#main'),
header: $('header.site-header'),
init: function () {
    this.onScroll();
},
onScroll: function () {
    var $this= $(this);
    $(window).scroll(function(e){
        var scrollTop = $(window).scrollTop();
        if(scrollTop > $this.header.height()){
            $this.mainCnt.addClass('fixed-header');
        }else{
            $this.mainCnt.removeClass('fixed-header');
        }
    });
 }
}

$(function () {
    $mandarina.init();
});

A: this.header.height

you need to remove this


text:
Q: SQL Query for getting nth Weekday date between two dates My scenario is as below:
@StartDate = 13th of current month
@EndDate = 12th of next month.

I want to get all the date with the day-name for Mondays, Tuesdays, Wednesdays, Thursdays, Fridays, Saturdays and Sundays lying between the start and end date.

A: Try this:
declare @startDate datetime = '2016-01-13'
declare @endDate datetime = '2016-02-12'

;with dateRange as
(
  select [Date] = dateadd(dd, 1, @startDate)
  where dateadd(dd, 1, @startDate) < @endDate
  union all
  select dateadd(dd, 1, [Date])
  from dateRange
  where dateadd(dd, 1, [Date]) < @endDate
)

select [Date], datename(dw,[Date])
from dateRange

A: To count the number of each day as per your comment (this should be part of the question really), change the last part of James' answer to this:
select datename(dw,[Date]) as day_name, count([Date]) as number_days
from dateRange group by datename(dw,[Date]), datepart(DW,[Date])
order by datepart(DW,[Date]);

A: You can try something like this :
DECLARE @StartDate DATETIME
DECLARE @StartDateFixed DATETIME
DECLARE @EndDate DATETIME
DECLARE @NumberOfDays int

SET @StartDate = '2016/01/01'
SET @EndDate = '2016/01/02'
SET @NumberOfDays = DATEDIFF(DAY,@StartDate,@EndDate) + 1

SET @StartDateFixed = DATEADD(DD,-1,@StartDate)

SELECT  WeekDay , COUNT(WeekDay)
FROM  (
        SELECT TOP (@NumberOfDays) WeekDay = DATENAME(DW , DATEADD(DAY,ROW_NUMBER() OVER(ORDER BY spt.name), @StartDateFixed))
        FROM   [master].[dbo].[spt_values] spt
      ) A
GROUP BY WeekDay

The output will be
WeekDay
------------------------------ -----------
Friday                         1
Saturday                       1

(2 row(s) affected)

A: In case if you need to get current and next date from date number specified such as 13 and 12
Current Month
DECLARE @cur_mont INT =  (SELECT MONTH(GETDATE()))

Current Year
DECLARE @cur_year INT = (SELECT YEAR(GETDATE()))

Next Month
DECLARE @nxt_mont INT = (SELECT MONTH(DATEADD(month, 1, GETDATE())))

Next Month year (In case of December year change)
DECLARE @nxt_year INT = (SELECT YEAR(DATEADD(month, 1, GETDATE())))

Create start date
DECLARE @startDate DATETIME = (SELECT CAST(CAST(@cur_year AS varchar) + '-' + CAST(@cur_mont AS varchar) + '-' + CAST(13 AS varchar) AS DATETIME))

Create end date
DECLARE @endDate DATETIME = (SELECT CAST(CAST(@nxt_year AS varchar) + '-' + CAST(@nxt_mont AS varchar) + '-' + CAST(12 AS varchar) AS DATETIME))

Dates between start and end date
SELECT  TOP (DATEDIFF(DAY, @startDate, @endDate) + 1)
    DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @startDate) AS Date,
    DATENAME(DW, DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @startDate)) AS Day
    FROM sys.all_objects a CROSS JOIN sys.all_objects b;

A: DECLARE @dayStart int = 13, --The day of current month
        @dayEnd int = 12,   --The day of another month
        @howManyMonth int = 1, --How many month to take
        @dateStart date,
        @dateEnd date
--Here we determine range of the dates
SELECT @dateStart = CONVERT (date,
        CAST(DATEPART(Year,GETDATE()) as nvarchar(5))+ '-' +
        CASE WHEN LEN(CAST(DATEPART(Month,GETDATE()) as nvarchar(5))) = 1
             THEN '0'+CAST(DATEPART(Month,GETDATE()) as nvarchar(5))
             ELSE CAST(DATEPART(Month,GETDATE()) as nvarchar(5)) END + '-' +
        CAST (@dayStart as nvarchar(5))),
        @dateEnd = CONVERT (date,
        CAST(DATEPART(Year,DATEADD(Month,@howManyMonth,GETDATE())) as nvarchar(5))+ '-' +
        CASE WHEN LEN(CAST(DATEPART(Month,DATEADD(Month,@howManyMonth,GETDATE())) as nvarchar(5))) = 1
             THEN '0'+CAST(DATEPART(Month,DATEADD(Month,@howManyMonth,GETDATE())) as nvarchar(5))
             ELSE CAST(DATEPART(Month,DATEADD(Month,@howManyMonth,GETDATE())) as nvarchar(5)) END + '-' +
        CAST (@dayEnd as nvarchar(5)))

;WITH cte AS (
SELECT @dateStart as date_
UNION ALL
SELECT DATEADD(day,1,date_)
FROM cte
WHERE DATEADD(day,1,date_) <= @dateEnd
)
--Get results
SELECT  DATENAME(WEEKDAY,date_) as [DayOfWeek],
        COUNT(*) as [DaysCount]
FROM cte
GROUP BY    DATEPART(WEEKDAY,date_),
            DATENAME(WEEKDAY,date_)
ORDER BY DATEPART(WEEKDAY,date_)
OPTION (MAXRECURSION 0)

Output:
DayOfWeek   DaysCount
----------- -----------
Sunday      4
Monday      4
Tuesday     4
Wednesday   5
Thursday    5
Friday      4
Saturday    4

(7 row(s) affected


text:
Q: Export CoreData with Binary Data Types How can I export the data stored in the CoreData model to an external file, and so that the user can get a copy of the data in swift?
What's more is that my CoreData model has binary data as well which are images. How can I export these kind of data?


text:
Q: c++ use of winmain() I just started learning programming for windows in c++. I had this crazy image, that win32 programming is based on calling windows functions and sending parameters to and from them. Like, when you want to create window, you call some win32 function that handles windows GUI and say "Hi, please, create me new window, 100 x 100 px, with two buttons", and that GUI function says "Hi, no problem, when something happends, like user clicks one button, I will change this variable xy located in this location".
So, I thought that it will be very similiar to console programming. But the very first instruction surprised me. I always thought that every program executes main() function first. So, when I launch app, windows stores some parameters on top of stack and run that application. So I assumed that initializing main() is just a c++ way to tell the compiler where the first instruction should be.
But in win32 programming, there is function called WinMain() which starts first. So I am little confused. I thought it´s rule that compiler must have main() to start with, that main just defines where it starts, like some start point identifier.
So, please, why is there WinMain() function instead of main()? When I thought that C++ programming is as logical as assembler, it confuses me once again.

A: main() is as arbitrary an entry point as WinMain() is. The standard only requires a function named main for consistency. The entry point (whether it's main or WinMain) is actually called by a hidden function that is the real entry point. On some platforms that "real" entry point is called something like _start. It's that function that does all of the initial work like initializing globals, setting up the environment, etc., and then it calls main(). On Windows, that start function happens to call WinMain() if available.
Edit: check out this answer for a more detailed explanation.

A: To understand how Win32 application works requires additional effort compared to usual console application.
"I had this crazy image, that win32 programming is based on calling windows functions and sending parameters to and from them"
my hints ...
1 )True , but also windows message that are the beats of a Windows Application , some example include WM_CREATE, WM_MOUSExx , WM_KEYxx , WM_PAINT where xx can be DOWN UP and so on .
Messages are sent to your application by Windows itself , it is up to you to define a specific function to trap them (the "WindowFunc").
There are hundreds of messages, luckily is not necessary to understand all them at first .
2) Every widget you can imagine to create in your app is a "Window" , and you can create Windows by CreateWindow function .Each window will be identified by a 32 bit integer value the so called Window Handle (HWND)
3 There are so many different class of windows as you can imagine (mainwindow , clientarea , edit, button) both available from the system and also created by yourself...
Windows are different as they belong from different WindowClass ...
To define a WindowClass you have to fill a WNDCLASS c structure and call RegisterClass
A field in the struct is a pointer to the WindowFunc
4 The WindowFunc is a function that takes 4 input parameters (HWND,WM_XX,wParam,lParam)
That function will be called from the system as soon as something happens regarding that window (HWND)
said that let me rewrite your statement
"Like, when you want to create window, you call some win32 function that handles windows GUI and say "Hi, please, create me new window, 100 x 100 px, with two buttons", and that GUI function says "Hi, no problem, when something happends, like user clicks one button,
...I will send you a message to the windowFunc as the user click... please check for the messagetype by yourself and if it is the WM_MOUSEDOWN you was waiting for then change the value for xy
What else ? i suggest to look at some simple sample in the sdk to get confident on how a win 32 app flow is
cheers

A: It is just a convention for native Win32 programs.  You can easily change it, the MSVC linker accepts the /ENTRY:main command line option to change the entry point name to "main".  You will however also have to change the signature of the main() function, it takes different arguments:
int APIENTRY main(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
  // etc..
}

Which I guess was the point of giving it a different name 20 years ago.

A: You can check this article and another one from a microsoft developer. Briefly there're several reasons: the name are arbitrary, windows' WinMain required a different signature, and windows predates c++ standarization.


text:
Q: How can I make a batch file calling JBOSS to run like a service? Just curious if theres a way to do this...
Basically I'll be calling Jboss from a batch file, and I want to have it run in a seperate thread or service
Any idea how to do this?

A: We use jbosssvc.exe to run jboss as a service.
Once you have that set up, you can put in your batch file net start JBAS4SVC


text:
Q: want to remove certain value from the vector in R I have vector in the below form:
a<-
[1] "[1]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""              "[5]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""
[11] "[9]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""              "[13]"               "\"0\""              "\"0\""              "\"0\""              "\"0\""

I want to remove all the numbers "[1]","[5]","[11]","[15]"...."[1500]" so on  using gsub or regex in R. I have given a try below:
remove<- gsub("[0:9]", a)

But getting following error:
Error in gsub("[0:9]", a) : argument "x" is missing, with no default

Thanks in advance!

A: Note that gsub only removes text inside character vector items, it does not remove the items themselves. In this case, you need a grep-like solution.
You may use a simple pattern to identify those items:
^\[\d+]$

See the regex demo.
Details

*

*^ - start of string

*\[ - a [ char

*\d+ - 1+ digits

*] - a literal ]

*$ - end of string.

Then, use it with grep command with invert=TRUE option to only keep the items that do not match this regex, and value=TRUE to get the values rather than indices.
See the R demo:
> a <- c("[1]", "\"0\"")
> grep("^\\[\\d+]$", a, invert=TRUE, value=TRUE)
[1] "\"0\""


text:
Q: How to show through which cassandra node your request was served Why?
For educational purposes. I think it would be really nice for my audience to actually "see" it work like that.
Setup

*

*A dockerized Spring boot REST API (serving up customer information)

*A dockerized Cassandra cluster consisting of three connected nodes, holding customer data with a replication factor of two.

Suggestions

*

*Showing which IP address or container name served my request

*Showing which IP address or container name held the data that was used to show my request.

*If I were to run these nodes on three seperate physical machines, maybe which machine held my data?

*Something else you have in mind that really shows the distributed capabilities of Cassandra

Can this be achieved in docker logs or something in Spring data Cassandra that I am not aware of?

A: I don't know about Spring Data, but in normal Java driver you can get execution information from ResultSet via getExecutionInfo, and call function getQueriedHost from it.  If you're using default DCAware/TokenAware load balancing policy, then you reach at least one of the nodes that hold your data. The rest of information you can get via Metadata class from which you can get a list of token ranges owned by hosts, generate a token for your partition key, and lookup in the token ranges.
P.S. See Java driver documentation for more details.


text:
Q: Shorter code for copy x elements between char arrays Does here exist a shorter code for this?
unsigned char* msg = new unsigned char(msgLen + 1);
for (int i = 0; i < msgLen; i++) {
    msg[i] = (buffer[index + i]);
}
msg[msgLen] = 0;

I am looking for something like:
take start nth element and end nth element from buffer and copy them to msg
I cannot use std::vector, because I do this stuff on platforms where the compiler doesn't have std::vector.

A: You can use std::copy.
std::copy(buffer + index, buffer + index + msgLen, msg);
msg[msgLen] = 0;

If not maybe std::memcpy (from C).
memcpy(msg, buffer + index, msgLen);
msg[msgLen] = 0;


text:
Q: Will related posts shown on Mobile but hidden for PC via css harm SEO? I have mobile layout which drastically differs from PC as I have Related content displayed at the bottom of page for mobile but not for PC. Will it harm SEO if I hide related posts on PC via css and display only on Mobile ?
Thanks.

A: Make sure when someone click on that related content the user are automatically redirected on mobile version of website, also make sure that content for mobile is same as for PC, also use same URL's. To fix duplicate content issue just add canonical tag on mobile version of site. I recommend using separate domain for mobile like m.example.com

A: Not, it will not hurt your SEO. Google uses what is displayed for desktop to compute mobile rankings (more details in a summary I maintain).
However, it is not recommended to display more content in mobile than in desktop.


text:
Q: how do i create a true "multiple lines" column in a picture library sharepoint 2010 I would like to have a pic lib and would like to have the normal multiple line of text like tin list etc..
Any ideas why there is such a limitation?

A: Try this:
1) Site Actions -> Site columns -> Create -> Create Multiple lines of text (Rich or Enhanced rich) -> Ok.
2) Go to your Picture library -> Picture and Library settings -> In content types area click on Picture content type -> Add from existings site or list columns -> Select and add your multiline column -> Ok.