问:
Logarithm Matlab
I try to use the logarithm function to a specific base in Matlab but I get the error message:
"Error using log
Too many input arguments." which I do not understand because the syntax is very simple.
 My code is: log(4,2);
Why do I get this error? </p>

答:
matlab's log function (before R2017a) doesn't have this functionality.
instead, you can do: log(x)/log(n), whereas log_n(x) = log(x)/log(n)

Title: Logarithm Matlab


来源: stackexchange

问:
What does [context assignObject: toPersistentStore ] do?
My project have multiple .sqlite .

Im using 1 context , 1  persistentStoreCoordinator,  linked to multiple persistentStores.

I wonder does [context assignObject :  toPersistentStore]

no need to call [context save] after ?
 what if the object A have 5 relationships to object  B C D E F
  Do i need to call . [context assignObject : B ..]  [context assignObject : C ..]  ... (and so on) ??  In order to save a whole branch of data ???

答:
According to the documentation, you need to call that method if you have multiple writable persistent stores that can store that entity type.

If the entity can only be saved in one of the stores, then it will be automatically assigned to that persistent store. If you have a whole chain of related entities, yes, you'll need to assign each one. You can't have relationships between entities in different stores, so watch out for that.

Finally, you'll still need to call save on the managed object context to persist those entities. Assigning them to a store doesn't save, it just determines where they will be saved by the context when the time comes.

ContentLicense: CC BY-SA 3.0


问:
Aggregate multiplicate function
I have a table of the following:

```<code>1    X    10
2    X    30
3    Y    5
4    Y    2
...etc
</code>```

I need to turn it into:

```<code>X    300   //(10 * 30)
Y    10    //(5 * 2)
</code>```

so I'm in fact looking for a kind of a multiplication function that I could use like sum, avg and stuff... does this exist guys?

for instance:

```<code>select field2, **multiply**(field3)
from t
group by field2
</code>```

Thanks

答:
You can define following two functions:

```<code>Public Function ResetProd() As Boolean
    Call Prod(Null)
    ResetProd = True
End Function

Public Function Prod(nNumber As Variant) As Double
    Static nPrevNumber As Double
    If IsNull(nNumber) Then
        nPrevNumber = 1
    Else
        nPrevNumber = nPrevNumber * nNumber
    End If
    Prod = nPrevNumber
End Function
</code>```

...and use them as follows:

```<code>SELECT PROD(_column_for_wich_you_want_product_) FROM _your_table_
WHERE RESETPROD()
</code>```

ContentLicense: CC BY-SA 2.5

Title: Aggregate multiplicate function

Body:
I have a table of the following:

1    X    10
2    X    30
3    Y    5
4    Y    2
...etc

I need to turn it into:

X    300   //(10 * 30)
Y    10    //(5 * 2)

so I'm in fact looking for a kind of a multiplication function that I could use like sum, avg and stuff... does this exist guys?

for instance:

select field2, **multiply**(field3)
from t
group by field2

Thanks

Body:
You can define following two functions:

Public Function ResetProd() As Boolean
    Call Prod(Null)
    ResetProd = True
End Function

Public Function Prod(nNumber As Variant) As Double
    Static nPrevNumber As Double
    If IsNull(nNumber) Then
        nPrevNumber = 1
    Else
        nPrevNumber = nPrevNumber * nNumber
    End If
    Prod = nPrevNumber
End Function

...and use them as follows:

SELECT PROD(_column_for_wich_you_want_product_) FROM _your_table_
WHERE RESETPROD()


问:
Set RadioButton checked onResume
Creating app in which i am setting data in recyclerview list and showing that data using radiobutton in radiogroup and text.I am able to check radiobutton,but when i again open that activity my checked radiobutton is unchecked,but i want that when i again open activity my radiobutton shoulde be checked.

Here is my Adapter class :

```<code>holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
                    holder.radioButton.setChecked(true);

                if (lastCheckedRB != null) {
                    lastCheckedRB.setChecked(false);
                }
                if(selectedId!=0)
                {
                    holder.radioButton.setChecked(true);
                }

                //store the clicked radiobutton
                if(holder.radioButton.isChecked())
                {
                    teamList.clear();
                    lastCheckedRB = checked_rb;
                    teamList.add(name);

                    int checkedIndex = group.indexOfChild(checked_rb);
                }
                else
                {
                    holder.radioButton.setChecked(false);
                }
                int selectedId = holder.radioGroup.getCheckedRadioButtonId();

            }
</code>```

Here is my Activity class :

```<code>protected void onResume() {
    super.onResume();
    try {
        adapter.lastCheckedRB.setChecked(true);
        }
        adapter.notifyDataSetChanged();
    } catch (NullPointerException e) {

    }
}
</code>```

答:
Because u activity is not have focus.
https://lh6.googleusercontent.com/-cRgfIY8Y0pE/ToyPWqE3L4I/AAAAAAAAAbM/mfpvj5yabiA/s800/20111005_L0023_L_StatesSchema.jpg</p>

Title: Set RadioButton checked onResume

Body:
Creating app in which i am setting data in recyclerview list and showing that data using radiobutton in radiogroup and text.I am able to check radiobutton,but when i again open that activity my checked radiobutton is unchecked,but i want that when i again open activity my radiobutton shoulde be checked.

Here is my Adapter class :

holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
                    holder.radioButton.setChecked(true);

                if (lastCheckedRB != null) {
                    lastCheckedRB.setChecked(false);
                }
                if(selectedId!=0)
                {
                    holder.radioButton.setChecked(true);
                }

                //store the clicked radiobutton
                if(holder.radioButton.isChecked())
                {
                    teamList.clear();
                    lastCheckedRB = checked_rb;
                    teamList.add(name);

                    int checkedIndex = group.indexOfChild(checked_rb);
                }
                else
                {
                    holder.radioButton.setChecked(false);
                }
                int selectedId = holder.radioGroup.getCheckedRadioButtonId();

            }

Here is my Activity class :

protected void onResume() {
    super.onResume();
    try {
        adapter.lastCheckedRB.setChecked(true);
        }
        adapter.notifyDataSetChanged();
    } catch (NullPointerException e) {

    }
}


问:
C# MVC Handling nulls in ApplicationDbContext Constructor parameters
I have been using Session Value in the ApplicationDbContext Constructor. But in my big application somewhere i have used Threading which runs in background. And when that Threading method hits the ApplicationDbContext Constructor it doesn't get the Session Value as request is already completed. I get null reference exception, so the Application crashes.

Following is ApplicationDbContext Constructor Code :-

```<code>public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext.Current.Session["ConnStringName"].ToString())
        {
        }
</code>```

How to handle null sessions in the above constructor?

答:
```<code>public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString ?? whateverDefaultConnStringName)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

  public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext?.Current?.Session?["ConnStringName"].ToString())
        {
        }
</code>```

Body:
I have been using Session Value in the ApplicationDbContext Constructor. But in my big application somewhere i have used Threading which runs in background. And when that Threading method hits the ApplicationDbContext Constructor it doesn't get the Session Value as request is already completed. I get null reference exception, so the Application crashes.

Following is ApplicationDbContext Constructor Code :-

public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext.Current.Session["ConnStringName"].ToString())
        {
        }

How to handle null sessions in the above constructor?


问:
Use a variable in another required file
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

```<code><?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>
</code>```

index.php

```<code><?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>
</code>```

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

答:
Amir Agha,

When you call another .php file by include or require php acts as if the contents of the included file is inserted in the same line and the same scope (except for classes and functions) so your code in the view of php interpreter looks like this:

```<code><?php
  $userName = "Amir";
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
  echo $lang['hello'];
 ?>
</code>```

So this code must display:

Wellcome Amir to our website!

But why it doesn't work? Simply because you wrote $useName instead of $userName in your index.php file.

p.s.: Other answers made it very complicated. only change $useName to $userName

Title: Use a variable in another required file

Body:
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

<?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>

index.php

<?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

Body:
Amir Agha,

When you call another .php file by include or require php acts as if the contents of the included file is inserted in the same line and the same scope (except for classes and functions) so your code in the view of php interpreter looks like this:

<?php
  $userName = "Amir";
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
  echo $lang['hello'];
 ?>

So this code must display:

Wellcome Amir to our website!

But why it doesn't work? Simply because you wrote $useName instead of $userName in your index.php file.

p.s.: Other answers made it very complicated. only change $useName to $userName


问:
Visual Studio 2012 Install Fails: Program Compatibility Mode is on
I'm trying to install Visual Studio 2012 Express for Windows Desktop and every time I run the installer I get this error:

"Windows Program Compatibility mode is on. Turn it off and then try setup again."

I checked the file properties and compatibility mode was off. Googling found that changing the name to "vs_premium.exe" or "vs_ultimate.exe" or changing the registry keys might help, but the name changes had no effect, and there were no registry keys to delete. I have restarted my machine several times to no avail.

Changing to Visual Studio 2013 is not an option for me, as my work computer has Visual Studio 2012 on it which they will not update to 2013, and I need to work on my project on both computers.

The computer I am using has a Windows 8.1 HP Pavilion g6. I have installed Visual Studio 2013 for Windows Desktop, Web, and Windows, as well as the 30-day trial for Professional (which has recently expired). I have also installed Visual Studio 2012 for Windows Phone but I have not used it yet.

答:
Run as administrator. And for my 2013 installer I renamed it to be
vs_professional.exe

And it worked.

ContentLicense: CC BY-SA 4.0


问:
img-responsive failure by using IE11
I am new to this and I'm building my first landinpage with the help of bootstrap.
So don't be mean to me ;)

I added a big picture with the width of 2400px and added the class "img-responsive" to make the suitable for every viewport. But in IE11 it does not work.
In Mozilla or Chrome there is no problem but I can not find any solution.
Can somebody give me some advice?

Thank you very much,
Tobi

Here is a example of the html:

```

答:
In my case works with:</p>

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge">
</code>```

Title: img-responsive failure by using IE11

Body:
In my case works with:

<meta http-equiv="X-UA-Compatible" content="IE=edge">


问:
List View Item Click listener not working
Row layout for list view . the click on the items is not working.
the list.onItemClickListener function is not getting called even though there is no error or crash.There is some issue with it which im not able to figure out.

XML code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:focusable="true"
    android:clickable="true"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/invoice_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/button_selector"
        android:padding="5dp">

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

            <ImageView
                android:id="@+id/invoice_image"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/report_card_symbol"
                android:textColor="@color/black"
                android:focusable="false"/>

            <TextView
                android:id="@+id/order_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="16dp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/invoice_amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/order_id"
                android:layout_centerInParent="true"
                android:layout_marginTop="2dp"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="15sp"
                android:visibility="visible" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:focusable="false"
                android:src="@drawable/ic_arrow_right_new"
                android:textColor="@color/black" />
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答:
Check these lines of listview itemclicklistener:-</p>

```<code>        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id {
            Toast.makeText(MainActivity.this, "You Clicked at " + TextView[+position], Toast.LENGTH_SHORT).show();
        }
        });
</code>```

Body:
Row layout for list view . the click on the items is not working.
the list.onItemClickListener function is not getting called even though there is no error or crash.There is some issue with it which im not able to figure out.

XML code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:focusable="true"
    android:clickable="true"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/invoice_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/button_selector"
        android:padding="5dp">

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

            <ImageView
                android:id="@+id/invoice_image"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/report_card_symbol"
                android:textColor="@color/black"
                android:focusable="false"/>

            <TextView
                android:id="@+id/order_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="16dp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/invoice_amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/order_id"
                android:layout_centerInParent="true"
                android:layout_marginTop="2dp"
                android:layout_toRightOf="@+id/invoice_image"
                android:ellipsize="end"
                android:maxLines="1"
                android:paddingLeft="10dp"
                android:text=""
                android:textColor="@color/black"
                android:textSize="15sp"
                android:visibility="visible" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:focusable="false"
                android:src="@drawable/ic_arrow_right_new"
                android:textColor="@color/black" />
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>

Body:
Check these lines of listview itemclicklistener:-

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id {
            Toast.makeText(MainActivity.this, "You Clicked at " + TextView[+position], Toast.LENGTH_SHORT).show();
        }
        });


问:
Unable to click on link using selenium webdriver
Tried using xpath,css,id, href, partial text,link text nothing is working
Is returning no text exists on the page

wanna click on Quality Center

how to click please help me out

Below is the html code what i tried:-

```<code><document>
<html>
   <head>
   <body class="Nav">
      <a id="Cahill_Line" href="Cahill Line" onclick="highlight('Cahill_Line')" target="" title="</a><HR>"/>
         <hr/>
         <br/>
      <a id="Help" href="javascript:LoadPage('3001', 'https://wiki.ucern.com/display/ipfactory/Revision%2bInfo%2bHelp'); void(0);" onclick="highlight('Help')" target="" title="Help"> Help</a>
      <br/>
      <a id="Processing_Info" href="javascript:toggle('divProcessing_Info', 'Processing_Info','WebHelp/processing_info.htm');" title="Build Processing">Build Processing</a>
      <br/>
      <div id="divProcessing_Info" class="indent" style="DISPLAY: none;">
      <a id="FT_Reports" href="javascript:toggle('divFT_Reports', 'FT_Reports','WebHelp/feature_tracker_reports.htm');" title="Feature Tracker">Feature Tracker</a>
      <br/>
      <div id="divFT_Reports" class="indent" style="DISPLAY: none;">
      <a id="Maven2" href="javascript:toggle('divMaven2', 'Maven2','webhelp/maven2_reports.htm');" title="Maven2">Maven2</a>
      <br/>
      <div id="divMaven2" class="indent" style="DISPLAY: none;">
      <a id="Navigator" href="javascript:toggle('divNavigator', 'Navigator','webhelp/navigator_reports.htm');" title="Navigator">Navigator</a>
      <br/>
      <div id="divNavigator" class="indent" style="DISPLAY: none;">
      <a id="Pkg_Reports" href="javascript:toggle('divPkg_Reports', 'Pkg_Reports','WebHelp/package_reports.htm');" title="Package">Package</a>
      <br/>
      <div id="divPkg_Reports" class="indent" style="DISPLAY: none;">
      <a id="CertStatusRpt" href="javascript:toggle('divCertStatusRpt', 'CertStatusRpt','WebHelp/cert_status_reports.htm');" title="Quality Center" style="font-weight: normal;">Quality Center</a>
</code>```

答:
In C# you could do like this:</p>

```<code>var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementExists(By.Id("CertStatusRpt")));
driver.FindElement(By.Id("CertStatusRpt")).Click();
</code>```

Body:
Tried using xpath,css,id, href, partial text,link text nothing is working
Is returning no text exists on the page

wanna click on Quality Center

how to click please help me out

Below is the html code what i tried:-

<document>

      <a id="Cahill_Line" href="Cahill Line" onclick="highlight('Cahill_Line')" target="" title="
"/>

       Help

      Build Processing

      Feature Tracker

      Maven2

      Navigator

      Package

      Quality Center

Body:
In C# you could do like this:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementExists(By.Id("CertStatusRpt")));
driver.FindElement(By.Id("CertStatusRpt")).Click();


问:
android.view.InflateException: Binary XML file : Error inflating class fragment
I am using GoogleMap in android app using Android Studio. It was working fine and don't know why suddenly it stopped working. minSdkVersion is 15 and targetSdkVersion is 24. Please check my below code and help me to come out of this :

XML:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/mapFragment"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
</code>```

Gridle:

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.google.maps.android:android-maps-utils:0.4.3'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.googlecode.android-query:android-query:0.24.3'
    compile 'com.makeramen:roundedimageview:2.2.1'
}
</code>```

Java:

```<code>    public class MapsActivity extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {
          @Override
          public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
          SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                        .findFragmentById(R.id.mapFragment);
          }
    }
</code>```

Manifest:

```<code>        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_key" />
</code>```

Error:

It is giving error in xml at <fragment, error: android.view.InflateException: Binary XML file : Error inflating class fragment

答:
If it crashes second time, you need to destroy it.</p>

```<code>public void onDestroy() {
    super.onDestroy();
    getFragmentManager().beginTransaction().remove(mapfragmentnamehere).commit();
}
</code>```

Body:
I am using GoogleMap in android app using Android Studio. It was working fine and don't know why suddenly it stopped working. minSdkVersion is 15 and targetSdkVersion is 24. Please check my below code and help me to come out of this :

XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/mapFragment"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

Gridle:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.google.maps.android:android-maps-utils:0.4.3'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.googlecode.android-query:android-query:0.24.3'
    compile 'com.makeramen:roundedimageview:2.2.1'
}

Java:

    public class MapsActivity extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {
          @Override
          public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
          SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                        .findFragmentById(R.id.mapFragment);
          }
    }

Manifest:

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_key" />

Error:

It is giving error in xml at <fragment, error: android.view.InflateException: Binary XML file : Error inflating class fragment

Body:
If it crashes second time, you need to destroy it.

public void onDestroy() {
    super.onDestroy();
    getFragmentManager().beginTransaction().remove(mapfragmentnamehere).commit();
}


问:
Is there a HTML opposite to ?
Is there a tag in HTML that will only display its content if JavaScript is enabled? I know  works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.

The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.

答:
Easiest way I can think of:

```<code><html>
<head>
    <noscript><style> .jsonly { display: none } </style></noscript>
</head>

<body>
    <p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
</code>```

No document.write, no scripts, pure CSS.

Title: Is there a HTML opposite to <noscript>?

Body:
Easiest way I can think of:

<html>
<head>
    <noscript><style> .jsonly { display: none } </style></noscript>
</head>

<body>
    <p class="jsonly">You are a JavaScript User!</p>
</body>
</html>

No document.write, no scripts, pure CSS.

OwnerDisplayName: Will


问:
Text change listener on list view
I have a list view with hym names. I also hav implemented a textchange listener to filter results on list view as per edit text input. The filter works fine but the problem is when i click on the result it calls an item on postion 0 instead of lets say item on position 7

```<code>public class MainActivity extends Activity {
private ListView list;

ArrayAdapter<String> adapter;
// Search EditText
EditText search;
// ArrayList for Listview
ArrayList<HashMap<String,      String>>
colourList;

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

list=(ListView)                     findViewById(R.id.list1);

String[] colours = new     String[]
{
"Black",
"Brown",
"Cream",
"Green",
"Meroon",
"orange",
"Purple",
"Red",
"White",
"Yellow"};

adapter = new ArrayAdapter <     String > (this,                                 R.layout.list_item,                 R.id.colour_names, colours);

list = (ListView)     findViewById(R.id.list1);
list.setAdapter(adapter);
search = (EditText)
findViewById(R.id.search);

search.addTextChangedListener(new         TextWatcher() {

public void     onTextChanged(CharSequence cs,int     arg1,int arg2,int arg3) {

// When user changed the Text

                        MainActivity.this.adapter.getFilter().filter(cs);

}

public void     beforeTextChanged(CharSequence arg0,int arg1,int arg2,int arg3)

{

// TODO Auto-generated method stub

}

@Override

public void     afterTextChanged(Editable arg0)

{

// TODO Auto-generated method stub

}});

 list.setOnItemClickListener(new         AdapterView.OnItemClickListener()
{
public void     onItemClick(AdapterView<?>
parent,View view,
int positions,long id)
{
if(positions==0)
{
Intent myIntent=new     Intent(view.getContext(),                                       Black.class);
                        startActivityForResult(myIntent,0);
}
if(positions==1)
{
Intent myIntent=new Intent(view.getContext(),
                                              Brown.class);
                    startActivityForResult(myIntent,0);
}
                if(positions==2)
                {
Intent myIntent=new Intent
                    (view.getContext(),
                     Cream.class);
                        startActivityForResult(myIntent,0);
}
if(positions==3)
{
Intent myIntent=new Intent
(view.getContext(),
                     Green.class);
                    startActivityForResult(myIntent,0);
}
                    if(positions==4)
{
Intent myIntent=new Intent(view.getContext(),
                    Meroon.class);
                    startActivityForResult(myIntent,0);
}
if(positions==5)
{
Intent myIntent=new  Intent(view.getContext(),Orange.class);
   startActivityForResult(myIntent,0);
}
</code>```

EDIT:

All the answers are not working,  please help.

答: Use setTag() to store its original position or the id of the name on the listview item and use getTag() to determine which item has clicked

Title: Text change listener on list view

Body:
I have a list view with hym names. I also hav implemented a textchange listener to filter results on list view as per edit text input. The filter works fine but the problem is when i click on the result it calls an item on postion 0 instead of lets say item on position 7

public class MainActivity extends Activity {
private ListView list;

ArrayAdapter<String> adapter;
// Search EditText
EditText search;
// ArrayList for Listview
ArrayList<HashMap<String,      String>>
colourList;

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

list=(ListView)                     findViewById(R.id.list1);

String[] colours = new     String[]
{
"Black",
"Brown",
"Cream",
"Green",
"Meroon",
"orange",
"Purple",
"Red",
"White",
"Yellow"};

adapter = new ArrayAdapter <     String > (this,                                 R.layout.list_item,                 R.id.colour_names, colours);

list = (ListView)     findViewById(R.id.list1);
list.setAdapter(adapter);
search = (EditText)
findViewById(R.id.search);

search.addTextChangedListener(new         TextWatcher() {

public void     onTextChanged(CharSequence cs,int     arg1,int arg2,int arg3) {

// When user changed the Text

                        MainActivity.this.adapter.getFilter().filter(cs);

}

public void     beforeTextChanged(CharSequence arg0,int arg1,int arg2,int arg3)

{

// TODO Auto-generated method stub

}

@Override

public void     afterTextChanged(Editable arg0)

{

// TODO Auto-generated method stub

}});

 list.setOnItemClickListener(new         AdapterView.OnItemClickListener()
{
public void     onItemClick(AdapterView<?>
parent,View view,
int positions,long id)
{
if(positions==0)
{
Intent myIntent=new     Intent(view.getContext(),                                       Black.class);
                        startActivityForResult(myIntent,0);
}
if(positions==1)
{
Intent myIntent=new Intent(view.getContext(),
                                              Brown.class);
                    startActivityForResult(myIntent,0);
}
                if(positions==2)
                {
Intent myIntent=new Intent
                    (view.getContext(),
                     Cream.class);
                        startActivityForResult(myIntent,0);
}
if(positions==3)
{
Intent myIntent=new Intent
(view.getContext(),
                     Green.class);
                    startActivityForResult(myIntent,0);
}
                    if(positions==4)
{
Intent myIntent=new Intent(view.getContext(),
                    Meroon.class);
                    startActivityForResult(myIntent,0);
}
if(positions==5)
{
Intent myIntent=new  Intent(view.getContext(),Orange.class);
   startActivityForResult(myIntent,0);
}

EDIT:

All the answers are not working,  please help.


问:
Check if vertex already exists before an add_edge using Boost Graph [BGL]
Is there a way to check if a vertex in a graph created using Boost already exists rather than looping through the vertices?

And if it already exists, how can I add a new edge using its vertex descriptor?

Example:

```<code>Graph g;
vertex v;

v = add_vertex(1, g);
vertex_name[v] = "root";

v = add_vertex(2, g);
vertex_name[v] = "vert_2";

v = add_vertex(3, g);
vertex_name[v] = "vert_3";

// This is not possible
edge e1;
if (vertex.find("root") == vertex.end()) {
   (boost::add_edge("root", "vert_2", g)).first
}
</code>```

答:
I think you may like the labeled_graph adaptor:

Live On Coliru

```<code>#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/labeled_graph.hpp>

using namespace boost;

int main()
{
    using AdjList = adjacency_list<setS, vecS, directedS>;
    using Graph = labeled_graph<AdjList, std::string, hash_mapS>;

    Graph g;

    for (std::string name : { "root", "vert_2", "vert_3" }) {
        add_vertex(name, g);
    }

    struct { std::string from, to; } edges [] = {
        {"root", "vert_2"},
        {"vert_2", "vert_3"},
        {"vert_2", "vert_3"},
        {"vert_2", "new_1"},
        {"new_1", "new_2"},
    };

    for (auto const& addition : edges) {
        if (g.vertex(addition.from) == g.null_vertex())
            std::cout << "source vertex (" << addition.from << ") not present\n";
        else if (g.vertex(addition.to) == g.null_vertex())
            std::cout << "target vertex (" << addition.to << ") not present\n";
        else {
            auto insertion = add_edge_by_label(addition.from, addition.to, g);
            std::cout << "Edge: (" << addition.from << " -> " << addition.to << ") "
                << (insertion.second? "inserted":"already exists")
                << "\n";
        }
    }
}
</code>```

Prints:

```<code>Edge: (root -> vert_2) inserted
Edge: (vert_2 -> vert_3) inserted
Edge: (vert_2 -> vert_3) already exists
target vertex (new_1) not present
source vertex (new_1) not present
</code>```

Body:
Is there a way to check if a vertex in a graph created using Boost already exists rather than looping through the vertices?

And if it already exists, how can I add a new edge using its vertex descriptor?

Example:

Graph g;
vertex v;

v = add_vertex(1, g);
vertex_name[v] = "root";

v = add_vertex(2, g);
vertex_name[v] = "vert_2";

v = add_vertex(3, g);
vertex_name[v] = "vert_3";

// This is not possible
edge e1;
if (vertex.find("root") == vertex.end()) {
   (boost::add_edge("root", "vert_2", g)).first
}

Body:
I think you may like the labeled_graph adaptor:

Live On Coliru

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/labeled_graph.hpp>

using namespace boost;

int main()
{
    using AdjList = adjacency_list<setS, vecS, directedS>;
    using Graph = labeled_graph<AdjList, std::string, hash_mapS>;

    Graph g;

    for (std::string name : { "root", "vert_2", "vert_3" }) {
        add_vertex(name, g);
    }

    struct { std::string from, to; } edges [] = {
        {"root", "vert_2"},
        {"vert_2", "vert_3"},
        {"vert_2", "vert_3"},
        {"vert_2", "new_1"},
        {"new_1", "new_2"},
    };

    for (auto const& addition : edges) {
        if (g.vertex(addition.from) == g.null_vertex())
            std::cout << "source vertex (" << addition.from << ") not present\n";
        else if (g.vertex(addition.to) == g.null_vertex())
            std::cout << "target vertex (" << addition.to << ") not present\n";
        else {
            auto insertion = add_edge_by_label(addition.from, addition.to, g);
            std::cout << "Edge: (" << addition.from << " -> " << addition.to << ") "
                << (insertion.second? "inserted":"already exists")
                << "\n";
        }
    }
}

Prints:

Edge: (root -> vert_2) inserted
Edge: (vert_2 -> vert_3) inserted
Edge: (vert_2 -> vert_3) already exists
target vertex (new_1) not present
source vertex (new_1) not present


问:
See type of Garbage Collector in Java Mission Control
How to see type of Garbage Collector in Java Mission Control?

I investigated all tabs including MBeans Browser, but didn't find the type of GC. I can only suppose it by memory regions enumerated on the Memory tab.

答: Click on Memory tab and then GC Configuration (Bottom of the window) you will see the entire gc config here including GC Types, Parallel GC Threads, Concurrent GC Threads etc., The screenshot is fom JMC 5.5.0


问:
Knockout.js web link RegEx
I'm trying to validate web URL link in my application through Knockout.js. Because total form is done in Knockout.js I tried some RegEx but it's not done</p>

```<code><div class="input" data-bind="validationElement5: linkdocrequiredTextInput2, css: {'is-not-empty': linkdocrequiredTextInput2}">
    <input class="input-field" data-bind="textInput: linkdocrequiredTextInput2" id="linkdocurlInputTextId">
    self.linkdocrequiredTextInput2 = ko.observable().extend({ required: true })
</div>
</code>```

Title: Knockout.js web link RegEx

Body:
I'm trying to validate web URL link in my application through Knockout.js. Because total form is done in Knockout.js I tried some RegEx but it's not done

    <input class="input-field" data-bind="textInput: linkdocrequiredTextInput2" id="linkdocurlInputTextId">
    self.linkdocrequiredTextInput2 = ko.observable().extend({ required: true })

Body:
you can use following function on form submit to validate URL

  function validateURL(textval) {
    var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
    return urlregex.test(textval);
}


答:
Make a function one in lang-en.php

```<code><?php
function lang($username)
{
$lang['hello'] = $username;
echo $lang['hello'];
}
?>
</code>```

In index.php call that function

```<code><?php
require_once("lang-en.php");
lang('arun');
?>
</code>```

Title: Use a variable in another required file

Body:
Make a function one in lang-en.php

<?php
function lang($username)
{
$lang['hello'] = $username;
echo $lang['hello'];
}
?>

In index.php call that function

<?php
require_once("lang-en.php");
lang('arun');
?>


问:
How can i check double array for uniqueness?
For example we have

String [][] doubleArray = {{"a","1"},{"b","3"},{"a","1"},{"c","1"}};.

How can i create a new array with only uniqueness subarrays :

{{"a","1"},{"b","3"},{"c","1"}}

What i tryed :

Set <String []> uniq = new HashSet<String []>(Arrays.asList(doubleArray));

But Java doesnt see the difference between {"a","1"} and {"a","1"} , so uniq returns me set of all subarrays of doubleArray, including clones.

答:
You can use Map like this:

```<code>String [][] doubleArray = {{"a","1"},{"b","3"},{"a","1"},{"c","1"}};
Map<String, String> map = new HashMap<>();
for (String[] strings : doubleArray) {
    map.put(strings[0], strings[1]);
}
System.out.println("map = " + map);
</code>```

The result:

```<code>map = {a=1, b=3, c=1}
</code>```

Body:
You can use Map like this:

String [][] doubleArray = {{"a","1"},{"b","3"},{"a","1"},{"c","1"}};
Map<String, String> map = new HashMap<>();
for (String[] strings : doubleArray) {
    map.put(strings[0], strings[1]);
}
System.out.println("map = " + map);

The result:

map = {a=1, b=3, c=1}


问:
Swift encode & in the GET parameter
I have a simple GET request for login. Username is Silver and password is  MOto&@10

I am using SwiftHttp framework for handling requests. On hitting login request, I always get response as false.

However on hitting the login request url on browser (replaced actual domain with server) I get true :

https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10

There is something wrong with encoding & in the password. Though I have replaced it with percent encoding. Here is my code :

```<code>do {
   let passwordString = self.convertSpecialCharacters(string: password.text!)
   print("%@", passwordString)
   let opt = try HTTP.GET(Constants.kLoginUrl, parameters: ["login": username.text!, "pass": passwordString])
   opt.start { response in
             if let err = response.error {
                 print("error: \(err.localizedDescription)")
                 return
             }

             print("opt finished: \(response.description)")
             self.parseLoginResponse(response.data)
}
} catch _ as NSError {

}
</code>```

And this is convertSpecialCharacters :

```<code>func convertSpecialCharacters(string: String) -> String {
        var newString = string

        let arrayEncode = ["&", "<", ">", "\"", "'", "-", "..."]

        for (escaped_char) in arrayEncode {
            newString = newString.encode(escaped_char)
        }

        return newString
    }
</code>```

Extension for encoding :

```<code>extension String {
        func encode(_ chars: String) -> String
        {
            let forbidden = CharacterSet(charactersIn: chars)
            return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
        }
    }
</code>```

答:
A suitable way is to use URLComponents which handles all percent encoding:

```<code>var urlComponents = URLComponents(string: "https://server/api/check-access/by-login-pass")!
let queryItems = [URLQueryItem(name:"_key", value:"wlyOF7TM8Y3tn19KUdlq"),
                  URLQueryItem(name:"login", value:"silver"),
                  URLQueryItem(name:"pass", value:"MOto&@10")]
urlComponents.queryItems = queryItems
let url = urlComponents.url

print(url) // "https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10"
</code>```

PS: I totally agree with luk2302's comment.

Title: Swift encode & in the GET parameter

Body:
I have a simple GET request for login. Username is Silver and password is  MOto&@10

I am using SwiftHttp framework for handling requests. On hitting login request, I always get response as false.

However on hitting the login request url on browser (replaced actual domain with server) I get true :

https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10

There is something wrong with encoding & in the password. Though I have replaced it with percent encoding. Here is my code :

do {
   let passwordString = self.convertSpecialCharacters(string: password.text!)
   print("%@", passwordString)
   let opt = try HTTP.GET(Constants.kLoginUrl, parameters: ["login": username.text!, "pass": passwordString])
   opt.start { response in
             if let err = response.error {
                 print("error: \(err.localizedDescription)")
                 return
             }

             print("opt finished: \(response.description)")
             self.parseLoginResponse(response.data)
}
} catch _ as NSError {

}

And this is convertSpecialCharacters :

func convertSpecialCharacters(string: String) -> String {
        var newString = string

        let arrayEncode = ["&", "<", ">", "\"", "'", "-", "..."]

        for (escaped_char) in arrayEncode {
            newString = newString.encode(escaped_char)
        }

        return newString
    }

Extension for encoding :

extension String {
        func encode(_ chars: String) -> String
        {
            let forbidden = CharacterSet(charactersIn: chars)
            return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
        }
    }

Body:
A suitable way is to use URLComponents which handles all percent encoding:

var urlComponents = URLComponents(string: "https://server/api/check-access/by-login-pass")!
let queryItems = [URLQueryItem(name:"_key", value:"wlyOF7TM8Y3tn19KUdlq"),
                  URLQueryItem(name:"login", value:"silver"),
                  URLQueryItem(name:"pass", value:"MOto&@10")]
urlComponents.queryItems = queryItems
let url = urlComponents.url

print(url) // "https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10"

PS: I totally agree with luk2302's comment.


问:
Is there a better way to create this model? (Django)
I have a model that pings a REST service and saves the results.

```<code>class StoreStatus(models.Model):
    store = models.OneToOneField(Store)
    status = models.TextField()

    def save(self, *args, **kwargs):
        self.status = get_store_information(self.store.code)
        self.pk = self.store.pk
        super( StoreStatus, self ).save(*args, **kwargs)
</code>```

I need to run it every repeatedly and figure I can just .save() it in a view, since the "Store" object is in the majority of my views.

Is there a better way to do this? I had to the set the pk manually because I was getting duplicate errors when I tried to save a second time.

Seems kind of dirty, and I'm trying to improve my coding.
Thanks

答:
That looks quite bad.

First, associating the retrieval of the status information with the saving of the object is quite a bad idea. If 'updating' is the only action you'll ever perform on this model, then maybe a better idea would be to write a an "update()" method that automatically saves once the status is updated, instead of doing it the other way around.

```<code>def update(self):
    self.status = get_store_information(self.store.code)
    self.save()
</code>```

Second: how are you creating the first instance of this model? You'll get duplication errors if you are trying to save a new instance every time the model gets updated. Say, if you do something like this:

```<code># this will crap out
update = Update(mystore)
update.save()
</code>```

What you should be doing is something like:

```<code># this will work (provided we have 'update')
mystore.status.update()
</code>```

Or:

```<code># always retrieve the stored instance before saving
status, created = StoreStatus.objects.get_or_create(store=mystore)
status.update()
</code>```

In case you are lazy enough, you can always add an "update_status" method to your Store model and perform the creation/update there. It's always better to be explicit about what you are doing. Remember: Django is based upon the principle of least surprise, and so should your code! :)

Body:
I have a model that pings a REST service and saves the results.

class StoreStatus(models.Model):
    store = models.OneToOneField(Store)
    status = models.TextField()

    def save(self, *args, **kwargs):
        self.status = get_store_information(self.store.code)
        self.pk = self.store.pk
        super( StoreStatus, self ).save(*args, **kwargs)

I need to run it every repeatedly and figure I can just .save() it in a view, since the "Store" object is in the majority of my views.

Is there a better way to do this? I had to the set the pk manually because I was getting duplicate errors when I tried to save a second time.

Seems kind of dirty, and I'm trying to improve my coding.
Thanks

Body:
That looks quite bad.

First, associating the retrieval of the status information with the saving of the object is quite a bad idea. If 'updating' is the only action you'll ever perform on this model, then maybe a better idea would be to write a an "update()" method that automatically saves once the status is updated, instead of doing it the other way around.

def update(self):
    self.status = get_store_information(self.store.code)
    self.save()

Second: how are you creating the first instance of this model? You'll get duplication errors if you are trying to save a new instance every time the model gets updated. Say, if you do something like this:

# this will crap out
update = Update(mystore)
update.save()

What you should be doing is something like:

# this will work (provided we have 'update')
mystore.status.update()

Or:

# always retrieve the stored instance before saving
status, created = StoreStatus.objects.get_or_create(store=mystore)
status.update()

In case you are lazy enough, you can always add an "update_status" method to your Store model and perform the creation/update there. It's always better to be explicit about what you are doing. Remember: Django is based upon the principle of least surprise, and so should your code! :)


问:
MYSQL - How to go about doing a join with subselect join
I am not sure how to word this so the question maybe look vague. I will try my best to describe the issue I am having.

I have a 3 tables:

```<code>LibraryRepairEvent
MemberBorrowsBook
Book
</code>```

This is how LibraryRepairEvent looks like:

This is how MemberBorrowsBook looks like:

This is how Book looks like:

What I am trying to do is out of all the events there, I want to find the organiser who raised the most donations and fetch some information in regards from the Book Table.

This is what I have so far :

```<code>SELECT *
FROM Book bk
JOIN (SELECT b.bookID, SUM(lre.donationsCollected) as maxDonations
FROM Book b
    JOIN MemberBorrowsBook mbb
            ON b.bookID = mbb.bookID
    LEFT JOIN LibraryRepairEvent lre
            ON mbb.memberID = lre.organiserID
) a
ON bk.bookID = a.bookID
GROUP BY maxDonations
ORDER BY maxDonations DESC
</code>```

However this query does not work as how it should be. Based on the screenshots I have included. It's returning the wrong information back.

Based on the example, LibraryRepairEvent shows organiserId jessicaalba@gmail.com has the highest amount raised (tallying up the donations of 900). Now it will look at the MemberBorrowsBook  table by using the join on memberID to get the bookID. So here I will have 45441 and 45651 as the bookID which then will be taken to the Book table. So now the end result should have been the details of these ID's but I am getting wrong data back.

Please ask me if unsure of anything.

答:
I think this should do. Select your columns accordingly.
I set up a rextester demo here, it would have helped us a lot if you had done so yourself. Perhaps next time :-)

```<code>select * from
(
   select OrganiserID, sum(DonationsCollected) totalDonations from LibraryRepairEvent group by OrganiserID
) summary
join MemberBorrowsBook mbb on mbb.MemberID = summary.OrganiserID
join Book b on mbb.BookID = b.BookID
where totalDonations = (
    select max(totalDonations) from
    (
        select sum(DonationsCollected) totalDonations from LibraryRepairEvent group by OrganiserID
    ) summary2
)
;
</code>```

NOTE This statement returns the information related to all rank-1 organisers. So if there are more than one achieving the highest donation sum, all of them will be reported. If you only want one of them this statement can be simplified significantly.

Body:
I am not sure how to word this so the question maybe look vague. I will try my best to describe the issue I am having.

I have a 3 tables:

LibraryRepairEvent
MemberBorrowsBook
Book

This is how LibraryRepairEvent looks like:

This is how MemberBorrowsBook looks like:

This is how Book looks like:

What I am trying to do is out of all the events there, I want to find the organiser who raised the most donations and fetch some information in regards from the Book Table.

This is what I have so far :

SELECT *
FROM Book bk
JOIN (SELECT b.bookID, SUM(lre.donationsCollected) as maxDonations
FROM Book b
    JOIN MemberBorrowsBook mbb
            ON b.bookID = mbb.bookID
    LEFT JOIN LibraryRepairEvent lre
            ON mbb.memberID = lre.organiserID
) a
ON bk.bookID = a.bookID
GROUP BY maxDonations
ORDER BY maxDonations DESC

However this query does not work as how it should be. Based on the screenshots I have included. It's returning the wrong information back.

Based on the example, LibraryRepairEvent shows organiserId jessicaalba@gmail.com has the highest amount raised (tallying up the donations of 900). Now it will look at the MemberBorrowsBook  table by using the join on memberID to get the bookID. So here I will have 45441 and 45651 as the bookID which then will be taken to the Book table. So now the end result should have been the details of these ID's but I am getting wrong data back.

Please ask me if unsure of anything.

Body:
I think this should do. Select your columns accordingly.
I set up a rextester demo here, it would have helped us a lot if you had done so yourself. Perhaps next time :-)

select * from
(
   select OrganiserID, sum(DonationsCollected) totalDonations from LibraryRepairEvent group by OrganiserID
) summary
join MemberBorrowsBook mbb on mbb.MemberID = summary.OrganiserID
join Book b on mbb.BookID = b.BookID
where totalDonations = (
    select max(totalDonations) from
    (
        select sum(DonationsCollected) totalDonations from LibraryRepairEvent group by OrganiserID
    ) summary2
)
;

NOTE This statement returns the information related to all rank-1 organisers. So if there are more than one achieving the highest donation sum, all of them will be reported. If you only want one of them this statement can be simplified significantly.


问:
What is the complexity of converting scala collection from one type to another?
I would like to know the complexity of converting scala collection operations like following ones :

```<code>List.fill(n)(1).toArray
Array.fill(n)(1).toList
ArrayBuffer( Array.fill(n)(1):_* )
</code>```

I suppose that for those exemples we need to loop over all elements so it will be O(n), unfortunately i don't know the subroutines under those conversions so the complexity may be optimized.

Don't hesitate to add complexity for others kind of scala conversions.

答:
I took a quick look at the source code, and they all appear to be O(n) as you thought.

Here's for example the subroutine copyToArray (used by toArray):

```<code>override /*TraversableLike*/ def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
  var i = start
  val end = (start + len) min xs.length
  val it = iterator
  while (i < end && it.hasNext) {
    xs(i) = it.next()
    i += 1
  }
}
</code>```

source

As you can see it simply iterates over the collection linearly.

Body:
I would like to know the complexity of converting scala collection operations like following ones :

List.fill(n)(1).toArray
Array.fill(n)(1).toList
ArrayBuffer( Array.fill(n)(1):_* )

I suppose that for those exemples we need to loop over all elements so it will be O(n), unfortunately i don't know the subroutines under those conversions so the complexity may be optimized.

Don't hesitate to add complexity for others kind of scala conversions.

Body:
I took a quick look at the source code, and they all appear to be O(n) as you thought.

Here's for example the subroutine copyToArray (used by toArray):

override /*TraversableLike*/ def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
  var i = start
  val end = (start + len) min xs.length
  val it = iterator
  while (i < end && it.hasNext) {
    xs(i) = it.next()
    i += 1
  }
}

source

As you can see it simply iterates over the collection linearly.


问:
Can I have different font style/sizes in the same graphviz record?
I have the following simple graph and I want to have only the text GetArea() in italics. Is this possible?

```<code>digraph {
  rankdir = BT;
  node [shape=record];
  cPolygon [label="{cPolygon|GetArea()}"];
  {rank=same; cSquare cTriangle}
  cSquare -> cPolygon;
  cTriangle -> cPolygon;
}
</code>```

答:
I think you should use HTML like labels:

```<code>digraph {
  rankdir = BT;
  node [shape=record];
  cPolygon [label=<<table border="0"><tr><td>cPolygon</td></tr><tr><td><i>GetArea()</i></td></tr></table>>];
  {rank=same; cSquare cTriangle}
  cSquare -> cPolygon;
  cTriangle -> cPolygon;
}
</code>```

yields

edit

a horizontal row:

```<code>...
  cPolygon [label=<<table border="0"><tr><td>cPolygon</td></tr><hr/><tr><td><i>GetArea()</i></td></tr></table>>];
...
</code>```

Body:
I have the following simple graph and I want to have only the text GetArea() in italics. Is this possible?

digraph {
  rankdir = BT;
  node [shape=record];
  cPolygon [label="{cPolygon|GetArea()}"];
  {rank=same; cSquare cTriangle}
  cSquare -> cPolygon;
  cTriangle -> cPolygon;
}

Body:
I think you should use HTML like labels:

digraph {
  rankdir = BT;
  node [shape=record];
  cPolygon [label=<<table border="0"><tr><td>cPolygon</td></tr><tr><td><i>GetArea()</i></td></tr></table>>];
  {rank=same; cSquare cTriangle}
  cSquare -> cPolygon;
  cTriangle -> cPolygon;
}

yields

edit

a horizontal row:

...
  cPolygon [label=<<table border="0"><tr><td>cPolygon</td></tr><hr/><tr><td><i>GetArea()</i></td></tr></table>>];
...


问:
Warning: in_array() expects parameter 2 to be array, null given in
I have different headers for different categories within Woocommerce on my website.

I am checking the product category string against an array with the in_array function. Before using the get_template_part function to output the different header to the page.

This code was working fine and has only recently, randomly. Started displaying the PHP error message 'Warning: in_array() expects parameter 2 to be array, null given in'.

```<code>    // Gets the product categories to loop over and out put based on scenario below.

    $terms = wp_get_post_terms( $post->ID, 'product_cat' );

    foreach ( $terms as $term ) $categories[] = $term->slug;

    if ( is_front_page() ) {

        get_template_part( '/includes/header/header', 'front' );

    } elseif ( in_array( 'courses', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'single' );

    } elseif ( in_array( 'services', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'services' );

    } elseif (is_product_category() || is_shop()) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'archive' );

    }

    else {

        get_template_part( '/includes/header/header', 'with-menus' );

    }
</code>```

答:
You need to initialize $categories as empty array before foreach runs:

```<code>$terms = wp_get_post_terms( $post->ID, 'product_cat' );
$categories = array();

foreach ( $terms as $term ) $categories[] = $term->slug;
[...]
</code>```

If $terms is empty, you got an empty array $categories and you don't get this error.

Body:
I have different headers for different categories within Woocommerce on my website.

I am checking the product category string against an array with the in_array function. Before using the get_template_part function to output the different header to the page.

This code was working fine and has only recently, randomly. Started displaying the PHP error message 'Warning: in_array() expects parameter 2 to be array, null given in'.

    // Gets the product categories to loop over and out put based on scenario below.

    $terms = wp_get_post_terms( $post->ID, 'product_cat' );

    foreach ( $terms as $term ) $categories[] = $term->slug;

    if ( is_front_page() ) {

        get_template_part( '/includes/header/header', 'front' );

    } elseif ( in_array( 'courses', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'single' );

    } elseif ( in_array( 'services', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'services' );

    } elseif (is_product_category() || is_shop()) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'archive' );

    }

    else {

        get_template_part( '/includes/header/header', 'with-menus' );

    }

Body:
You need to initialize $categories as empty array before foreach runs:

$terms = wp_get_post_terms( $post->ID, 'product_cat' );
$categories = array();

foreach ( $terms as $term ) $categories[] = $term->slug;
[...]

If $terms is empty, you got an empty array $categories and you don't get this error.


问:
How to remove git pull message from windows
When I type git pull origin master on Ubuntu, it pulls the changes from the remote repository into my local repository, and it works fine.

However, if I do it on Windows (using git bash), it pulls the changes as a merge commit (as if I was accepting a pull request). So even if I'm just updating my local repository, next time I push it, the pull commit will be there.

Is there a way to remove this behaviour from Windows? I'd want it to be like Ubuntu, where pulling doens't cause a new commit.

答:
git pull equals git fetch plus git merge unless it is a fast forward, where the merge is not needed, or you have configured pull.rebase=true, in which case a rebase is done instead of a merge.

So there are two possibilities:

You have local commits in Windows but not in Ubuntu. Then, do a git fetch and optionally a git rebase (but be aware of the rebase rules!).

You have Ubuntu configured with pull.rebase=true but not Windows.

My advice anyway would be not to do git pull. Instead just do git fetch and from then on whatever you need.

PS: Something like this happened to me once, and it was because in Windows I had a couple of extra private commits (to adapt the project to Windows' quirkiness). So when doing a git pull those two commits where just in the middle. I did git config pull.rebase true and the problem was over.


问:
this and protoype javascript
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?</p>

```<code>function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);
</code>```

答:
d is a instance, to get the prototype use:</p>

```<code>d.constructor.prototype;
</code>```

Title: this and protoype javascript

Body:
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?

function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);

Body:
d is a instance, to get the prototype use:

d.constructor.prototype;


问:
Prevent Android activity dialog from closing on outside touch
I have an activity that is using the Theme.Dialog style such that it is a floating window over another activity. However, when I click outside the dialog window (on the background activity), the dialog closes. How can I stop this behaviour?</p>

答:
When using dialog as an activity in the onCreate add this</p>

```<code>setFinishOnTouchOutside(false);
</code>```

Body:
When using dialog as an activity in the onCreate add this

setFinishOnTouchOutside(false);


问:
How to create documentation with devtools while building a package?
Well, I want to create a documentation in my package project but I get this error:

```<code>library(devtools)
> devtools::document()
Updating varbinq documentation
Loading varbinq
Error: contains a blank line
</code>```

why when I have no blank line in my function! It looks like this:

```<code>#' function which do something
#'
#' @param x a value of something
#' @return a value of something2
#' @examples
#' f(2)
f <- function(x){
  x+2
}
</code>```

maybe it's because of others functions?

答: This might happen when there's a blank line in the package DESCRIPTION file. </p>

Body:
Well, I want to create a documentation in my package project but I get this error:

library(devtools)
> devtools::document()
Updating varbinq documentation
Loading varbinq
Error: contains a blank line

why when I have no blank line in my function! It looks like this:

#' function which do something
#'
#' @param x a value of something
#' @return a value of something2
#' @examples
#' f(2)
f <- function(x){
  x+2
}

maybe it's because of others functions?


问:
Use a variable in another required file
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

```<code><?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>
</code>```

index.php

```<code><?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>
</code>```

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

答:
you nearly had it
langen.php

```<code><?php

   //declare array
   $lang = array();
   $templang['hello1'] = "Wellcome ";
   $templang['hello2'] = " to our website!";
   //add new item in array
   array_push($lang,$templang);

?>
</code>```

index.php

```<code><?php
   $useName = "Amir";
   require_once("langen.php");
   //it is first entry of array row so [0] is 0
   echo $lang[0]['hello1'];
   echo $userName;
   echo $lang[0]['hello2'];
   //out is welcome amir to our website
?>
</code>```

this is a easy way too see how to pass variables a little long way but i didn't want to combine so that you can see how it works you can also do some reading about sessions for passing variables between pages that is not included

Title: Use a variable in another required file

Body:
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

<?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>

index.php

<?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

Body:
you nearly had it
langen.php

<?php

   //declare array
   $lang = array();
   $templang['hello1'] = "Wellcome ";
   $templang['hello2'] = " to our website!";
   //add new item in array
   array_push($lang,$templang);

?>

index.php

<?php
   $useName = "Amir";
   require_once("langen.php");
   //it is first entry of array row so [0] is 0
   echo $lang[0]['hello1'];
   echo $userName;
   echo $lang[0]['hello2'];
   //out is welcome amir to our website
?>

this is a easy way too see how to pass variables a little long way but i didn't want to combine so that you can see how it works you can also do some reading about sessions for passing variables between pages that is not included


问:
Picasso fails to decode some images: skia decode returned false
Update: It seems that this question boils down to that some images are correctly decoded, while some don't. If I convert the non-working JPEGs to pngs, they work. None of my images taken directly as JPEGs from either a Nikon D5000, a Panasonic Lumix or a Sony Experia phone can be decoded.

I am using Picasso to fill a ListView in my Android app. I am, however, running into the error --- decoder->decode returned false for the images I am to use, but it works fine for other pictures I run across around the web. Therefore, I believe it has something to do with the images, but I am not really sure. The error arises in the Skia library which is used by Picasso (as far as I know).

For example, this image works fine, while this does not, and it is the latter I need to work. All other pictures I need to use are taken with the same camera and edited by Gimp in the same way, resulting in images like the first one, but none of them work. Hence, I suspect it has something to do with the images themselves rather than the decoder.

A few questions that pops up:

Is it possible that the metadata can do something in this process? The metadata are similar in all the pictures.

Could it be something with the encoded images that makes the encoder go crazy? If so, what could it be and how can I investigate it? End of file missing or anything?

Is it possible to enable more debugging and output from Picasso or Skia? Stack traces, for example?

Will non-UTF8 characters mess things up, or is this handled correctly? The example image does not have UTF8 characters in it, but some of the images may have.

What I have tried:

I tried opening a non-working image in Inkscape and exporting it as a png file instead. Now, the image actually works, so there seems to be something with the JPEG encoding.

Another try was to open the image in Gimp and exporting to JPEG again, but that did not help.

I also tried opening the image in Shotwell and re-exporting to JPEG, both with and without the metadata, but none of these images work. Exporting to png works as with exporting to png from Inkscape.

All the non-working images are taken with a Nikon D5000 camera, so I tried taking a few images with a Sony Experia phone and a Panasonic Lumix camera. Non of the JPEGs work directly, but if converted to PNG they are all decoded.

I tried setting up a Picasso.Builder object as shown here, to get a stack trace. I have pasted the stack trace below. It might seem that it actually is the Android.BitmapFactory.decodeStream() that fails, as the stack trace points to com.squareup.picasso.BitmapHunter.decodeStream(), which utilizes Android.BitmapFactory.decodeStream(). So maybe the error has nothing to do with Skia after all.

I also used Imagemagick's identify -verbose on the working and the non-working images and compared the outputs. I was unable to find any differences that stood out, so it did not bring me any further.

Example Logcat output:

```<code>D/Picasso(528): Main        created      [R0] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Dispatcher  enqueued     [R0]+7ms
D/Picasso(528): Main        created      [R1] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Hunter      joined       [R1]+1ms to [R0]+10ms, [R1]+1ms
D/Picasso(528): Main        created      [R2] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Hunter      joined       [R2]+1ms to [R0]+14ms, [R1]+5ms, [R2]+2ms
D/Picasso(528): Hunter      executing    [R0]+21ms, [R1]+12ms, [R2]+9ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  retrying     [R0]+1456ms, [R1]+1447ms, [R2]+1444ms
D/Picasso(528): Hunter      executing    [R0]+1458ms, [R1]+1448ms, [R2]+1445ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  retrying     [R0]+2867ms, [R1]+2857ms, [R2]+2854ms
D/Picasso(528): Hunter      executing    [R0]+2868ms, [R1]+2859ms, [R2]+2855ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  batched      [R0]+3406ms, [R1]+3397ms, [R2]+3394ms for error
D/dalvikvm(249): GC_EXPLICIT freed 119 objects / 5288 bytes in 28ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R0]+3607ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R1]+3598ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R2]+3596ms
D/Picasso(528): Dispatcher  delivered    [R0]+3610ms, [R1]+3601ms, [R2]+3598ms
</code>```

Stack trace from Picasso, pointing to this file.

```<code>W/System.err(1467): java.io.IOException: Failed to decode stream.
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.decodeStream(BitmapHunter.java:145)
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:217)
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:159)
W/System.err(1467):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
W/System.err(1467):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
W/System.err(1467):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
W/System.err(1467):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
W/System.err(1467):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
W/System.err(1467):     at java.lang.Thread.run(Thread.java:1096)
W/System.err(1467):     at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:411)
</code>```

getView method in my BaseAdapter for the ListView:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    final View view;
    Recipe recipe = this.getItem(position);

    if (convertView != null){
        view = convertView;
        view.setTag(recipe.getId());
    }
    else{
        view = myActivity.getLayoutInflater().inflate(R.layout.recipe_item, parent, false);
        view.setTag(recipe.getId());
    }

    ImageView imageView = (ImageView) view.findViewById(R.id.filtered_recipes_list_image_view);

//  final String foo = "https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg";
    final String foo = "http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg";

    Picasso.with(myActivity).setIndicatorsEnabled(true);
    Picasso.with(myActivity).setLoggingEnabled(true);
    Picasso.with(myActivity).load(foo).into(imageView, new Callback() {

        @Override
        public void onSuccess() {
            Log.i("TAGZ", "Success! url = " + foo);
        }

        @Override
        public void onError() {
            Log.i("TAGZ", "Error! url = " + foo);
        }

    });

    return view;
}
</code>```

答:
Reason for that error is: You are trying to set an image of size which is more than your image view layout size.

I found a simple solution for that! If you are using picasso library for image loading..then, resize your image to fir your image view layout.

i.e, I have done like this:

```<code>Picasso.with(ImageLoaderActivity.this)
                        .load("https://static.pexels.com/photos/34578/pexels-photo.jpg")
                        .resize(200,250)
                        .into(img);
</code>```

Body:
Update: It seems that this question boils down to that some images are correctly decoded, while some don't. If I convert the non-working JPEGs to pngs, they work. None of my images taken directly as JPEGs from either a Nikon D5000, a Panasonic Lumix or a Sony Experia phone can be decoded.

I am using Picasso to fill a ListView in my Android app. I am, however, running into the error --- decoder->decode returned false for the images I am to use, but it works fine for other pictures I run across around the web. Therefore, I believe it has something to do with the images, but I am not really sure. The error arises in the Skia library which is used by Picasso (as far as I know).

For example, this image works fine, while this does not, and it is the latter I need to work. All other pictures I need to use are taken with the same camera and edited by Gimp in the same way, resulting in images like the first one, but none of them work. Hence, I suspect it has something to do with the images themselves rather than the decoder.

A few questions that pops up:

Is it possible that the metadata can do something in this process? The metadata are similar in all the pictures.

Could it be something with the encoded images that makes the encoder go crazy? If so, what could it be and how can I investigate it? End of file missing or anything?

Is it possible to enable more debugging and output from Picasso or Skia? Stack traces, for example?

Will non-UTF8 characters mess things up, or is this handled correctly? The example image does not have UTF8 characters in it, but some of the images may have.

What I have tried:

I tried opening a non-working image in Inkscape and exporting it as a png file instead. Now, the image actually works, so there seems to be something with the JPEG encoding.

Another try was to open the image in Gimp and exporting to JPEG again, but that did not help.

I also tried opening the image in Shotwell and re-exporting to JPEG, both with and without the metadata, but none of these images work. Exporting to png works as with exporting to png from Inkscape.

All the non-working images are taken with a Nikon D5000 camera, so I tried taking a few images with a Sony Experia phone and a Panasonic Lumix camera. Non of the JPEGs work directly, but if converted to PNG they are all decoded.

I tried setting up a Picasso.Builder object as shown here, to get a stack trace. I have pasted the stack trace below. It might seem that it actually is the Android.BitmapFactory.decodeStream() that fails, as the stack trace points to com.squareup.picasso.BitmapHunter.decodeStream(), which utilizes Android.BitmapFactory.decodeStream(). So maybe the error has nothing to do with Skia after all.

I also used Imagemagick's identify -verbose on the working and the non-working images and compared the outputs. I was unable to find any differences that stood out, so it did not bring me any further.

Example Logcat output:

D/Picasso(528): Main        created      [R0] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Dispatcher  enqueued     [R0]+7ms
D/Picasso(528): Main        created      [R1] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Hunter      joined       [R1]+1ms to [R0]+10ms, [R1]+1ms
D/Picasso(528): Main        created      [R2] Request{http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg}
D/Picasso(528): Hunter      joined       [R2]+1ms to [R0]+14ms, [R1]+5ms, [R2]+2ms
D/Picasso(528): Hunter      executing    [R0]+21ms, [R1]+12ms, [R2]+9ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  retrying     [R0]+1456ms, [R1]+1447ms, [R2]+1444ms
D/Picasso(528): Hunter      executing    [R0]+1458ms, [R1]+1448ms, [R2]+1445ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  retrying     [R0]+2867ms, [R1]+2857ms, [R2]+2854ms
D/Picasso(528): Hunter      executing    [R0]+2868ms, [R1]+2859ms, [R2]+2855ms
D/skia(528):    --- decoder->decode returned false
D/Picasso(528): Dispatcher  batched      [R0]+3406ms, [R1]+3397ms, [R2]+3394ms for error
D/dalvikvm(249): GC_EXPLICIT freed 119 objects / 5288 bytes in 28ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R0]+3607ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R1]+3598ms
I/TAGZ(528):    Error! url = http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg
D/Picasso(528): Main        errored      [R2]+3596ms
D/Picasso(528): Dispatcher  delivered    [R0]+3610ms, [R1]+3601ms, [R2]+3598ms

Stack trace from Picasso, pointing to this file.

W/System.err(1467): java.io.IOException: Failed to decode stream.
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.decodeStream(BitmapHunter.java:145)
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:217)
W/System.err(1467):     at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:159)
W/System.err(1467):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
W/System.err(1467):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
W/System.err(1467):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
W/System.err(1467):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
W/System.err(1467):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
W/System.err(1467):     at java.lang.Thread.run(Thread.java:1096)
W/System.err(1467):     at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:411)

getView method in my BaseAdapter for the ListView:

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    final View view;
    Recipe recipe = this.getItem(position);

    if (convertView != null){
        view = convertView;
        view.setTag(recipe.getId());
    }
    else{
        view = myActivity.getLayoutInflater().inflate(R.layout.recipe_item, parent, false);
        view.setTag(recipe.getId());
    }

    ImageView imageView = (ImageView) view.findViewById(R.id.filtered_recipes_list_image_view);

//  final String foo = "https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg";
    final String foo = "http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg";

    Picasso.with(myActivity).setIndicatorsEnabled(true);
    Picasso.with(myActivity).setLoggingEnabled(true);
    Picasso.with(myActivity).load(foo).into(imageView, new Callback() {

        @Override
        public void onSuccess() {
            Log.i("TAGZ", "Success! url = " + foo);
        }

        @Override
        public void onError() {
            Log.i("TAGZ", "Error! url = " + foo);
        }

    });

    return view;
}

Body:
Reason for that error is: You are trying to set an image of size which is more than your image view layout size.

I found a simple solution for that! If you are using picasso library for image loading..then, resize your image to fir your image view layout.

i.e, I have done like this:

Picasso.with(ImageLoaderActivity.this)
                        .load("https://static.pexels.com/photos/34578/pexels-photo.jpg")
                        .resize(200,250)
                        .into(img);


问:
angularjs bootstrap - set title if
I have a
 that I want to give it title

```<code><tr title="qualified">
</code>```

if a controller variable qualified is true

I am using AngularJS.

答:
I solved it this way:</p>

```<code><tr title="{{ qualified ? 'Qualified' : ''}}">
</code>```

Title: angularjs bootstrap - set title if

Body:
I have a
 that I want to give it title

if a controller variable qualified is true

I am using AngularJS.

Body:
I solved it this way:

<tr title="{{ qualified ? 'Qualified' : ''}}">


问:
How to learn to write idiomatic c++ code
I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

答:
The best way to learn how to write C++ idiomatic code is ... to write C++ code and to have your code reviewed by some advanced C++ developer.
You should also read some of the most famous C++ books (Effective C++ by Scott Meyers is a good start, Modern C++ Design is a bad book to learn how to write nice C++ code but is a great book if you want to discover and understand the concept of generic programming).

On top of all that, you should read much doc about STL and boost and learn a lot about iterators. Iterators are the key to use STL (and boost implementation of containers and algorithms) and if you don't know how to use them, you won't write C++ idiomatic code. Ever.


问:
constraint on static fields and type inference
Is it possible to have constraint on static fields in Haxe? For example we may have classes which have static field instance of type of corresponding class. And we may want a function that will return an instance of class passed as parameter. This is my attempt:

```<code>class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T {
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        $type(a); //Test.hx:14: characters 14-15 : Warning : Unknown<0>
    }
}
</code>```

but it fails, because type parameter constraints are checked lazily. Any ideas on how do this?

答:
Have you considered using a typedef?

Heres a quick edit of your code showing the basic idea

```<code>typedef HasInstance = {
    var instance:Dynamic;
}

class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Bar {
    static public var instance = new Bar();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T:HasInstance>(t:T):T {
        trace(t);
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        trace(a);
        $type(a);
        var b = getInstance(Bar);
        trace(b);
        $type(b);
    }
}
</code>```

example on try haxe!

You would change the instance type within the typedef to be more appropriate for your needs, and you can also constrain typedefs too, which can be very useful

Body:
Is it possible to have constraint on static fields in Haxe? For example we may have classes which have static field instance of type of corresponding class. And we may want a function that will return an instance of class passed as parameter. This is my attempt:

class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T {
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        $type(a); //Test.hx:14: characters 14-15 : Warning : Unknown<0>
    }
}

but it fails, because type parameter constraints are checked lazily. Any ideas on how do this?

Body:
Have you considered using a typedef?

Heres a quick edit of your code showing the basic idea

typedef HasInstance = {
    var instance:Dynamic;
}

class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Bar {
    static public var instance = new Bar();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T:HasInstance>(t:T):T {
        trace(t);
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        trace(a);
        $type(a);
        var b = getInstance(Bar);
        trace(b);
        $type(b);
    }
}

example on try haxe!

You would change the instance type within the typedef to be more appropriate for your needs, and you can also constrain typedefs too, which can be very useful