问:
Jenkins Multibranch Pipeline: clean workspace / delete directory when build ends
we are using Jenkins multibranch (scripted) pipeline to run multiple builds, in parallel. Each one will create a new, uniquely named directory to checkout the code and run the test. Directories are uniquely named because they contain the branch name but also a random part like "JAA2A5HUZB7TRE4OTVXU7S...".

This means that after each build X directories (X = number of parallel jobs * number of branches) stay on the Jenkins node, filling disk space.

I wonder how I could automatically delete these directories.

A simplified version of my initial pipeline looks like this

// Initialize the matrix
def matrix = [
  'foo',
  'bar',
]

// Initialize empty tasks map
def tasks = [:]

// Job status
successful = true

// Fill our tasks map from the Matrix data
for (x in matrix) {

  def job_name = x

  tasks[job_name] = {
    node('libvirt') {
        // Checkout repository first
        stage("$job_name - Checkout") {
          checkout scm
        }

        // Then build the machine
        gitlabCommitStatus('build') {
            stage("$job_name - Build") {
                  sh "./bin/build.sh ${job_name}"
            }
        }
      }
    }
  }
}

//// Pipeline ////

notifyBuild('STARTED')

// Run tasks in parallel
try {
  parallel tasks
} catch(e) {
  throw e
} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
}

// Methods
def notifyBuild(String buildStatus = 'STARTED') {
   // used to send formatted e-mails
}
```

<p>I first added <code>deleteDir()</code> like this</p>

<pre class="lang-groovy prettyprint-override"><code>} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    deleteDir()
  }
}
</code>```

it raises an error and makes the build fail.

I then added a cleanWs() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    cleanWs()
  }
}
```

<p>The output is</p>

```Running on node in /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA
[Pipeline] {
[Pipeline] step
[WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
```

but the directory /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA still exists.

I'm looking for any solution to adapt this scripted pipeline (and for declarative pipeline if you know how) to be able to delete all directories created by the build.

答:
This doesn't directly answer your question (I personally use deleteDir() and for me it works) but as an alternative to save disk place you could consider discarding "old" builds in your multibranch pipeline:</p>

```<code>stage ('Remove old builds') {
    //keep 10 builds per branch
    properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
we are using Jenkins multibranch (scripted) pipeline to run multiple builds, in parallel. Each one will create a new, uniquely named directory to checkout the code and run the test. Directories are uniquely named because they contain the branch name but also a random part like "JAA2A5HUZB7TRE4OTVXU7S...".

This means that after each build X directories (X = number of parallel jobs * number of branches) stay on the Jenkins node, filling disk space.

I wonder how I could automatically delete these directories.

A simplified version of my initial pipeline looks like this

// Initialize the matrix
def matrix = [
  'foo',
  'bar',
]

// Initialize empty tasks map
def tasks = [:]

// Job status
successful = true

// Fill our tasks map from the Matrix data
for (x in matrix) {

  def job_name = x

  tasks[job_name] = {
    node('libvirt') {
        // Checkout repository first
        stage("$job_name - Checkout") {
          checkout scm
        }

        // Then build the machine
        gitlabCommitStatus('build') {
            stage("$job_name - Build") {
                  sh "./bin/build.sh ${job_name}"
            }
        }
      }
    }
  }
}

//// Pipeline ////

notifyBuild('STARTED')

// Run tasks in parallel
try {
  parallel tasks
} catch(e) {
  throw e
} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
}

// Methods
def notifyBuild(String buildStatus = 'STARTED') {
   // used to send formatted e-mails
}

I first added deleteDir() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    deleteDir()
  }
}

it raises an error and makes the build fail.

I then added a cleanWs() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    cleanWs()
  }
}

The output is

Running on node in /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA
[Pipeline] {
[Pipeline] step
[WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

but the directory /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA still exists.

I'm looking for any solution to adapt this scripted pipeline (and for declarative pipeline if you know how) to be able to delete all directories created by the build.

Body:
This doesn't directly answer your question (I personally use deleteDir() and for me it works) but as an alternative to save disk place you could consider discarding "old" builds in your multibranch pipeline:

stage ('Remove old builds') {
    //keep 10 builds per branch
    properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]);
}


来源: stackexchange

问:
Default ctor not generated when there's a template copy ctor
```<code>template<class T>
class MyClass {
 public:
  //MyClass() = default;

 template<class X>
 MyClass(MyClass<X>& other)
 {
  val = other.getVal();
 }

 T getVal()
 {
  return val;
 }

 private:
  T val;
};

main()
{
 MyClass<double> xd;       //this one causing the problem
 MyClass<double> xd1(xd);  //this one is fine

 MyClass<int> xi(xd);
}
</code>```

This code will not compile.
But if you uncomment MyClass() = default, then everything is fine.
As far as I remember the template ctor not preventing compiler from generating the default ctor and copy ctor as well.
And indeed the compiler complaining only when trying to create object through the default ctor, but not for copy construction (which in this case is compiler generated)
The code was compiled with g++ 5.4.0 and 7.1.0. Same behavior with both

答:
This is not a copy constructor:

```<code>template<class X>
MyClass(MyClass<X>& other) {
    val = other.getVal();
}
</code>```

This is a constructor taking a mutable lvalue reference to many different type than this class.

This is a copy constructor:

```<code>MyClass(const MyClass&) {
    // ...
}
</code>```

You can test if a function bus a special function by trying to put = default after it's signature. If the compiler complains about your misuse of defaulted functions, you function is not a special one.

When any other constructor than special constructors is added, the default constructor is not generated. That function being a template makes no different effect than a non template one. In that case, MyClass() = default is indeed required.

From cppreference:

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

On the contrary, if a user provided constructor is declared, no implicitly defined default constructor is defined.

And from [class.ctor]§5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

Since your class has a user provided constructor, no implicitly declared/defined constructor is generated. Again, you can always force it's generation with = default.

ContentLicense: CC BY-SA 3.0

Body:
template<class T>
class MyClass {
 public:
  //MyClass() = default;

 template<class X>
 MyClass(MyClass<X>& other)
 {
  val = other.getVal();
 }

 T getVal()
 {
  return val;
 }

 private:
  T val;
};

main()
{
 MyClass<double> xd;       //this one causing the problem
 MyClass<double> xd1(xd);  //this one is fine

 MyClass<int> xi(xd);
}

This code will not compile.
But if you uncomment MyClass() = default, then everything is fine.
As far as I remember the template ctor not preventing compiler from generating the default ctor and copy ctor as well.
And indeed the compiler complaining only when trying to create object through the default ctor, but not for copy construction (which in this case is compiler generated)
The code was compiled with g++ 5.4.0 and 7.1.0. Same behavior with both

Body:
This is not a copy constructor:

template<class X>
MyClass(MyClass<X>& other) {
    val = other.getVal();
}

This is a constructor taking a mutable lvalue reference to many different type than this class.

This is a copy constructor:

MyClass(const MyClass&) {
    // ...
}

You can test if a function bus a special function by trying to put = default after it's signature. If the compiler complains about your misuse of defaulted functions, you function is not a special one.

When any other constructor than special constructors is added, the default constructor is not generated. That function being a template makes no different effect than a non template one. In that case, MyClass() = default is indeed required.

From cppreference:

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

On the contrary, if a user provided constructor is declared, no implicitly defined default constructor is defined.

And from [class.ctor]§5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

Since your class has a user provided constructor, no implicitly declared/defined constructor is generated. Again, you can always force it's generation with = default.


问:
Rationale behind using namespace behavior
Quote from the standard:

A using-directive specifies that the names in the nominated namespace
  can be used in the scope in which the using-directive appears after
  the using-directive. During unqualified name lookup (3.4.1), the names
  appear as if they were declared in the nearest enclosing namespace
  which contains both the using-directive and the nominated namespace.

Look at this code:

```<code>namespace A {

    int fn() { return 1; }

}

namespace Inner {

    int fn() { return 2; }

    namespace B {

        using namespace A;

        int z = fn();

    }

}
</code>```

Here, before I knew the exact rules of namespaces, I had expected that z will be initialized to 1, as I written using namespace A, so expected that A::fn() will be used. But it is not the case, z will be initialized to 2, as Inner::fn() is called because of the rule I quoted.

What is the rationale behind this behavior: "as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace"?

What would be the cons, if using namespace worked as applying using declarations for everything in that namespace?

Note: this is the related issue that motivated me to ask this question.

答:
A desirable property of a namespace system is that of what I call incremental API compatibility. That is, if I add a symbol to a namespace, then any previously working program should keep working and mean the same thing.

Now, plain C++ with overloads is not incrementally API compatible:

```<code>int foo(long x) { return 1; }

int main()
{
    foo(0);
}
</code>```

Now I add the overload int foo(int x) { return 2; } and the program silently changes meaning.

Anyway, when C++ people designed the namespace system they wanted that when incrementing an external API, previously working code should not change the namespace from where the symbol is chosen. From your example, the previous working code would be something like:

```<code>namespace A {
    //no fn here, yet
}

namespace Inner {

    int fn() { return 2; }

    namespace B {

        using namespace A;
        int z = fn();
    }
}
</code>```

And z is easily initialized to 2. Now augmenting namespace A with a symbol named fn will not change the meaning of that working code.

The opposite case does not really apply:

```<code>namespace A {
    int fn() { return 1; }
}

namespace Inner {

    // no fn here

    namespace B {

        using namespace A;
        int z = fn();
    }
}
</code>```

Here z is initialized to 1. Of course, if I add fn to Inner it will change the meaning of the program, but Inner is not an external API: actually, when Inner was written initially, A::fn did already exist (it was being called!), so there is no excuse for being unaware of the clash.

A somewhat practical example

Imagine this C++98 program:

```<code>#include <iostream>

namespace A {
int move = 0;
void foo()
{
    using namespace std;
    cout << move << endl;
    return 0;
}
}

int main()
{
    A::foo();
    return 0;
}
</code>```

Now, if I compile this with C++11, everything works fine thanks to this using rule. If using namespace std worked as applying using declarations for everything in that namespace, then this program would try to print function std::move instead of  A::move.

Body:
Quote from the standard:

A using-directive specifies that the names in the nominated namespace
  can be used in the scope in which the using-directive appears after
  the using-directive. During unqualified name lookup (3.4.1), the names
  appear as if they were declared in the nearest enclosing namespace
  which contains both the using-directive and the nominated namespace.

Look at this code:

namespace A {

    int fn() { return 1; }

}

namespace Inner {

    int fn() { return 2; }

    namespace B {

        using namespace A;

        int z = fn();

    }

}

Here, before I knew the exact rules of namespaces, I had expected that z will be initialized to 1, as I written using namespace A, so expected that A::fn() will be used. But it is not the case, z will be initialized to 2, as Inner::fn() is called because of the rule I quoted.

What is the rationale behind this behavior: "as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace"?

What would be the cons, if using namespace worked as applying using declarations for everything in that namespace?

Note: this is the related issue that motivated me to ask this question.

Body:
A desirable property of a namespace system is that of what I call incremental API compatibility. That is, if I add a symbol to a namespace, then any previously working program should keep working and mean the same thing.

Now, plain C++ with overloads is not incrementally API compatible:

int foo(long x) { return 1; }

int main()
{
    foo(0);
}

Now I add the overload int foo(int x) { return 2; } and the program silently changes meaning.

Anyway, when C++ people designed the namespace system they wanted that when incrementing an external API, previously working code should not change the namespace from where the symbol is chosen. From your example, the previous working code would be something like:

namespace A {
    //no fn here, yet
}

namespace Inner {

    int fn() { return 2; }

    namespace B {

        using namespace A;
        int z = fn();
    }
}

And z is easily initialized to 2. Now augmenting namespace A with a symbol named fn will not change the meaning of that working code.

The opposite case does not really apply:

namespace A {
    int fn() { return 1; }
}

namespace Inner {

    // no fn here

    namespace B {

        using namespace A;
        int z = fn();
    }
}

Here z is initialized to 1. Of course, if I add fn to Inner it will change the meaning of the program, but Inner is not an external API: actually, when Inner was written initially, A::fn did already exist (it was being called!), so there is no excuse for being unaware of the clash.

A somewhat practical example

Imagine this C++98 program:

#include <iostream>

namespace A {
int move = 0;
void foo()
{
    using namespace std;
    cout << move << endl;
    return 0;
}
}

int main()
{
    A::foo();
    return 0;
}

Now, if I compile this with C++11, everything works fine thanks to this using rule. If using namespace std worked as applying using declarations for everything in that namespace, then this program would try to print function std::move instead of  A::move.


问:
How to maintain a constant ImageView width and and height
I have a recyclerView displaying a list of imageView(thumbnail size) and textView. Whenever i populate my textViews with lot of text, the imageView is shrinked and the height increases. The textView is also wrapped to the left  leaving lot of white space on the right. Below is an image of what i am talking about. How can i make the thumbnail width and height fixed even though my textView has a lot of texts, so as to maintain the image quality.

*axml**

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</android.support.v7.widget.CardView>
</code>```

答:
Use this

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                **android:layout_height="wrap_content"**
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_launcher"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                **android:layout_height="wrap_content"**
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Captionjkdhka asdgasidga sgdia g Caption vCaptionCaptionCaptionvCaptionCaption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</code>```

Issue was with height of your image view and layout

Body:
I have a recyclerView displaying a list of imageView(thumbnail size) and textView. Whenever i populate my textViews with lot of text, the imageView is shrinked and the height increases. The textView is also wrapped to the left  leaving lot of white space on the right. Below is an image of what i am talking about. How can i make the thumbnail width and height fixed even though my textView has a lot of texts, so as to maintain the image quality.

*axml**

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</android.support.v7.widget.CardView>

Body:
Use this

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                **android:layout_height="wrap_content"**
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_launcher"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                **android:layout_height="wrap_content"**
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Captionjkdhka asdgasidga sgdia g Caption vCaptionCaptionCaptionvCaptionCaption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

Issue was with height of your image view and layout


问:
Texture does not work
Hello I am trying to render texture on two triangles. glGetError() does not return any error. I can render colored rectangle, but texture does not work. Shaders are compiled without errors.  Why this code does not work? (Image)

```<code>class MainRenderer implements GLSurfaceView.Renderer {
    int vertexBuffer;
    int indexBuffer;
    int shaderProgram;
    int texture;

    @Override
    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        GLES20.glClearColor(1, 0, 0, 1);

        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        texture = textures[0];
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, BitmapFactory.decodeResource(MainActivity.MainActivityHandle.getResources(), R.drawable.pes), 0);

        float vertices[] = {
                1, 1,
                1, 0,
                0, 0,
                0, 1
        };
        int indices[] = {
                0, 1, 3,
                1, 2, 3
        };
        String vertexShaderCode = "attribute vec2 position;  vec2 texturePosition; void main(){texturePosition = position;gl_Position = vec4(position,0.0, 1.0);}";
        String fragmentShaderCode = "precision mediump float;uniform sampler2D texture; vec2 texturePosition; void main(){gl_FragColor = texture2D(texture, texturePosition);}";

        int vertexBuffers[] = new int[1];
        GLES20.glGenBuffers(1, vertexBuffers, 0);
        vertexBuffer = vertexBuffers[0];
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, 4 * 2 * 4, FloatBuffer.wrap(vertices), GLES20.GL_STATIC_DRAW);

        int indexBuffers[] = new int[1];
        GLES20.glGenBuffers(1, indexBuffers, 0);
        indexBuffer = indexBuffers[0];
        GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
        GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, 2 * 3 * 4, IntBuffer.wrap(indices), GLES20.GL_STATIC_DRAW);

        int vertexShader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
        GLES20.glShaderSource(vertexShader, vertexShaderCode);
        GLES20.glCompileShader(vertexShader);

        int fragmentShader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
        GLES20.glShaderSource(fragmentShader, fragmentShaderCode);
        GLES20.glCompileShader(fragmentShader);

        shaderProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(shaderProgram, vertexShader);
        GLES20.glAttachShader(shaderProgram, fragmentShader);
        GLES20.glLinkProgram(shaderProgram);
    }

    @Override
    public void onSurfaceChanged(GL10 unused, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 unused) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        GLES20.glUseProgram(shaderProgram);

        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer);
        GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);

        int positionAttributeHandle = GLES20.glGetAttribLocation(shaderProgram, "position");
        GLES20.glEnableVertexAttribArray(positionAttributeHandle);
        GLES20.glVertexAttribPointer(positionAttributeHandle, 2, GLES20.GL_FLOAT, false, 2*4, 0);

        GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

        GLES20.glDisableVertexAttribArray(positionAttributeHandle);
    }
}
</code>```

答: I can at least see that you are using (in vertex and fragment shaders) just 'vec2 texturePosition', while you should use a 'varying' for output from vertex shader to the fragment shader. Try adding 'varying' before 'vec2 ...' in shaders.</p>

Title: Texture does not work

Body:
Hello I am trying to render texture on two triangles. glGetError() does not return any error. I can render colored rectangle, but texture does not work. Shaders are compiled without errors.  Why this code does not work? (Image)

class MainRenderer implements GLSurfaceView.Renderer {
    int vertexBuffer;
    int indexBuffer;
    int shaderProgram;
    int texture;

    @Override
    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        GLES20.glClearColor(1, 0, 0, 1);

        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        texture = textures[0];
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, BitmapFactory.decodeResource(MainActivity.MainActivityHandle.getResources(), R.drawable.pes), 0);

        float vertices[] = {
                1, 1,
                1, 0,
                0, 0,
                0, 1
        };
        int indices[] = {
                0, 1, 3,
                1, 2, 3
        };
        String vertexShaderCode = "attribute vec2 position;  vec2 texturePosition; void main(){texturePosition = position;gl_Position = vec4(position,0.0, 1.0);}";
        String fragmentShaderCode = "precision mediump float;uniform sampler2D texture; vec2 texturePosition; void main(){gl_FragColor = texture2D(texture, texturePosition);}";

        int vertexBuffers[] = new int[1];
        GLES20.glGenBuffers(1, vertexBuffers, 0);
        vertexBuffer = vertexBuffers[0];
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, 4 * 2 * 4, FloatBuffer.wrap(vertices), GLES20.GL_STATIC_DRAW);

        int indexBuffers[] = new int[1];
        GLES20.glGenBuffers(1, indexBuffers, 0);
        indexBuffer = indexBuffers[0];
        GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
        GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, 2 * 3 * 4, IntBuffer.wrap(indices), GLES20.GL_STATIC_DRAW);

        int vertexShader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
        GLES20.glShaderSource(vertexShader, vertexShaderCode);
        GLES20.glCompileShader(vertexShader);

        int fragmentShader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
        GLES20.glShaderSource(fragmentShader, fragmentShaderCode);
        GLES20.glCompileShader(fragmentShader);

        shaderProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(shaderProgram, vertexShader);
        GLES20.glAttachShader(shaderProgram, fragmentShader);
        GLES20.glLinkProgram(shaderProgram);
    }

    @Override
    public void onSurfaceChanged(GL10 unused, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 unused) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        GLES20.glUseProgram(shaderProgram);

        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer);
        GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);

        int positionAttributeHandle = GLES20.glGetAttribLocation(shaderProgram, "position");
        GLES20.glEnableVertexAttribArray(positionAttributeHandle);
        GLES20.glVertexAttribPointer(positionAttributeHandle, 2, GLES20.GL_FLOAT, false, 2*4, 0);

        GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

        GLES20.glDisableVertexAttribArray(positionAttributeHandle);
    }
}


问:
SelectIndexChanged not working (C# desktop)
**The autopostback-fix does not work! **

I have a GUI that looks like:

I want to show the details of a cat when it's clicked on.

I used this code for it:

```<code>private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
</code>```

When running however, nothing seems to work. What am I doing wrong?

EDIT

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Data.SqlClient;

using IntegrationTool;

namespace IntegrationTool
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=CatShelter;Integrated Security=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[cats]", conn);
            SqlDataReader reader = cmd.ExecuteReader();

            List<Cat> cats = new List<Cat>();

            while (reader.Read())
            {
                Cat c = new Cat();
                c.ID = (int)reader["CatID"];
                c.Name = (string)reader["Name"];
                c.DateArrived = (DateTime)reader["DateArrived"];
                c.IsAdopted = (string)reader["IsAdopted"];
                c.AdoptedBy = (string)reader["AdoptedBy"];

                cats.Add(c);
            }

            foreach (Cat c in cats)
            {
                Console.WriteLine(c.Name);
            }

            reader.Close();
            conn.Close();

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }

            listBox_Cats.DataSource = cats;
            listBox_Cats.DisplayMember = "Name";
            listBox_Cats.ValueMember = "ID";

        }

        private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                Console.WriteLine(cat.Name);
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
   }
}

namespace IntegrationTool
</code>```

{

```<code>  partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.listBox_Cats = new System.Windows.Forms.ListBox();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.groupBox2 = new System.Windows.Forms.GroupBox();
        this.button2 = new System.Windows.Forms.Button();
        this.cb_VetCheck = new System.Windows.Forms.CheckBox();
        this.label5 = new System.Windows.Forms.Label();
        this.tb_Comment = new System.Windows.Forms.TextBox();
        this.tb_ID = new System.Windows.Forms.TextBox();
        this.tb_DateArrived = new System.Windows.Forms.TextBox();
        this.tb_IsAdopted = new System.Windows.Forms.TextBox();
        this.tb_adoptedBy = new System.Windows.Forms.TextBox();
        this.groupBox3 = new System.Windows.Forms.GroupBox();
        this.label6 = new System.Windows.Forms.Label();
        this.tb_Name = new System.Windows.Forms.TextBox();
        this.groupBox1.SuspendLayout();
        this.groupBox2.SuspendLayout();
        this.groupBox3.SuspendLayout();
        this.SuspendLayout();
        //
        // listBox_Cats
        //
        this.listBox_Cats.FormattingEnabled = true;
        this.listBox_Cats.Location = new System.Drawing.Point(16, 35);
        this.listBox_Cats.Name = "listBox_Cats";
        this.listBox_Cats.Size = new System.Drawing.Size(137, 316);
        this.listBox_Cats.TabIndex = 0;
        //
        // groupBox1
        //
        this.groupBox1.Controls.Add(this.tb_Name);
        this.groupBox1.Controls.Add(this.label6);
        this.groupBox1.Controls.Add(this.tb_adoptedBy);
        this.groupBox1.Controls.Add(this.tb_IsAdopted);
        this.groupBox1.Controls.Add(this.tb_DateArrived);
        this.groupBox1.Controls.Add(this.tb_ID);
        this.groupBox1.Controls.Add(this.label4);
        this.groupBox1.Controls.Add(this.label3);
        this.groupBox1.Controls.Add(this.label2);
        this.groupBox1.Controls.Add(this.label1);
        this.groupBox1.Location = new System.Drawing.Point(252, 31);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(409, 190);
        this.groupBox1.TabIndex = 1;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Details";
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 35);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(24, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = "ID: ";
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(6, 95);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(69, 13);
        this.label2.TabIndex = 1;
        this.label2.Text = "Date Arrived:";
        //
        // label3
        //
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(6, 123);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(60, 13);
        this.label3.TabIndex = 2;
        this.label3.Text = "Is adopted:";
        //
        // label4
        //
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(6, 157);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(65, 13);
        this.label4.TabIndex = 3;
        this.label4.Text = "Adopted By:";
        //
        // groupBox2
        //
        this.groupBox2.Controls.Add(this.tb_Comment);
        this.groupBox2.Controls.Add(this.label5);
        this.groupBox2.Controls.Add(this.cb_VetCheck);
        this.groupBox2.Location = new System.Drawing.Point(252, 243);
        this.groupBox2.Name = "groupBox2";
        this.groupBox2.Size = new System.Drawing.Size(409, 157);
        this.groupBox2.TabIndex = 2;
        this.groupBox2.TabStop = false;
        this.groupBox2.Text = "Validate";
        //
        // button2
        //
        this.button2.Location = new System.Drawing.Point(553, 424);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(107, 31);
        this.button2.TabIndex = 4;
        this.button2.Text = "Save";
        this.button2.UseVisualStyleBackColor = true;
        //
        // cb_VetCheck
        //
        this.cb_VetCheck.AutoSize = true;
        this.cb_VetCheck.Location = new System.Drawing.Point(9, 30);
        this.cb_VetCheck.Name = "cb_VetCheck";
        this.cb_VetCheck.Size = new System.Drawing.Size(76, 17);
        this.cb_VetCheck.TabIndex = 0;
        this.cb_VetCheck.Text = "Vet Check";
        this.cb_VetCheck.UseVisualStyleBackColor = true;
        //
        // label5
        //
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(6, 75);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(51, 13);
        this.label5.TabIndex = 1;
        this.label5.Text = "Comment";
        //
        // tb_Comment
        //
        this.tb_Comment.Location = new System.Drawing.Point(9, 91);
        this.tb_Comment.Name = "tb_Comment";
        this.tb_Comment.Size = new System.Drawing.Size(288, 20);
        this.tb_Comment.TabIndex = 2;
        //
        // tb_ID
        //
        this.tb_ID.Location = new System.Drawing.Point(81, 35);
        this.tb_ID.Name = "tb_ID";
        this.tb_ID.ReadOnly = true;
        this.tb_ID.Size = new System.Drawing.Size(66, 20);
        this.tb_ID.TabIndex = 4;
        //
        // tb_DateArrived
        //
        this.tb_DateArrived.Location = new System.Drawing.Point(81, 92);
        this.tb_DateArrived.Name = "tb_DateArrived";
        this.tb_DateArrived.ReadOnly = true;
        this.tb_DateArrived.Size = new System.Drawing.Size(66, 20);
        this.tb_DateArrived.TabIndex = 5;
        //
        // tb_IsAdopted
        //
        this.tb_IsAdopted.Location = new System.Drawing.Point(81, 120);
        this.tb_IsAdopted.Name = "tb_IsAdopted";
        this.tb_IsAdopted.ReadOnly = true;
        this.tb_IsAdopted.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        this.tb_IsAdopted.Size = new System.Drawing.Size(66, 20);
        this.tb_IsAdopted.TabIndex = 6;
        //
        // tb_adoptedBy
        //
        this.tb_adoptedBy.Location = new System.Drawing.Point(81, 154);
        this.tb_adoptedBy.Name = "tb_adoptedBy";
        this.tb_adoptedBy.ReadOnly = true;
        this.tb_adoptedBy.Size = new System.Drawing.Size(66, 20);
        this.tb_adoptedBy.TabIndex = 7;
        //
        // groupBox3
        //
        this.groupBox3.Controls.Add(this.listBox_Cats);
        this.groupBox3.Location = new System.Drawing.Point(12, 31);
        this.groupBox3.Name = "groupBox3";
        this.groupBox3.Size = new System.Drawing.Size(175, 369);
        this.groupBox3.TabIndex = 5;
        this.groupBox3.TabStop = false;
        this.groupBox3.Text = "Cats";
        //
        // label6
        //
        this.label6.AutoSize = true;
        this.label6.Location = new System.Drawing.Point(7, 61);
        this.label6.Name = "label6";
        this.label6.Size = new System.Drawing.Size(41, 13);
        this.label6.TabIndex = 8;
        this.label6.Text = "Name: ";
        //
        // tb_Name
        //
        this.tb_Name.Location = new System.Drawing.Point(81, 61);
        this.tb_Name.Name = "tb_Name";
        this.tb_Name.ReadOnly = true;
        this.tb_Name.Size = new System.Drawing.Size(66, 20);
        this.tb_Name.TabIndex = 9;
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(721, 480);
        this.Controls.Add(this.groupBox3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.groupBox2);
        this.Controls.Add(this.groupBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.groupBox2.ResumeLayout(false);
        this.groupBox2.PerformLayout();
        this.groupBox3.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox_Cats;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox tb_adoptedBy;
    private System.Windows.Forms.TextBox tb_IsAdopted;
    private System.Windows.Forms.TextBox tb_DateArrived;
    private System.Windows.Forms.TextBox tb_ID;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.GroupBox groupBox2;
    private System.Windows.Forms.TextBox tb_Comment;
    private System.Windows.Forms.Label label5;
    private System.Windows.Forms.CheckBox cb_VetCheck;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.GroupBox groupBox3;
    private System.Windows.Forms.TextBox tb_Name;
    private System.Windows.Forms.Label label6;
}
</code>```

}

答:
Your listBox_Cats_SelectedIndexChanged is not bound to the SelectedIndexChanged event of the listBox.

There should be entry in your designer file that looks like:

```<code>this.listBox_Cats.SelectedIndexChanged += new System.EventHandler(this.listBox_Cats_SelectedIndexChanged);
</code>```

You can add it manually if it isn't already there - in InitializeComponent.

Body:
**The autopostback-fix does not work! **

I have a GUI that looks like:

I want to show the details of a cat when it's clicked on.

I used this code for it:

private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }

When running however, nothing seems to work. What am I doing wrong?

EDIT

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Data.SqlClient;

using IntegrationTool;

namespace IntegrationTool
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=CatShelter;Integrated Security=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[cats]", conn);
            SqlDataReader reader = cmd.ExecuteReader();

            List<Cat> cats = new List<Cat>();

            while (reader.Read())
            {
                Cat c = new Cat();
                c.ID = (int)reader["CatID"];
                c.Name = (string)reader["Name"];
                c.DateArrived = (DateTime)reader["DateArrived"];
                c.IsAdopted = (string)reader["IsAdopted"];
                c.AdoptedBy = (string)reader["AdoptedBy"];

                cats.Add(c);
            }

            foreach (Cat c in cats)
            {
                Console.WriteLine(c.Name);
            }

            reader.Close();
            conn.Close();

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }

            listBox_Cats.DataSource = cats;
            listBox_Cats.DisplayMember = "Name";
            listBox_Cats.ValueMember = "ID";

        }

        private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                Console.WriteLine(cat.Name);
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
   }
}

namespace IntegrationTool

{

  partial class Form1
    {
        ///
        /// Required designer variable.
        ///
        private System.ComponentModel.IContainer components = null;

    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        this.listBox_Cats = new System.Windows.Forms.ListBox();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.groupBox2 = new System.Windows.Forms.GroupBox();
        this.button2 = new System.Windows.Forms.Button();
        this.cb_VetCheck = new System.Windows.Forms.CheckBox();
        this.label5 = new System.Windows.Forms.Label();
        this.tb_Comment = new System.Windows.Forms.TextBox();
        this.tb_ID = new System.Windows.Forms.TextBox();
        this.tb_DateArrived = new System.Windows.Forms.TextBox();
        this.tb_IsAdopted = new System.Windows.Forms.TextBox();
        this.tb_adoptedBy = new System.Windows.Forms.TextBox();
        this.groupBox3 = new System.Windows.Forms.GroupBox();
        this.label6 = new System.Windows.Forms.Label();
        this.tb_Name = new System.Windows.Forms.TextBox();
        this.groupBox1.SuspendLayout();
        this.groupBox2.SuspendLayout();
        this.groupBox3.SuspendLayout();
        this.SuspendLayout();
        //
        // listBox_Cats
        //
        this.listBox_Cats.FormattingEnabled = true;
        this.listBox_Cats.Location = new System.Drawing.Point(16, 35);
        this.listBox_Cats.Name = "listBox_Cats";
        this.listBox_Cats.Size = new System.Drawing.Size(137, 316);
        this.listBox_Cats.TabIndex = 0;
        //
        // groupBox1
        //
        this.groupBox1.Controls.Add(this.tb_Name);
        this.groupBox1.Controls.Add(this.label6);
        this.groupBox1.Controls.Add(this.tb_adoptedBy);
        this.groupBox1.Controls.Add(this.tb_IsAdopted);
        this.groupBox1.Controls.Add(this.tb_DateArrived);
        this.groupBox1.Controls.Add(this.tb_ID);
        this.groupBox1.Controls.Add(this.label4);
        this.groupBox1.Controls.Add(this.label3);
        this.groupBox1.Controls.Add(this.label2);
        this.groupBox1.Controls.Add(this.label1);
        this.groupBox1.Location = new System.Drawing.Point(252, 31);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(409, 190);
        this.groupBox1.TabIndex = 1;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Details";
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 35);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(24, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = "ID: ";
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(6, 95);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(69, 13);
        this.label2.TabIndex = 1;
        this.label2.Text = "Date Arrived:";
        //
        // label3
        //
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(6, 123);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(60, 13);
        this.label3.TabIndex = 2;
        this.label3.Text = "Is adopted:";
        //
        // label4
        //
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(6, 157);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(65, 13);
        this.label4.TabIndex = 3;
        this.label4.Text = "Adopted By:";
        //
        // groupBox2
        //
        this.groupBox2.Controls.Add(this.tb_Comment);
        this.groupBox2.Controls.Add(this.label5);
        this.groupBox2.Controls.Add(this.cb_VetCheck);
        this.groupBox2.Location = new System.Drawing.Point(252, 243);
        this.groupBox2.Name = "groupBox2";
        this.groupBox2.Size = new System.Drawing.Size(409, 157);
        this.groupBox2.TabIndex = 2;
        this.groupBox2.TabStop = false;
        this.groupBox2.Text = "Validate";
        //
        // button2
        //
        this.button2.Location = new System.Drawing.Point(553, 424);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(107, 31);
        this.button2.TabIndex = 4;
        this.button2.Text = "Save";
        this.button2.UseVisualStyleBackColor = true;
        //
        // cb_VetCheck
        //
        this.cb_VetCheck.AutoSize = true;
        this.cb_VetCheck.Location = new System.Drawing.Point(9, 30);
        this.cb_VetCheck.Name = "cb_VetCheck";
        this.cb_VetCheck.Size = new System.Drawing.Size(76, 17);
        this.cb_VetCheck.TabIndex = 0;
        this.cb_VetCheck.Text = "Vet Check";
        this.cb_VetCheck.UseVisualStyleBackColor = true;
        //
        // label5
        //
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(6, 75);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(51, 13);
        this.label5.TabIndex = 1;
        this.label5.Text = "Comment";
        //
        // tb_Comment
        //
        this.tb_Comment.Location = new System.Drawing.Point(9, 91);
        this.tb_Comment.Name = "tb_Comment";
        this.tb_Comment.Size = new System.Drawing.Size(288, 20);
        this.tb_Comment.TabIndex = 2;
        //
        // tb_ID
        //
        this.tb_ID.Location = new System.Drawing.Point(81, 35);
        this.tb_ID.Name = "tb_ID";
        this.tb_ID.ReadOnly = true;
        this.tb_ID.Size = new System.Drawing.Size(66, 20);
        this.tb_ID.TabIndex = 4;
        //
        // tb_DateArrived
        //
        this.tb_DateArrived.Location = new System.Drawing.Point(81, 92);
        this.tb_DateArrived.Name = "tb_DateArrived";
        this.tb_DateArrived.ReadOnly = true;
        this.tb_DateArrived.Size = new System.Drawing.Size(66, 20);
        this.tb_DateArrived.TabIndex = 5;
        //
        // tb_IsAdopted
        //
        this.tb_IsAdopted.Location = new System.Drawing.Point(81, 120);
        this.tb_IsAdopted.Name = "tb_IsAdopted";
        this.tb_IsAdopted.ReadOnly = true;
        this.tb_IsAdopted.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        this.tb_IsAdopted.Size = new System.Drawing.Size(66, 20);
        this.tb_IsAdopted.TabIndex = 6;
        //
        // tb_adoptedBy
        //
        this.tb_adoptedBy.Location = new System.Drawing.Point(81, 154);
        this.tb_adoptedBy.Name = "tb_adoptedBy";
        this.tb_adoptedBy.ReadOnly = true;
        this.tb_adoptedBy.Size = new System.Drawing.Size(66, 20);
        this.tb_adoptedBy.TabIndex = 7;
        //
        // groupBox3
        //
        this.groupBox3.Controls.Add(this.listBox_Cats);
        this.groupBox3.Location = new System.Drawing.Point(12, 31);
        this.groupBox3.Name = "groupBox3";
        this.groupBox3.Size = new System.Drawing.Size(175, 369);
        this.groupBox3.TabIndex = 5;
        this.groupBox3.TabStop = false;
        this.groupBox3.Text = "Cats";
        //
        // label6
        //
        this.label6.AutoSize = true;
        this.label6.Location = new System.Drawing.Point(7, 61);
        this.label6.Name = "label6";
        this.label6.Size = new System.Drawing.Size(41, 13);
        this.label6.TabIndex = 8;
        this.label6.Text = "Name: ";
        //
        // tb_Name
        //
        this.tb_Name.Location = new System.Drawing.Point(81, 61);
        this.tb_Name.Name = "tb_Name";
        this.tb_Name.ReadOnly = true;
        this.tb_Name.Size = new System.Drawing.Size(66, 20);
        this.tb_Name.TabIndex = 9;
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(721, 480);
        this.Controls.Add(this.groupBox3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.groupBox2);
        this.Controls.Add(this.groupBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.groupBox2.ResumeLayout(false);
        this.groupBox2.PerformLayout();
        this.groupBox3.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox_Cats;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox tb_adoptedBy;
    private System.Windows.Forms.TextBox tb_IsAdopted;
    private System.Windows.Forms.TextBox tb_DateArrived;
    private System.Windows.Forms.TextBox tb_ID;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.GroupBox groupBox2;
    private System.Windows.Forms.TextBox tb_Comment;
    private System.Windows.Forms.Label label5;
    private System.Windows.Forms.CheckBox cb_VetCheck;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.GroupBox groupBox3;
    private System.Windows.Forms.TextBox tb_Name;
    private System.Windows.Forms.Label label6;
}

}

Body:
Your listBox_Cats_SelectedIndexChanged is not bound to the SelectedIndexChanged event of the listBox.

There should be entry in your designer file that looks like:

this.listBox_Cats.SelectedIndexChanged += new System.EventHandler(this.listBox_Cats_SelectedIndexChanged);

You can add it manually if it isn't already there - in InitializeComponent.


问:
Yii2 - Validate AccessControl over IP
I would like to restrict access to a controller to only one IP (or an IP list).

What is the right way to configure?
(Example, I would like only IP 172.19.37.175 to have access to index.php?r=painel/restrict).

I tried this way:

```<code>public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::classname(),
            'only'  => ['index'],
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['?'],
                    'ips' => ['172.19.37.175'],
                ],
            ],
            'denyCallback' => function ($rule, $action) {
            throw new \Exception('You are not allowed to access this page');
                    }
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
    ];
}
</code>```

Title: Yii2 - Validate AccessControl over IP

Body:
I would like to restrict access to a controller to only one IP (or an IP list).

What is the right way to configure?
(Example, I would like only IP 172.19.37.175 to have access to index.php?r=painel/restrict).

I tried this way:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::classname(),
            'only'  => ['index'],
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['?'],
                    'ips' => ['172.19.37.175'],
                ],
            ],
            'denyCallback' => function ($rule, $action) {
            throw new \Exception('You are not allowed to access this page');
                    }
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
    ];
}

Body:
change

'roles' => ['?']

to

'roles' => ['@']


问:
Error establishing database connection in WordPress install
I am working with a managed server from 1&1 and I am trying to manually install WordPress with no luck. I went and downloaded the WP core files, uploaded them via FTP and then went into mySQL and created the database and username/password etc. and assigned the privileges. When I try to install wordpress via "www.example.com/wp-admin/install.php", I continuously receive the error:

Error establishing a database connection

I tried everything and triple checked my user,password, etc.

Here is my credentials (Password is hidden):

答:
```<code>// ** MySQL settings ** //
/** The name of the database for WordPress */
define('DB_NAME', 'yourdb');

/** MySQL database username */
define('DB_USER', 'yourdb user');

/** MySQL database password */
define('DB_PASSWORD', 'yourpassword');

/** MySQL hostname */
define('DB_HOST', 'hostname');
</code>```

<p>Host name is always a localhost. for check your database credential  is correct or not please feel a wrong value @ let me know I am here </p>

Body:
// ** MySQL settings ** //
/** The name of the database for WordPress */
define('DB_NAME', 'yourdb');

/** MySQL database username */
define('DB_USER', 'yourdb user');

/** MySQL database password */
define('DB_PASSWORD', 'yourpassword');

/** MySQL hostname */
define('DB_HOST', 'hostname');

Host name is always a localhost. for check your database credential  is correct or not please feel a wrong value @ let me know I am here


问:
Knockout viewmodel passed to action coming empty
I have a controller action where I'm trying to post a model from knockout:

```<code>    [HttpPost]
    public void AddItems(MyViewModel model)
    {
        [...]
    }
</code>```

knockout action:

```<code>self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    var model = ko.toJSON(self);
    $.post(url,
            model,
            function (result) {

            })
        .success(function () { console.log("AddItems second success"); })
        .error(function () { console.log("AddItems error"); })
        .complete(function () { console.log("AddItems complete"); });

    // this doesn't work either
    //var model2 = ko.toJSON({ model: self });
    //$.ajax(url, {
    //    data: model,
    //    type: "post",
    //    async: false,
    //    contentType: "application/json",
    //    success: function (data) {
    //        console.log("AddItems second success");
    //    },
    //    error: function (xmlHttpRequest, textStatus, errorThrown) {
    //        console.log("AddItems error");
    //    }
    //});
}
</code>```

I have commented out another post action which I tried as well - this one doesn't reach the controller action at all returning a 500 error in js console.

The model:

```<code>public class MyViewModel
{
    public int Id { get; set; }

    public string Ref { get; set; }

    public List<ItemViewModel> Items { get; set; }

    public decimal PriceTotal { get; set; }
}
</code>```

The model which gets posted to action has the correct structure but all properties are either empty or null.

How to pass a knockout viewmodel to the action with correct object data?

***** EDIT *****

I think the action doesn't get the json model.

Because when I pass a hand written raw object model:

```<code>var model4 = {
  "Ref": "sgsgsasg",
  "Id": 1,
  "PriceTotal": 382
}
</code>```

it gets to the action nicely and with correct values.

While the knockout passes json and then the action cannot convert it to the mvc model.

答:
You haven't passed the parameter your url is expecting, hence the 500.

```<code>self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    $.ajax(url , {
       type: "POST",
       cache: false,
       data: { model: ko.toJSON(self) }
    }).done(function () {
       console.log("AddItems second success");
    }).fail(function (jqXHR, textStatus, errorThrown) {
       console.log("AddItems complete");
    });
}
</code>```

Controller

```<code>[HttpPost]
public void AddItems(string model)
{
    var audit = InsertAudit();
    try
    {
        MyViewModel data = JsonConvert.DeserializeObject<MyViewModel>(model);
        //Logic here
    }
    catch (Exception ex)
    {
         FailAudit(audit.ID, ex.ToString());
    }
}
</code>```

Body:
I have a controller action where I'm trying to post a model from knockout:

    [HttpPost]
    public void AddItems(MyViewModel model)
    {
        [...]
    }

knockout action:

self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    var model = ko.toJSON(self);
    $.post(url,
            model,
            function (result) {

            })
        .success(function () { console.log("AddItems second success"); })
        .error(function () { console.log("AddItems error"); })
        .complete(function () { console.log("AddItems complete"); });

    // this doesn't work either
    //var model2 = ko.toJSON({ model: self });
    //$.ajax(url, {
    //    data: model,
    //    type: "post",
    //    async: false,
    //    contentType: "application/json",
    //    success: function (data) {
    //        console.log("AddItems second success");
    //    },
    //    error: function (xmlHttpRequest, textStatus, errorThrown) {
    //        console.log("AddItems error");
    //    }
    //});
}

I have commented out another post action which I tried as well - this one doesn't reach the controller action at all returning a 500 error in js console.

The model:

public class MyViewModel
{
    public int Id { get; set; }

    public string Ref { get; set; }

    public List<ItemViewModel> Items { get; set; }

    public decimal PriceTotal { get; set; }
}

The model which gets posted to action has the correct structure but all properties are either empty or null.

How to pass a knockout viewmodel to the action with correct object data?

***** EDIT *****

I think the action doesn't get the json model.

Because when I pass a hand written raw object model:

var model4 = {
  "Ref": "sgsgsasg",
  "Id": 1,
  "PriceTotal": 382
}

it gets to the action nicely and with correct values.

While the knockout passes json and then the action cannot convert it to the mvc model.

Body:
You haven't passed the parameter your url is expecting, hence the 500.

self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    $.ajax(url , {
       type: "POST",
       cache: false,
       data: { model: ko.toJSON(self) }
    }).done(function () {
       console.log("AddItems second success");
    }).fail(function (jqXHR, textStatus, errorThrown) {
       console.log("AddItems complete");
    });
}

Controller

[HttpPost]
public void AddItems(string model)
{
    var audit = InsertAudit();
    try
    {
        MyViewModel data = JsonConvert.DeserializeObject<MyViewModel>(model);
        //Logic here
    }
    catch (Exception ex)
    {
         FailAudit(audit.ID, ex.ToString());
    }
}


问:
Import doc and docx files in .Net and C#
I'm writing a text editor and I want to add the possibility to import .doc and .docx files. I know that I could use OLE Automation, but if I use a recent OLE library, it won't work with those people with an older version of Word, and if instead I use an older version, it won't be able to read .docx files.
Any ideas?
Thanks

EDIT: Another solution would be that, like my application works with HTML and RTF, convert .doc and .docx files with command line to one of these formats, something like this: http://www.snee.com/bobdc.blog/ 2007/09/using-word-for-command-line-co.html

答:
Why don't you use the Office Primary Interop Assemblies (PIAs)?

I think you will have to decide which versions of Word you want to support. I suggest you settle on Word 2003 as the lowest. That will allow you to use the Office 2003 PIAs and program against them. Installing PIAs in a machine installs binding redirects as well, so they work with newer versions on Word. There should be no problem in opening .docx files with Word 2007 or 2010 through Office 2003 PIAs, although I haven't tried this myself.

ContentLicense: CC BY-SA 2.5


问:
Creating sub-commands with the same name in Go w/ Cobra
I'm very new to Go in general, and this is my first project in Cobra.

It seems easy enough to create commands in Cobra with the command-line tool:

cobra add <command>

And adding sub-commands seems easy enough as well.

cobra add <subcommand> -p '<command>'

Where I've run into an issue is having two sub-commands for two different commands, but having the sub-commands have the same name. For instance:

I may have a command named 'people' and a command named 'places'.

cobra add people

cobra add places

Each command needs its own sub-command called 'add'.

cobra add add -p 'people'

cobra add add -p 'places'

The second command will fail because it will attempt to create an 'add.go' file which was already created by the first command. Is it possible to add sub-commands of the same name to different parent commands? Where the end result would be something like:

people add --first "bob" --last "smith"

places add "someplace" --zip "12345"

答: All command add does is generate a Go source file for you. You could write the file yourself; or you could take the first one that was created, rename it, then create the next one. You'll also likely have to rename some global variables/functions in the generated files to avoid name collisions.


问:
access parent project OTHER_SWIFT_FLAGS from pod
Building a custom pod for a private framework, in my main project i use custom OTHER_SWIFT_FLAGS.

In theory it should be possible to override the settings of the pod during the install based on the main project but there is no documentation on how to do so.

So far my attempts failed, any hint?
Looks like project(https://guides.cocoapods.org/syntax/podfile.html#project) should be the way to go but again, no documentation.

答:
So basically it looks like this.
Accessing the xcode project, then accessing the pod and looping through each config to set the proper value.</p>

```<code>post_install do |installer|
require 'xcodeproj'
project_path = 'pathTo/myProj.xcodeproj' # path to your xcode project
project = Xcodeproj::Project.open(project_path)
project.targets.each do |target|
    if target.name == 'myTarget' # name of the target in your main project containing the custom flag
        installer.pods_project.targets.each do |podTarget|
            if podTarget.name == 'myPod' #name of your pod
                target.build_configurations.each do |targetConfig|
                    podTarget.build_configurations.each do |podConfig|
                        podConfig.build_settings["OTHER_SWIFT_FLAGS"] = targetConfig.build_settings["OTHER_SWIFT_FLAGS"]
                    end
                end

            end
        end
    end
end
</code>```

Body:
So basically it looks like this.
Accessing the xcode project, then accessing the pod and looping through each config to set the proper value.

post_install do |installer|
require 'xcodeproj'
project_path = 'pathTo/myProj.xcodeproj' # path to your xcode project
project = Xcodeproj::Project.open(project_path)
project.targets.each do |target|
    if target.name == 'myTarget' # name of the target in your main project containing the custom flag
        installer.pods_project.targets.each do |podTarget|
            if podTarget.name == 'myPod' #name of your pod
                target.build_configurations.each do |targetConfig|
                    podTarget.build_configurations.each do |podConfig|
                        podConfig.build_settings["OTHER_SWIFT_FLAGS"] = targetConfig.build_settings["OTHER_SWIFT_FLAGS"]
                    end
                end

            end
        end
    end
end


问:
django.db.utils.IntegrityError: null value in column - but value is not null
I am using Django Rest Framework and in my serialiazers.py

```<code>class MeetingSerializer(serializers.ModelSerializer):
    meeting_organiser = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Meeting
        fields = '__all__'
</code>```

The Meeting model in my models.py is like:

```<code>class Meeting(models.Model):
    [some fields here...]
    meeting_organiser = models.ForeignKey(User, default=1)
    [more fields here...]
</code>```

However, when I try to do a save() to the Meeting model I get this error:

```<code>django.db.utils.IntegrityError: null value in column "meeting_organiser" violates not-null constraint
</code>```

I tried to debug and added in the serializers.py:

```<code>def save(self):
    print(self.validated_data)
</code>```

and in models.py:

```<code>def save(self, *args, **kwargs):
    print(self.meeting_organiser.username)
</code>```

In both cases, the meeting organiser object was not null and it contained the right values.

答:
You need to add a permission such as IsAuthenticated to make sure the request is authenticated.

Otherwise, you'll get a AnonymousUser which translates to None and I assume that as this parameter is explicitly given, the model's default doesn't apply.

Body:
I am using Django Rest Framework and in my serialiazers.py

class MeetingSerializer(serializers.ModelSerializer):
    meeting_organiser = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Meeting
        fields = '__all__'

The Meeting model in my models.py is like:

class Meeting(models.Model):
    [some fields here...]
    meeting_organiser = models.ForeignKey(User, default=1)
    [more fields here...]

However, when I try to do a save() to the Meeting model I get this error:

django.db.utils.IntegrityError: null value in column "meeting_organiser" violates not-null constraint

I tried to debug and added in the serializers.py:

def save(self):
    print(self.validated_data)

and in models.py:

def save(self, *args, **kwargs):
    print(self.meeting_organiser.username)

In both cases, the meeting organiser object was not null and it contained the right values.


问:
Get Black and White 2 BIT image using Emgu CV
Hi have a image which I need to convert into black and white and in 2 bit depth.

I tried following and it generates an image with 8 bit. Don't see any option to generate image of 2 bit.

```<code>Emgu.CV.Image<Gray, Single> image = new Emgu.CV.Image<Gray, Single>("test.jpg");
</code>```

Can someone please advise?

答:
In emgucv you have the following image Depth

Byte, SByte, Single (float), Double, UInt16, Int16, Int32 (int)
(from emgucv)

You do not have an 2 bit depth.
But you can make an images that looks like an 2 bit image like this:

```<code>var theImage = new Image<Gray, byte>(@"d:\temp\lena.jpg");
        for (int i = theImage.Rows - 1; i >= 0; i--)
        {
            for (int j = theImage.Cols - 1; j >= 0; j--)
            {
                if(theImage.Data[i,j,0]>byte.MaxValue/2)
                {
                        theImage.Data[i, j, 0] = byte.MaxValue;
                }
                else
                {
                    theImage.Data[i, j, 0] = 0;
                }

            }
        }
</code>```

Body:
Hi have a image which I need to convert into black and white and in 2 bit depth.

I tried following and it generates an image with 8 bit. Don't see any option to generate image of 2 bit.

Emgu.CV.Image<Gray, Single> image = new Emgu.CV.Image<Gray, Single>("test.jpg");

Can someone please advise?

Body:
In emgucv you have the following image Depth

Byte, SByte, Single (float), Double, UInt16, Int16, Int32 (int)
(from emgucv)

You do not have an 2 bit depth.
But you can make an images that looks like an 2 bit image like this:

var theImage = new Image<Gray, byte>(@"d:\temp\lena.jpg");
        for (int i = theImage.Rows - 1; i >= 0; i--)
        {
            for (int j = theImage.Cols - 1; j >= 0; j--)
            {
                if(theImage.Data[i,j,0]>byte.MaxValue/2)
                {
                        theImage.Data[i, j, 0] = byte.MaxValue;
                }
                else
                {
                    theImage.Data[i, j, 0] = 0;
                }

            }
        }


问:
Wordpress https 'redirected you too many times.' error
I am hosting a wordpress site on AWS and am transitioning from http to https. After reading some resources from online I added this line to the wp-config.php file:

```<code>define('FORCE_SSL_ADMIN', true);
</code>```

Now when i try to access the /wp-admin/ page I get the xx.xx.com redirected you too many times. The all of the other pages work, it is only the admin panel that is not working.

答:
For anyone coming here like me being behind a reverse proxy that handle the SSL stuff, it took me a while but I could find the documentation where it states what has to be done:

https://codex.wordpress.org/Administration_Over_SSL

It states to add an if in the wp-config:

```<code>// in some setups HTTP_X_FORWARDED_PROTO might contain
// a comma-separated list e.g. http,https
// so check for https existence
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
   $_SERVER['HTTPS']='on';
</code>```

As I don't like to touch the config (mostly because I forget I touched it) I tried to find a more elegant way of doing it:

https://wordpress.org/plugins/ssl-insecure-content-fixer/

I have tried with this plugin and it works.

Body:
I am hosting a wordpress site on AWS and am transitioning from http to https. After reading some resources from online I added this line to the wp-config.php file:

define('FORCE_SSL_ADMIN', true);

Now when i try to access the /wp-admin/ page I get the xx.xx.com redirected you too many times. The all of the other pages work, it is only the admin panel that is not working.

Body:
For anyone coming here like me being behind a reverse proxy that handle the SSL stuff, it took me a while but I could find the documentation where it states what has to be done:

https://codex.wordpress.org/Administration_Over_SSL

It states to add an if in the wp-config:

// in some setups HTTP_X_FORWARDED_PROTO might contain
// a comma-separated list e.g. http,https
// so check for https existence
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
   $_SERVER['HTTPS']='on';

As I don't like to touch the config (mostly because I forget I touched it) I tried to find a more elegant way of doing it:

https://wordpress.org/plugins/ssl-insecure-content-fixer/

I have tried with this plugin and it works.