问:
OpenCV maximum and minimum RGB value using mask
I need to get the minimum RGB value of a circle. How can I do like the average RGB value method (cv2.mean) appliying a mask? To get the average RGB value of a circle I'm doing:

```<code>circle_img = np.zeros((circle_img.shape[0],circle_img.shape[1]), np.uint8)
cv2.circle(circle_img,(x_center,y_center),radio,(255,255,255),-1)
datos_rgb = cv2.mean(color_img, mask=circle_img)
</code>```

Where color_img is the original image.

To get the minimum RGB value I'm doing:

```<code>masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_min = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).min(axis=0)
</code>```

Where masked_data is the second image (masked circle).

But I'm getting all time the value  [0,0,0] because of the background I think... I need to do like the average (cv2.mean) apliying the mask to ignore the black background. There is no pure black in the original image, so it is not possible to get the value [0,0,0]

To get the maximum RGB value it works perfectly doing:

```<code>masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_max = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).max(axis=0)
</code>```

Because the black color [0,0,0] it does not affect here.

This is the original image.

This is the masked circle.

答:
You may try using only numpy methods to get the results for all required calculations, rather than using OpenCV for some and numpy for others, and in some cases numpy can out-perform OpenCV in terms of execution time. You may use numpys' min, max and mean as:

```<code>import cv2
import numpy as np

img = cv2.imread("./assets/11yeJ.jpg")
mask = np.zeros((img.shape[0],img.shape[1]), np.uint8)
cv2.circle(mask, (493, 338), 30, (255, 255, 255), -1)

# Get the indices of mask where value == 255, which may be later used to slice the array.
img_mask = img[np.where(mask == 255)]

img_avg = np.mean(img_mask, axis=0)
img_min = np.min(img_mask, axis=0)
img_max = np.max(img_mask, axis=0)
</code>```

Body:
I need to get the minimum RGB value of a circle. How can I do like the average RGB value method (cv2.mean) appliying a mask? To get the average RGB value of a circle I'm doing:

circle_img = np.zeros((circle_img.shape[0],circle_img.shape[1]), np.uint8)
cv2.circle(circle_img,(x_center,y_center),radio,(255,255,255),-1)
datos_rgb = cv2.mean(color_img, mask=circle_img)

Where color_img is the original image.

To get the minimum RGB value I'm doing:

masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_min = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).min(axis=0)

Where masked_data is the second image (masked circle).

But I'm getting all time the value  [0,0,0] because of the background I think... I need to do like the average (cv2.mean) apliying the mask to ignore the black background. There is no pure black in the original image, so it is not possible to get the value [0,0,0]

To get the maximum RGB value it works perfectly doing:

masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_max = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).max(axis=0)

Because the black color [0,0,0] it does not affect here.

This is the original image.

This is the masked circle.

Body:
You may try using only numpy methods to get the results for all required calculations, rather than using OpenCV for some and numpy for others, and in some cases numpy can out-perform OpenCV in terms of execution time. You may use numpys' min, max and mean as:

import cv2
import numpy as np

img = cv2.imread("./assets/11yeJ.jpg")
mask = np.zeros((img.shape[0],img.shape[1]), np.uint8)
cv2.circle(mask, (493, 338), 30, (255, 255, 255), -1)

# Get the indices of mask where value == 255, which may be later used to slice the array.
img_mask = img[np.where(mask == 255)]

img_avg = np.mean(img_mask, axis=0)
img_min = np.min(img_mask, axis=0)
img_max = np.max(img_mask, axis=0)


来源: stackexchange

问:
derived entity instance in base type is null at initialization time
I have say ClassA entity = new ClassA(){firstname="blah", age=28}
Also class A inherit a ClassB, so in ClassB contructor I want to do something like ClassB()
{ do something with classA entity, but the think is that the entity instance is still null, it goes thru the newing up stage then after the values firstname and age get set, is there a way around this to be able to get the not null instance of the derived class and pass it to the base class? Thankx.  Using C# 4.</p>

答:
are you calling ClassA's constructor from ClassB?</p>

```<code>public class ClassA
{

}

public class classB
{
  public ClassB(): base()
  {
     //Do something with ClassA
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
are you calling ClassA's constructor from ClassB?

public class ClassA
{

}

public class classB
{
  public ClassB(): base()
  {
     //Do something with ClassA
  }
}


问:
Animate div from bottom to top and back
I have a div element which represents a navigation bar and has the id #navbar. It is positioned absolutely and is set to bottom: 20px;. Now I want it to move to the top, while keeping a 20px distance to the top, on the click of a button. When clicking the button again it should move back to the bottom of the page (again keeping the 20px distance) even if the window has been resized. In general, the resizing of the window should have no effect on the navigation bar. Here is the JavaScript code I have.

```<code>var isUp = false;
function animate() {
    if(!isUp) {
        $("#navbar").animate({top: 20}, 2000);
    } else {
        $("#navbar").animate({bottom: 20}, 2000);
    }
}
</code>```

But it doesn't work and the bar always ends up in the middle of the page. Any help is greatly appreciated.

EDIT:
Here is an example: https://jsfiddle.net/6knLw3a3/

答:
Advice to animate only one prop bottom or top.

Example: https://jsfiddle.net/17oy80c3/

ContentLicense: CC BY-SA 3.0

Title: Animate div from bottom to top and back

Body:
I have a div element which represents a navigation bar and has the id #navbar. It is positioned absolutely and is set to bottom: 20px;. Now I want it to move to the top, while keeping a 20px distance to the top, on the click of a button. When clicking the button again it should move back to the bottom of the page (again keeping the 20px distance) even if the window has been resized. In general, the resizing of the window should have no effect on the navigation bar. Here is the JavaScript code I have.

var isUp = false;
function animate() {
    if(!isUp) {
        $("#navbar").animate({top: 20}, 2000);
    } else {
        $("#navbar").animate({bottom: 20}, 2000);
    }
}

But it doesn't work and the bar always ends up in the middle of the page. Any help is greatly appreciated.

EDIT:
Here is an example: https://jsfiddle.net/6knLw3a3/


问:
How to get other array value if match?
Array 1 output

```<code> Array (
       [0] => Array ( [ID] => 335 [userid] => 4 [username] => demo [media_id] => 17 )
       [1] => Array ( [ID] => 436 [userid] => 4 [username] => demo [media_id] => 18 )
       [2] => Array ( [ID] => 637 [userid] => 4 [username] => demo [media_id] => 19 )
       [3] => Array ( [ID] => 838 [userid] => 4 [username] => demo [media_id] => 20 )
 );
</code>```

Array 2 output

```<code> Array (
        [1] => Array ( [ID] => 35 [userid] => 4  [media_id] => 17 )
        [2] => Array ( [ID] => 36 [userid] => 4  [media_id] => 18 )
     );
</code>```

How to get other array value if match? I need if media_id and userid of array 2 match in array 1 then how to get perticuler ID and username from array 1 in foreach loop of array 2 ?

Update

```<code>$array1 = array (
    0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "17" ),
    1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "18" ),
    2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
    3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                      );

$array2 = array (
    1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
    2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                          );

      foreach($array2 as $array) {

          foreach($array1 as $get_data) {
                 if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']){
                                    $get_result[] = //get_data true;
                                   } else {
                                    $get_result[] = //get_data false;
                                   }
                                }

                      //get ID and username or show false value

              }
</code>```

Final answer

```<code>foreach($array2 as $array) {
     $return = "false";
     foreach($array1 as $get_data) {
         if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
         $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
         $return = "true";
    }
  }

   if($return = "false"){
        echo false;
   }

}
</code>```

答:
Not sure about your real needs, but @gmc gave you (part of ? all ?) what you need IMHO</p>

```<code><?php

$array1 = array (
0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "117" ),
1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "118" ),
2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                  );

$array2 = array (
1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                      );

$get_result = array();

  foreach($array2 as $array) {

      foreach($array1 as $get_data) {
             if( ($array['media_id'] == $get_data['media_id']) && ($array['userid'] == $get_data['userid'])) {
                                $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
                               }
                            }
  }

if (count($get_result) == 0) {
echo"false";
}
else {
echo"true"; print_r($get_result); }
?>

/* I modified values to 117 & 118 -> returns "false" */
/* If you set values to 17 & 18 -> returns "true" */
</code>```

Title: How to get other array value if match?

Body:
Array 1 output

 Array (
       [0] => Array ( [ID] => 335 [userid] => 4 [username] => demo [media_id] => 17 )
       [1] => Array ( [ID] => 436 [userid] => 4 [username] => demo [media_id] => 18 )
       [2] => Array ( [ID] => 637 [userid] => 4 [username] => demo [media_id] => 19 )
       [3] => Array ( [ID] => 838 [userid] => 4 [username] => demo [media_id] => 20 )
 );

Array 2 output

 Array (
        [1] => Array ( [ID] => 35 [userid] => 4  [media_id] => 17 )
        [2] => Array ( [ID] => 36 [userid] => 4  [media_id] => 18 )
     );

How to get other array value if match? I need if media_id and userid of array 2 match in array 1 then how to get perticuler ID and username from array 1 in foreach loop of array 2 ?

Update

$array1 = array (
    0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "17" ),
    1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "18" ),
    2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
    3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                      );

$array2 = array (
    1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
    2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                          );

      foreach($array2 as $array) {

          foreach($array1 as $get_data) {
                 if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']){
                                    $get_result[] = //get_data true;
                                   } else {
                                    $get_result[] = //get_data false;
                                   }
                                }

                      //get ID and username or show false value

              }

Final answer

foreach($array2 as $array) {
     $return = "false";
     foreach($array1 as $get_data) {
         if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
         $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
         $return = "true";
    }
  }

   if($return = "false"){
        echo false;
   }

}

Body:
Not sure about your real needs, but @gmc gave you (part of ? all ?) what you need IMHO

<?php

$array1 = array (
0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "117" ),
1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "118" ),
2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                  );

$array2 = array (
1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                      );

$get_result = array();

  foreach($array2 as $array) {

      foreach($array1 as $get_data) {
             if( ($array['media_id'] == $get_data['media_id']) && ($array['userid'] == $get_data['userid'])) {
                                $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
                               }
                            }
  }

if (count($get_result) == 0) {
echo"false";
}
else {
echo"true"; print_r($get_result); }
?>

/* I modified values to 117 & 118 -> returns "false" */
/* If you set values to 17 & 18 -> returns "true" */


问:
HTML: Valid id attribute values?
When creating the id attributes for HTML elements, what rules are there for the value?

答:
jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write

```<code>var name = 'O'Hara';
</code>```

Selectors in jQuery API (see bottom note)

OwnerDisplayName: Mr Shark

ContentLicense: CC BY-SA 4.0

Title: HTML: Valid id attribute values?

Body:
jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write

var name = 'O'Hara';

Selectors in jQuery API (see bottom note)

OwnerDisplayName: kAlvaro


问:
Javascript: How to get/select all object with same keys?
I have object like this:

```<code>[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]
</code>```

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

```<code>[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]
</code>```

Thanks for your help ^_^

答:
using .filter() is smarter

You should loop through your object

```<code>// Your object
let obj = {...}

function getByPropertieValue( obj, prop, value )
{
    // objects with the good prop
    let matchs = []
    obj.forEach( subObj => { if (subObj[prop] == value) matchs.push(subObj) } )

    return matchs
}

console.log( getByPropertieValue(obj, 'kat', 'tkj') )
</code>```

Body:
I have object like this:

[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]

Thanks for your help ^_^

Body:
using .filter() is smarter

You should loop through your object

// Your object
let obj = {...}

function getByPropertieValue( obj, prop, value )
{
    // objects with the good prop
    let matchs = []
    obj.forEach( subObj => { if (subObj[prop] == value) matchs.push(subObj) } )

    return matchs
}

console.log( getByPropertieValue(obj, 'kat', 'tkj') )


问:
Java getters and setters don't work
Why do my getters and setters generate 'null' when I first instantiate the instances of the class?  When I set the attributes myself, they work, but they don't seem to get through the constructor appropriately?</p>

```<code>public class StudentClass {
public static void main (String[] args)
{

    System.out.println("Number of Students: "     + Student.getClassNumber() );

    Student s1 = new Student("Jack","Sprat","9 Monroe Street","New York", "NY", "jflash@optonline.net");  //instantiate
    Student s2 = new Student("Arnold","Lane","15 Broadway","Bronx", "NY", "alane@yahoo.net");  //instantiate
    Student s3 = new Student("Brian","Wilson","409 Surf Ave","Brooklyn", "NY", "bwilson@godonlyknows.com");  //instantiate
    Student s4 = new Student("Rosie","OGrady","190 Bowery","New York", "NY", "sweetrosie@yahoo.com");  //instantiate
    Student s5 = new Student("Gilbert","Sullivan","188 Savoy Street","Colonia", "NJ", "verymodel@gmail.com");  //instantiate

    System.out.println(s1.toString());         //call the toString() method
    System.out.println(s2.toString());
    System.out.println(s3.toString());
    System.out.println(s4.toString());
    System.out.println(s5.toString());

    String before = s1.getFirstname() + " " + s2.getLastname();   //call getters

    System.out.println("\nBefore change: " + before);

    s1.setLastname("Paulson");
    s2.setFirstname("George");
    s3.setState("NJ");
    s3.setCity("Wayne");

    System.out.println("After  change: " + s2.getFirstname() +
                                     " " + s1.getLastname());
    System.out.println();

    System.out.println(s1.toString());         //call the toString() method
    System.out.println(s2.toString());
    System.out.println(s3.toString());
    System.out.println(s4.toString());
    System.out.println(s5.toString());

}
}

class Student {
private static int classNumber;
private static String className = "Java 101";
private static String Instructor = "James Gosling";

private int studentId = 999;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;

Student(String first, String last) {
    firstname = first;
    lastname = last;
    classNumber += 1;
    studentId += 1;
}

Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    location = address;
    town = city;
    province = state;
    ping = email;
}

static int getClassNumber( )             //class method (getter)
{
    return (classNumber);
}
static String getClassName( )
{
    return (className);
}
static String getInstructor( )
{
    return (className);
}

int getStudentId( )                       //instance method (getter)
{
    return (studentId);
}
String getFirstname( )
{
    return (firstname);
}
String getLastname( )
{
    return (lastname);
}
String getAddress( )
{
    return (address);
}
String getCity( )
{
    return (city);
}
String getState( )
{
    return (state);
}
String getEmail( )
{
    return (email);
}

static void setClassNumber(int classNumber)      //static method (setter)
{
    Student.classNumber = classNumber;             //"Employee" to indicate static field
}
static void setClassName(String className)      //static method (setter)
{
    Student.className = className;             //"Employee" to indicate static field
}
static void setInstructor(String Instructor)      //static method (setter)
{
    Student.Instructor = Instructor;             //"Employee" to indicate static field
}

void  setFirstname(String firstname)
{
    this.firstname = firstname;
}
void  setLastname(String lastname)
{
    this.lastname = lastname;
}
void  setAddress(String address)
{
    this.address = address;
}
void  setCity(String city)
{
    this.city = city;
}
void  setState(String state)
{
    this.state = state;
}
void  setEmail(String email)
{
    this.email = email;
}

public String toString( )                      // toString instance method
{
    String studentProfile =
            "\t Class Name: "  + className +
            "\t Instructor: "   + Instructor +
            "\t Number of Students: "   + classNumber +
            "\t Name: " + firstname +  " " + lastname +
            "\t Address: "  + address +
            "\t City: "  + city +
            "\t State: "  + state +
            "\t Email: "  + email +
            "\t ID: "   + studentId;
    return (studentProfile);
}
}
</code>```

答:
You can closely look at your constructor and you will solve the issue:

```<code>Student(String first, String last, String location, String town, String province,
            String ping) {
        this(first,last);
        location = address;
        town = city;
        province = state;
        ping = email;
    }
</code>```

The issue is that you are trying to assign the values to the method arguments, BUT you need to assign values to instance variables (not to method arguments)

The following is the better (but NOT the best) approach:

```<code> Student(String first, String last, String location, String town, String province,
                String ping) {
            this(first,last);
            address = location;
            city = town;
            state = province;
            email = ping;
        }
</code>```

To avoid these problems, I strongly recommend you rename the variables same as the instance variables so that you can use this operator to set the values as shown below:

```<code>Student(String first, String last, String address,
    String city, String state, String email) {
       this(first,last);
       this.address = address;
       this.city = city;
       this.state = state;
       this.email = email;
   }
</code>```

Title: Java getters and setters don't work

Body:
Why do my getters and setters generate 'null' when I first instantiate the instances of the class?  When I set the attributes myself, they work, but they don't seem to get through the constructor appropriately?

public class StudentClass {
public static void main (String[] args)
{

    System.out.println("Number of Students: "     + Student.getClassNumber() );

    Student s1 = new Student("Jack","Sprat","9 Monroe Street","New York", "NY", "jflash@optonline.net");  //instantiate
    Student s2 = new Student("Arnold","Lane","15 Broadway","Bronx", "NY", "alane@yahoo.net");  //instantiate
    Student s3 = new Student("Brian","Wilson","409 Surf Ave","Brooklyn", "NY", "bwilson@godonlyknows.com");  //instantiate
    Student s4 = new Student("Rosie","OGrady","190 Bowery","New York", "NY", "sweetrosie@yahoo.com");  //instantiate
    Student s5 = new Student("Gilbert","Sullivan","188 Savoy Street","Colonia", "NJ", "verymodel@gmail.com");  //instantiate

    System.out.println(s1.toString());         //call the toString() method
    System.out.println(s2.toString());
    System.out.println(s3.toString());
    System.out.println(s4.toString());
    System.out.println(s5.toString());

    String before = s1.getFirstname() + " " + s2.getLastname();   //call getters

    System.out.println("\nBefore change: " + before);

    s1.setLastname("Paulson");
    s2.setFirstname("George");
    s3.setState("NJ");
    s3.setCity("Wayne");

    System.out.println("After  change: " + s2.getFirstname() +
                                     " " + s1.getLastname());
    System.out.println();

    System.out.println(s1.toString());         //call the toString() method
    System.out.println(s2.toString());
    System.out.println(s3.toString());
    System.out.println(s4.toString());
    System.out.println(s5.toString());

}
}

class Student {
private static int classNumber;
private static String className = "Java 101";
private static String Instructor = "James Gosling";

private int studentId = 999;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;

Student(String first, String last) {
    firstname = first;
    lastname = last;
    classNumber += 1;
    studentId += 1;
}

Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    location = address;
    town = city;
    province = state;
    ping = email;
}

static int getClassNumber( )             //class method (getter)
{
    return (classNumber);
}
static String getClassName( )
{
    return (className);
}
static String getInstructor( )
{
    return (className);
}

int getStudentId( )                       //instance method (getter)
{
    return (studentId);
}
String getFirstname( )
{
    return (firstname);
}
String getLastname( )
{
    return (lastname);
}
String getAddress( )
{
    return (address);
}
String getCity( )
{
    return (city);
}
String getState( )
{
    return (state);
}
String getEmail( )
{
    return (email);
}

static void setClassNumber(int classNumber)      //static method (setter)
{
    Student.classNumber = classNumber;             //"Employee" to indicate static field
}
static void setClassName(String className)      //static method (setter)
{
    Student.className = className;             //"Employee" to indicate static field
}
static void setInstructor(String Instructor)      //static method (setter)
{
    Student.Instructor = Instructor;             //"Employee" to indicate static field
}

void  setFirstname(String firstname)
{
    this.firstname = firstname;
}
void  setLastname(String lastname)
{
    this.lastname = lastname;
}
void  setAddress(String address)
{
    this.address = address;
}
void  setCity(String city)
{
    this.city = city;
}
void  setState(String state)
{
    this.state = state;
}
void  setEmail(String email)
{
    this.email = email;
}

public String toString( )                      // toString instance method
{
    String studentProfile =
            "\t Class Name: "  + className +
            "\t Instructor: "   + Instructor +
            "\t Number of Students: "   + classNumber +
            "\t Name: " + firstname +  " " + lastname +
            "\t Address: "  + address +
            "\t City: "  + city +
            "\t State: "  + state +
            "\t Email: "  + email +
            "\t ID: "   + studentId;
    return (studentProfile);
}
}

Body:
You can closely look at your constructor and you will solve the issue:

Student(String first, String last, String location, String town, String province,
            String ping) {
        this(first,last);
        location = address;
        town = city;
        province = state;
        ping = email;
    }

The issue is that you are trying to assign the values to the method arguments, BUT you need to assign values to instance variables (not to method arguments)

The following is the better (but NOT the best) approach:

 Student(String first, String last, String location, String town, String province,
                String ping) {
            this(first,last);
            address = location;
            city = town;
            state = province;
            email = ping;
        }

To avoid these problems, I strongly recommend you rename the variables same as the instance variables so that you can use this operator to set the values as shown below:

Student(String first, String last, String address,
    String city, String state, String email) {
       this(first,last);
       this.address = address;
       this.city = city;
       this.state = state;
       this.email = email;
   }


问:
How to read from one stream and write to several at once?
Suppose I have a readable stream, e.g. request(URL). And I want to write its response on the disk via fs.createWriteStream() and piping with the request. But at the same time I want to calculate a checksum of the downloading data via crypto.createHash() stream.

```<code>readable -+-> calc checksum
          |
          +-> write to disk
</code>```

And I want to do it on the fly, without buffering an entire response in memory.

It seems that I can implement it using oldschool on('data') hook. Pseudocode below:

```<code>const hashStream = crypto.createHash('sha256');
hashStream.on('error', cleanup);

const dst = fs.createWriteStream('...');
dst.on('error', cleanup);

request(...).on('data', (chunk) => {
    hashStream.write(chunk);
    dst.write(chunk);
}).on('end', () => {
    hashStream.end();
    const checksum = hashStream.read();
    if (checksum != '...') {
        cleanup();
    } else {
        dst.end();
    }
}).on('error', cleanup);

function cleanup() { /* cancel streams, erase file */ };
</code>```

But such approach looks pretty awkward. I tried to use stream.Transform or stream.Writable to implement something like read | calc + echo | write but I'm stuck with the implementation.

答:
Node.js readable streams have a .pipe method which works pretty much like the unix pipe-operator, except that you can stream js objects as well as just strings of some type.

Here's a link to the doc on pipe

An example of the use in your case could be something like:

```<code>const req = request(...);
req.pipe(dst);
req.pipe(hash);
</code>```

Note that you still have to handle errors per stream as they're not propagated and the destinations are not closed if the readable errors.

Body:
Suppose I have a readable stream, e.g. request(URL). And I want to write its response on the disk via fs.createWriteStream() and piping with the request. But at the same time I want to calculate a checksum of the downloading data via crypto.createHash() stream.

readable -+-> calc checksum
          |
          +-> write to disk

And I want to do it on the fly, without buffering an entire response in memory.

It seems that I can implement it using oldschool on('data') hook. Pseudocode below:

const hashStream = crypto.createHash('sha256');
hashStream.on('error', cleanup);

const dst = fs.createWriteStream('...');
dst.on('error', cleanup);

request(...).on('data', (chunk) => {
    hashStream.write(chunk);
    dst.write(chunk);
}).on('end', () => {
    hashStream.end();
    const checksum = hashStream.read();
    if (checksum != '...') {
        cleanup();
    } else {
        dst.end();
    }
}).on('error', cleanup);

function cleanup() { /* cancel streams, erase file */ };

But such approach looks pretty awkward. I tried to use stream.Transform or stream.Writable to implement something like read | calc + echo | write but I'm stuck with the implementation.

Body:
Node.js readable streams have a .pipe method which works pretty much like the unix pipe-operator, except that you can stream js objects as well as just strings of some type.

Here's a link to the doc on pipe

An example of the use in your case could be something like:

const req = request(...);
req.pipe(dst);
req.pipe(hash);

Note that you still have to handle errors per stream as they're not propagated and the destinations are not closed if the readable errors.


问:
OpenGL: How to check if the user supports glGenBuffers()?
I checked docs, and it says OpenGL version must be at least 1.5 to make glGenBuffers() work. The user has version 1.5 but the function call will cause a crash. Is this a mistake in the docs, or a driver problem on the user?

I am using this glGenBuffers() for VBO, how do i check if the user has support for this?

Edit: im using glew with glewInit() to initialize VBO

Edit2: I got it working on the user with glGenBuffersARB() function calls. But im still looking a way to find out when should i use glGenBuffers() and when should i use glGenBuffersARB() AND when should i use VertexArrays if none of the VBO function calls are supported.

I also found out that if(GLEW_VERSION_1_5) returns false on the user, but GL_VERSION gives 1.5.0, which just doesnt make any sense!

答:
Check this link. Maybe it will help you;)

```<code>if (GLEW_VERSION_1_5)
{
  /* You have OpenGL 1.5 */
}
</code>```

Try glGenBuffersARB insted glGenBuffers; I think you only need to check 1.5 support;

Body:
Check this link. Maybe it will help you;)

if (GLEW_VERSION_1_5)
{
  /* You have OpenGL 1.5 */
}

Try glGenBuffersARB insted glGenBuffers; I think you only need to check 1.5 support;


问:
yii2 listview next page without changing url
Yii2 listview is missing $.fn.yiilistview.update from yii1. Even more, it is dependent on pjax for basic requirements and thus creates all kinds of issues with nested pjax , timeouts etc for simple pagination with listView.

A GET request to controller is rendered by javascript into an HTML ( jSON returned from controller containing listview html ) . Since URL is not changed in this process, I did not use pjax for avoiding complexity and made simple ajax call and based on data returned on success will update container. ( like pjax does only manually using ajax without changing url)

now when I do next page, then URL is updated and also page full refreshes. Initially it was not working as well but once I added an IF check on page GET param inside controller and instead of returning renderAjax output in JSON, would directly return HTML now

How can we avoid updating URL with yii2 listview next page without using pjax and make it work seeemlesly with controller and javascript written in fashion to emulate pjax in manual ajax calls as stated above ?

Controller :

```<code>if($pageParam == null) {
    $page =  $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;

    Yii::$app->response->format = 'json';
    return array("error"=>false,"page"=>$page);
} else {
    return $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;
}
</code>```

List View :

```<code><?php if($dataProvider != null) : ?>
    <?=
    ListView::widget([
        'id'=>'itemList',
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_dataListView',
        'summary'=>'',
        'emptyText'=>$emptyPage
    ])
    ?>
<?php endif; ?>
</code>```

js :

ajax success GET callback :

```<code>success     : function(data) {
                    if(!data.error) {
                        $("#list-container").html(data.page);
</code>```

listcontainer itself resides in parent view for _list

答:
well, figured this out, trick was to not do pjax:begin / pjax:end calls in PHP and instead take control in javscript as any way I was manually replacing HTML using JSON returned from yii.

I could not figure a way without pjax - so here is solution on ajax:success

```<code>$("#list-container").html(data.page);
$(document).pjax('a', '#list-container', {push:false});
</code>```

Body:
Yii2 listview is missing $.fn.yiilistview.update from yii1. Even more, it is dependent on pjax for basic requirements and thus creates all kinds of issues with nested pjax , timeouts etc for simple pagination with listView.

A GET request to controller is rendered by javascript into an HTML ( jSON returned from controller containing listview html ) . Since URL is not changed in this process, I did not use pjax for avoiding complexity and made simple ajax call and based on data returned on success will update container. ( like pjax does only manually using ajax without changing url)

now when I do next page, then URL is updated and also page full refreshes. Initially it was not working as well but once I added an IF check on page GET param inside controller and instead of returning renderAjax output in JSON, would directly return HTML now

How can we avoid updating URL with yii2 listview next page without using pjax and make it work seeemlesly with controller and javascript written in fashion to emulate pjax in manual ajax calls as stated above ?

Controller :

if($pageParam == null) {
    $page =  $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;

    Yii::$app->response->format = 'json';
    return array("error"=>false,"page"=>$page);
} else {
    return $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;
}

List View :

<?php if($dataProvider != null) : ?>
    <?=
    ListView::widget([
        'id'=>'itemList',
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_dataListView',
        'summary'=>'',
        'emptyText'=>$emptyPage
    ])
    ?>
<?php endif; ?>

js :

ajax success GET callback :

success     : function(data) {
                    if(!data.error) {
                        $("#list-container").html(data.page);

listcontainer itself resides in parent view for _list

Body:
well, figured this out, trick was to not do pjax:begin / pjax:end calls in PHP and instead take control in javscript as any way I was manually replacing HTML using JSON returned from yii.

I could not figure a way without pjax - so here is solution on ajax:success

$("#list-container").html(data.page);
$(document).pjax('a', '#list-container', {push:false});


问:
Testing Internet Connection With Firebase
I tried the google recommended code for detecting connection state given here

but what i found is that the listener "looses connection" or stops working as it should ideally.At first it works fine i.e if i turn on/off my wifi/sim data then it shows correctly weather i am online or offline but then after some time (around 20 seconds or so) it stops working and always gives state as not connected even if i am connected to internet.It doesn't change if i toggle my net connection on and off.It works fine if i restart my app but after some time it stops working again.

I tried searching for answers but i could not find any solution, Someone suggested that the listener closes the connection after sometime and needs to be reinitialized.But doesn't that defeat the purpose for which it was made for?
I also tried using onDiscoonect() but couldn't find a way to restart it.

One solution might be to reinitialize it again and again after a set period of time using handler,but that is not how its supposed to work.

Is there a better solution?

答:
The .info/connected listener reports the state of the Firebase database connection, which is a WebSocket.  It does not report the state of your Internet connection.

Firebase auto-manages its WebSocket connection.  If there are no active listeners or pending writes, the connection is closed.  See this related question.


答:
You have the constructor assignments the wrong way round!

Set field = constructor parameter;

For example

```<code>address = location;
</code>```

Stylistically it's nice to have the parameter names dentical to the field names, and write

```<code>this.address = address;
</code>```

etc.

Title: Java getters and setters don't work

Body:
You have the constructor assignments the wrong way round!

Set field = constructor parameter;

For example

address = location;

Stylistically it's nice to have the parameter names dentical to the field names, and write

this.address = address;

etc.


问:
Quickest way to find the nth largest value in a numpy Matrix
There are lots of solutions to do this for a single array, but what about a matrix, such as:

```<code>>>> k
array([[ 35,  48,  63],
       [ 60,  77,  96],
       [ 91, 112, 135]])
</code>```

You can use k.max(), but of course this only returns the highest value, 135. What if I want the second or third?

答:
As said, np.partition should be faster (at most O(n) running time):

```<code>np.partition(k.flatten(), -2)[-2]
</code>```

should return the 2nd largest element. (partition guarantees that the numbered element is in position, all elements before are smaller, and all behind are bigger).

Body:
There are lots of solutions to do this for a single array, but what about a matrix, such as:

>>> k
array([[ 35,  48,  63],
       [ 60,  77,  96],
       [ 91, 112, 135]])

You can use k.max(), but of course this only returns the highest value, 135. What if I want the second or third?

Body:
As said, np.partition should be faster (at most O(n) running time):

np.partition(k.flatten(), -2)[-2]

should return the 2nd largest element. (partition guarantees that the numbered element is in position, all elements before are smaller, and all behind are bigger).


问:
Mobx returning ObservableObjectAdministration instead of my object
I'm new to mobx. I was wondering why I'm getting ObservableObjectAdministration when I call the computed getServerUrls() function instead of the object.

Below is my store.

```<code>import { observable, computed } from 'mobx';
import { ServerNames } from 'master-server-urls';

class ServerNamesStores {

  @observable ServerNameUrls = {};
  @computed get getServerUrls() {
    console.log('@computed get getServerUrls()',  this.ServerNameUrls);
    return this.ServerNameUrls;
  }

  constructor() {
    const overrideServer = {
      "medicontentServer": "https://mediaserver.example.com"
    }
    const newServerNames = Object.assign({}, ServerNames, overrideServer);
    this.ServerNameUrls = newServerNames;
  }

}

const serverNamesStores = new ServerNamesStores();

export default serverNamesStores;
export { ServerNamesStores };
</code>```

and below is my App.js

```<code>import React, { Component } from 'react';
import { observer } from 'mobx-react';
import ServerNamesStores from './Stores/ServerNamesStores'
import logo from './logo.svg';
import './App.scss';

@observer
class App extends Component {

  constructor(props) {
    super(props)
    const { ServerNameUrls, getServerUrls } = ServerNamesStores
    console.log('ServerNameUrls', ServerNameUrls);
    console.log('1. getServerUrls', getServerUrls);
    console.log('2. getServerUrls', JSON.stringify(getServerUrls));
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;
</code>```

Accessing the property works great. The code below works fine and will show the property value for ServerNameUrls.webServer

```<code>const { ServerNameUrls, getServerUrls } = ServerNamesStores
console.log('ServerNameUrls', ServerNameUrls.webServer)
</code>```

答:
I fixed it by adding the code below :)

```<code>import { toJS } from 'mobx';
</code>```

and then on the usage

```<code>console.log('getServerUrls output', toJS(getServerUrls));
</code>```

More info on MobX website

Body:
I'm new to mobx. I was wondering why I'm getting ObservableObjectAdministration when I call the computed getServerUrls() function instead of the object.

Below is my store.

import { observable, computed } from 'mobx';
import { ServerNames } from 'master-server-urls';

class ServerNamesStores {

  @observable ServerNameUrls = {};
  @computed get getServerUrls() {
    console.log('@computed get getServerUrls()',  this.ServerNameUrls);
    return this.ServerNameUrls;
  }

  constructor() {
    const overrideServer = {
      "medicontentServer": "https://mediaserver.example.com"
    }
    const newServerNames = Object.assign({}, ServerNames, overrideServer);
    this.ServerNameUrls = newServerNames;
  }

}

const serverNamesStores = new ServerNamesStores();

export default serverNamesStores;
export { ServerNamesStores };

and below is my App.js

import React, { Component } from 'react';
import { observer } from 'mobx-react';
import ServerNamesStores from './Stores/ServerNamesStores'
import logo from './logo.svg';
import './App.scss';

@observer
class App extends Component {

  constructor(props) {
    super(props)
    const { ServerNameUrls, getServerUrls } = ServerNamesStores
    console.log('ServerNameUrls', ServerNameUrls);
    console.log('1. getServerUrls', getServerUrls);
    console.log('2. getServerUrls', JSON.stringify(getServerUrls));
  }

  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

    );
  }
}

export default App;

Accessing the property works great. The code below works fine and will show the property value for ServerNameUrls.webServer

const { ServerNameUrls, getServerUrls } = ServerNamesStores
console.log('ServerNameUrls', ServerNameUrls.webServer)

Body:
I fixed it by adding the code below :)

import { toJS } from 'mobx';

and then on the usage

console.log('getServerUrls output', toJS(getServerUrls));

More info on MobX website


问:
How to remove dependency on System.Web.Mvc within domain model assembly containing POCOs
I have an assembly generated using POCO template using Entity Framework (e.g. "Company.Models.dll").Besides generated POCOs I also have "follow up" partial classes that define meta data using System.ComponentModel.DataAnnotations.
So for example Company.Models.Customer is auto-generated (in separate folder) and then I have partial class with same namespace. Within this partial class I define inner class for metadata...For example:

```<code>using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Company.Models
{
    [MetadataType(typeof (CustomerMetaData))]
    public partial class Customer
    {
        public override string ToString()
        {
            return String.Format("Id: {0}, Name: {1}", Id, Name);
        }

        //[Bind(Exclude = "Id")]
        public class CustomerMetaData
        {
            [ScaffoldColumn(false)]
            public int Id { get; set; }

            [DisplayName("Name")]
            [Required(ErrorMessage = "Customer Name is required.")]
            [StringLength(100, ErrorMessage = "Customer name cannot exceed 100 characters.", MinimumLength = 2)]
            public string Name { get; set; }
        }
    }
}
</code>```

The issue I am having is that I now want to use this assembly in my MVC project and want to use MVC specific attributes (like the commented out Bind attribute above).However, doing so requires making my Company.Models.dll dependent on System.Web.Mvc.dll.

I would like to avoid this at all costs if possible but how?

So far I am aware of 2 possible solutions and am asking community for their opinions or better approaches...

Solution 1

This solution has been discussed here: Using Data Annotations on POCO's with MVC for Remote Validation The "trick" was to use ViewModels and map (either mannually or using AutoMapper) POCOs to MVC project specific ViewModels. Then apply all necessary attributes to ViewModels instead of domain model POCOs. While this makes sense for large projects it is a bit overkill for small simple solutions...

Solution 2

Use Bind attribute in Controller action parameters (as seen on some http://www.asp.net/mvc tutorials). For example:

```<code>//
// POST: /Customer/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Customer customerToCreate)
{
        if (!ModelState.IsValid)
        return View();

        // TODO: Add insert logic here
    return RedirectToAction("Index");
    }
</code>```

Using this solution would allow to skip dependency on System.Web.Mvc from my POCO dll at the cost of having to remember to insert Bind attribute on all relevant Controller actions.
Also, if I have multiple ASP.NET MVC projects the issue gets worse...

So, is there another way? ;)

答:
A third option, which is similar to solution 2, is binding to the customer type.

You would create a Model Binder.

Watch Jimmy Bogards MVC Conf presentation on the subject: http://www.viddler.com/explore/mvcconf/videos/1/

Sample Code:

Global ASAX

```<code>    protected void Application_Start()
    {

        ModelBinders.Binders.Add(typeof(Media), new MediaModelBinder());
        ModelBinders.Binders.Add(typeof(Album), new AlbumModelBinder());

    }
</code>```

ModelBinder Class

```<code>public class MediaModelBinder : BaseModelBinder, IModelBinder
{
    /// <summary>
    /// Initializes a new instance of the <see cref="MediaModelBinder"/> class.
    /// </summary>
    public MediaModelBinder() : base(DependencyInjection.Resolve<IUserAuthorization>()) { }

    /// <summary>
    /// Binds the model to a value by using the specified controller context and binding context.
    /// </summary>
    /// <param name="controllerContext">The controller context.</param>
    /// <param name="bindingContext">The binding context.</param>
    /// <returns>The bound value.</returns>
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var mediaRepository = DependencyInjection.Resolve<IMediaRepository>();
        User user = GetUser(controllerContext);

        int mediaId = Convert.ToInt32(controllerContext.RouteData.Values["id"]);
        Media media = mediaRepository.RetrieveByPrimaryKeyAndUserId(mediaId, user.Id);

        return media;
    }
}
</code>```

Body:
I have an assembly generated using POCO template using Entity Framework (e.g. "Company.Models.dll").Besides generated POCOs I also have "follow up" partial classes that define meta data using System.ComponentModel.DataAnnotations.
So for example Company.Models.Customer is auto-generated (in separate folder) and then I have partial class with same namespace. Within this partial class I define inner class for metadata...For example:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Company.Models
{
    [MetadataType(typeof (CustomerMetaData))]
    public partial class Customer
    {
        public override string ToString()
        {
            return String.Format("Id: {0}, Name: {1}", Id, Name);
        }

        //[Bind(Exclude = "Id")]
        public class CustomerMetaData
        {
            [ScaffoldColumn(false)]
            public int Id { get; set; }

            [DisplayName("Name")]
            [Required(ErrorMessage = "Customer Name is required.")]
            [StringLength(100, ErrorMessage = "Customer name cannot exceed 100 characters.", MinimumLength = 2)]
            public string Name { get; set; }
        }
    }
}

The issue I am having is that I now want to use this assembly in my MVC project and want to use MVC specific attributes (like the commented out Bind attribute above).However, doing so requires making my Company.Models.dll dependent on System.Web.Mvc.dll.

I would like to avoid this at all costs if possible but how?

So far I am aware of 2 possible solutions and am asking community for their opinions or better approaches...

Solution 1

This solution has been discussed here: Using Data Annotations on POCO's with MVC for Remote Validation The "trick" was to use ViewModels and map (either mannually or using AutoMapper) POCOs to MVC project specific ViewModels. Then apply all necessary attributes to ViewModels instead of domain model POCOs. While this makes sense for large projects it is a bit overkill for small simple solutions...

Solution 2

Use Bind attribute in Controller action parameters (as seen on some http://www.asp.net/mvc tutorials). For example:

//
// POST: /Customer/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Customer customerToCreate)
{
        if (!ModelState.IsValid)
        return View();

        // TODO: Add insert logic here
    return RedirectToAction("Index");
    }

Using this solution would allow to skip dependency on System.Web.Mvc from my POCO dll at the cost of having to remember to insert Bind attribute on all relevant Controller actions.
Also, if I have multiple ASP.NET MVC projects the issue gets worse...

So, is there another way? ;)

Body:
A third option, which is similar to solution 2, is binding to the customer type.

You would create a Model Binder.

Watch Jimmy Bogards MVC Conf presentation on the subject: http://www.viddler.com/explore/mvcconf/videos/1/

Sample Code:

Global ASAX

    protected void Application_Start()
    {

        ModelBinders.Binders.Add(typeof(Media), new MediaModelBinder());
        ModelBinders.Binders.Add(typeof(Album), new AlbumModelBinder());

    }

ModelBinder Class

public class MediaModelBinder : BaseModelBinder, IModelBinder
{
    /// <summary>
    /// Initializes a new instance of the <see cref="MediaModelBinder"/> class.
    /// </summary>
    public MediaModelBinder() : base(DependencyInjection.Resolve<IUserAuthorization>()) { }

    /// <summary>
    /// Binds the model to a value by using the specified controller context and binding context.
    /// </summary>
    /// <param name="controllerContext">The controller context.</param>
    /// <param name="bindingContext">The binding context.</param>
    /// <returns>The bound value.</returns>
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var mediaRepository = DependencyInjection.Resolve<IMediaRepository>();
        User user = GetUser(controllerContext);

        int mediaId = Convert.ToInt32(controllerContext.RouteData.Values["id"]);
        Media media = mediaRepository.RetrieveByPrimaryKeyAndUserId(mediaId, user.Id);

        return media;
    }
}


答:
you're incorrectly assigning the class fields to the constructor parameters . To put it simply, you've the constructor assignments the wrong way around.

change this:

```<code>Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    location = address;
    town = city;
    province = state;
    ping = email;
}
</code>```

to this:

```<code>Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    this.address = location;
    this.city = town;
    this.state = province;
    this.email = ping;
}
</code>```

Title: Java getters and setters don't work

Body:
you're incorrectly assigning the class fields to the constructor parameters . To put it simply, you've the constructor assignments the wrong way around.

change this:

Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    location = address;
    town = city;
    province = state;
    ping = email;
}

to this:

Student(String first, String last, String location, String town, String province,
        String ping) {
    this(first,last); //call first constructor with two variables
    this.address = location;
    this.city = town;
    this.state = province;
    this.email = ping;
}


问:
Image rotated by 0 degrees has a different base64 compared to the original image
I have an image that I have rotated by 0 degrees on PIL, the exact command being:

```<code>image = Image.open("filename.jpg")
rotated = image.rotate(0,expand=True)
rotated.save("filename2.jpg")
</code>```

The base64 or even the sha1 hash of both these images is quite different. If the angle of rotation is 0, why should this be happening?

答:
Because jpg is lossy, just opening a jpg file and saving it again will result in loss of information and a different hash.

With png, you might get the exact same file as long as no other information (e.g. header with modification time) is updated. The pixels won't be modified after a 0° rotation, but the compression algorithm might yield a different binary file even if the image itself hasn't been touched.

To debug this behaviour, you could try it with a bmp file, save it again without rotation, save it again with rotation and check the hashes.

Body:
I have an image that I have rotated by 0 degrees on PIL, the exact command being:

image = Image.open("filename.jpg")
rotated = image.rotate(0,expand=True)
rotated.save("filename2.jpg")

The base64 or even the sha1 hash of both these images is quite different. If the angle of rotation is 0, why should this be happening?


问:
omnet++ installation error in windows 7
I am tring to install omnet++ but it gives me error "windows can not find ",is there anyone can help

I have been trying  mingmenv.cmd gives me the same error

it gives as shown below error when I try to install:

答:
First of all, did you unpack the OMNeT Windows installation file with the on-board ZIP tools or another program? Try to use programs like WinRAR or 7-Zip to unpack the OMNeT++ installation, the on-board ZIP tool from Windows 7 might have problems with the MinGW files.

Second, does the path to the OMNeT++ installation contain any spaces or special characters? This might also be the source of errors.

Third, does the message immediately show after you start the mingwenv.cmd or after you start it and try to run ./configure or make to configure and build OMNeT?? Check if no antivirus might block the OMNeT sources / helper programs.

General note: under Windows, you always use the mingwenv.cmd shell to compile OMNeT, the normal Windows command environment does not have the necessary paths or settings for OMNMeT.

Title: omnet++ installation error in windows 7


问:
SQL error: Invalid parameter number: parameter was not defined
This is my code. I believe it does not bind the value's to the parameters.. But I don't know why:

```<code>public function create($fields)
    {
        $keys = array_keys($fields);
        $values = null;
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

        if(!$this->db->prepare($sql)->execute($fields)) {
            return true;
        }
        return false;
    }
</code>```

And on index.php:

```<code>$user = new User();
$user->create(array(
                'name' => 'test',
                'username' => 'test2',
                'email' => 'test@gmail.com'
            ));
</code>```

Why are my values not bound to the parameters? This is the full error:

An exception occurred while executing 'INSERT INTO users (name,
  username, email) VALUES (?, ?, ?)' with params ["test", "test2",
  "test@gmail.com"]:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

答:
If you're using the ? way for your query, the array that you send in params might not have keys i think!

EDIT: do execute(array_values($fields)), you must use the keys when there are params like username = :username, pass = :pass etc

Body:
This is my code. I believe it does not bind the value's to the parameters.. But I don't know why:

public function create($fields)
    {
        $keys = array_keys($fields);
        $values = null;
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

        if(!$this->db->prepare($sql)->execute($fields)) {
            return true;
        }
        return false;
    }

And on index.php:

$user = new User();
$user->create(array(
                'name' => 'test',
                'username' => 'test2',
                'email' => 'test@gmail.com'
            ));

Why are my values not bound to the parameters? This is the full error:

An exception occurred while executing 'INSERT INTO users (name,
  username, email) VALUES (?, ?, ?)' with params ["test", "test2",
  "test@gmail.com"]:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined


问:
Merge multiple arrays based on their index using javascript
I need to merge two arrays into a single array.  I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

    <title></title>

```

答:
In case someone needs to merge any number of arrays (with fixed length) in the way mentioned above in the post, following function will be useful

console.clear();
var array1 = ["a1", "b1", "c1", "d1"];
var array2 = ["a2", "b2", "c2", "d2"];
var array3 = ["a3", "b3", "c3", "d3"];
var array4 = ["a4", "b4", "c4", "d4"];

function mergeElementsAtIndex(one_or_more_arrays){
    const total_arr = arguments.length;
    newArray = arguments[0].map((v, k) => {
   var temp_val = v;
        for(var i=1; i < total_arr; i++){
         temp_val += arguments[i][k];
        }
        return temp_val;
    });
    return newArray;
}
merged_array = mergeElementsAtIndex(array1, array2, array3, array4);
console.log(merged_array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
In case someone needs to merge any number of arrays (with fixed length) in the way mentioned above in the post, following function will be useful

console.clear();
var array1 = ["a1", "b1", "c1", "d1"];
var array2 = ["a2", "b2", "c2", "d2"];
var array3 = ["a3", "b3", "c3", "d3"];
var array4 = ["a4", "b4", "c4", "d4"];

function mergeElementsAtIndex(one_or_more_arrays){
    const total_arr = arguments.length;
    newArray = arguments[0].map((v, k) => {
   var temp_val = v;
        for(var i=1; i < total_arr; i++){
         temp_val += arguments[i][k];
        }
        return temp_val;
    });
    return newArray;
}
merged_array = mergeElementsAtIndex(array1, array2, array3, array4);
console.log(merged_array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Templated member function typedefs won't compile
```<code>#include <iostream>
#include <string>
using namespace std;

void printstr( const string & s ) { cout << s << endl; }

template < typename A >
class Test
{
public:
    typedef void (*Func)( const A & );
};

typedef void (*Func)( const string & );

template < typename A >
void bind(
        Test< A >::Func f,           //<---- does NOT compile
        //Func f,                    //<---- compiles & works!
        //void (*f)( const A & ),    //<---- compiles & works!
        const A & a) { f( a ); }

int main( )
{
    bind( printstr, string("test") );
    return 0;
}
</code>```

In the code above, I am trying to use a function pointer typedef from another class. As shown, it does not compile, but with either of the other two lines uncommented instead of the Test::Func f, line, it compiles fine! Is this something I can't do in C++? What syntax is needed?

Using g++ 4.4.3, I get

```<code>test.cpp:20: error: variable or field "bind" declared void
test.cpp:20: error: expected ")" before "f"
test.cpp:23: error: expected primary-expression before "const"
</code>```

答:
The name Test::Func is a dependent name and needs to be prefixed with typename

```<code>typename Test< A >::Func f,
</code>```

For a more detailed explanation you should check out Johannes explanation in the following answer

Where and why do I have to put the "template" and "typename" keywords?

Body:
#include <iostream>
#include <string>
using namespace std;

void printstr( const string & s ) { cout << s << endl; }

template < typename A >
class Test
{
public:
    typedef void (*Func)( const A & );
};

typedef void (*Func)( const string & );

template < typename A >
void bind(
        Test::Func f,           //<---- does NOT compile
        //Func f,                    //<---- compiles & works!
        //void (*f)( const A & ),    //<---- compiles & works!
        const A & a) { f( a ); }

int main( )
{
    bind( printstr, string("test") );
    return 0;
}

In the code above, I am trying to use a function pointer typedef from another class. As shown, it does not compile, but with either of the other two lines uncommented instead of the Test::Func f, line, it compiles fine! Is this something I can't do in C++? What syntax is needed?

Using g++ 4.4.3, I get

test.cpp:20: error: variable or field "bind" declared void
test.cpp:20: error: expected ")" before "f"
test.cpp:23: error: expected primary-expression before "const"

Body:
The name Test<A>::Func is a dependent name and needs to be prefixed with typename

typename Test< A >::Func f,

For a more detailed explanation you should check out Johannes explanation in the following answer

Where and why do I have to put the "template" and "typename" keywords?


问:
Cards in React-Bootstrap
Are Cards added to React-Bootstrap yet?

Or is there any other undocumented way of adding it?

What I am thinking of right now is -> className = 'bootstrap card class syntax', but I guess, it won't work because it won't recognise it.

答:
Sort of found the answer, but it doesn't go by the name of card

You can use <Thumbnail>, it gives the same feel as that of a card.

Title: Cards in React-Bootstrap


问:
How to sum a list of numbers in Emacs Lisp?
This works:

```<code>(+ 1 2 3)
6
</code>```

This doesn't work:

```<code>(+ '(1 2 3))
</code>```

This works if 'cl-*' is loaded:

```<code>(reduce '+ '(1 2 3))
6
</code>```

If reduce were always available I could write:

```<code>(defun sum (L)
  (reduce '+ L))

(sum '(1 2 3))
6
</code>```

What is the best practice for defining functions such as sum?

答: (insert (number-to-string (apply '+ '(1 2 3))))</p>

OwnerDisplayName: J.F. Sebastian

Body:
This works:

(+ 1 2 3)
6

This doesn't work:

(+ '(1 2 3))

This works if 'cl-*' is loaded:

(reduce '+ '(1 2 3))
6

If reduce were always available I could write:

(defun sum (L)
  (reduce '+ L))

(sum '(1 2 3))
6

What is the best practice for defining functions such as sum?


问:
Class Not Found: Empty Test Suite in IntelliJ
I'm just starting the computer science program at my college, and I'm having some issues with IntelliJ. When I try to run unit tests, I get the message

```<code>Process finished with exit code 1
Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.
</code>```

I also see a message entitled "No tests were found" on the left side of my screen. My test code is here:

```<code>package edu.macalester.comp124.hw0;

import org.junit.Test;
import static org.junit.Assert.*;

public class AreaTest {

    @Test
    public void testSquare() {
    assertEquals(Area.getSquareArea(3.0), 9.0, 0.001);
    }

    @Test
    public void testCircle() {
    assertEquals(Area.getCircleArea(3.0), 28.2743, 0.001);
    }
}
</code>```

And my project code is here:

```<code>package edu.macalester.comp124.hw0;

import java.lang.Math;
public class Area {

/**
 * Calculates the area of a square.
 * @param sideLength The length of the side of a square
 * @return The area
 */
public static double getSquareArea(double sideLength) {
    // Has been replaced by correct formula
    return sideLength * sideLength;
}

/**
 * Calculates the area of a circle.
 * @param radius The radius of the circle
 * @return The area
 */
public static double getCircleArea(double radius) {
    // Replaced by correct value
    return radius * 2 * Math.PI;
}

}
</code>```

How can I get my tests to work?  I'm using the most recent version of IntelliJ IDEA CE.

答: Was getting same error. My device was not connected to android studio. When I connected to studio. It works. This solves my problem.</p>

Body:
I'm just starting the computer science program at my college, and I'm having some issues with IntelliJ. When I try to run unit tests, I get the message

Process finished with exit code 1
Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.

I also see a message entitled "No tests were found" on the left side of my screen. My test code is here:

package edu.macalester.comp124.hw0;

import org.junit.Test;
import static org.junit.Assert.*;

public class AreaTest {

    @Test
    public void testSquare() {
    assertEquals(Area.getSquareArea(3.0), 9.0, 0.001);
    }

    @Test
    public void testCircle() {
    assertEquals(Area.getCircleArea(3.0), 28.2743, 0.001);
    }
}

And my project code is here:

package edu.macalester.comp124.hw0;

import java.lang.Math;
public class Area {

/**
 * Calculates the area of a square.
 * @param sideLength The length of the side of a square
 * @return The area
 */
public static double getSquareArea(double sideLength) {
    // Has been replaced by correct formula
    return sideLength * sideLength;
}

/**
 * Calculates the area of a circle.
 * @param radius The radius of the circle
 * @return The area
 */
public static double getCircleArea(double radius) {
    // Replaced by correct value
    return radius * 2 * Math.PI;
}

}

How can I get my tests to work?  I'm using the most recent version of IntelliJ IDEA CE.


问:
C programming--why gets() not taking input?
```<code>#include<stdio.h>
int main()
{
   int choice;
   char sl[10];
   char phn[10];
   printf("Enter choice: ");
   scanf("%d",&choice);
   switch(choice)
   {
   case 1:
       printf("\nEnter Student Details: \n\n");
       printf("\nEnter serial number: ");
       gets(sl);
       printf("Roll number: ");
       gets(phn);
   default:
      break;
   }
   return 0;
}
</code>```

C PROGRAMMING:

I used 2 gets() function here. second one is working but first one is not working. why?? how to make it work?

N.B: I want to take "sl" and "phn" variable as char type and I want to use gets() to take input.
please someone help....

答:
Never use gets(). It offers no protections against a buffer overflow vulnerability (that is, you cannot tell it how big the buffer you pass to it is, so it cannot prevent a user from entering a line larger than the buffer and clobbering memory).

fgets() is safe because you can guarantee you never overflow the input string buffer by passing in the buffer size (which includes room for the NULL.)

The most important difference is that fgets() knows how big the string
is and gets() does not. That means it is nearly impossible to write
safe code using gets() so don't do it.

in there use fgets() instead of gets()

Body:
#include<stdio.h>
int main()
{
   int choice;
   char sl[10];
   char phn[10];
   printf("Enter choice: ");
   scanf("%d",&choice);
   switch(choice)
   {
   case 1:
       printf("\nEnter Student Details: \n\n");
       printf("\nEnter serial number: ");
       gets(sl);
       printf("Roll number: ");
       gets(phn);
   default:
      break;
   }
   return 0;
}

C PROGRAMMING:

I used 2 gets() function here. second one is working but first one is not working. why?? how to make it work?

N.B: I want to take "sl" and "phn" variable as char type and I want to use gets() to take input.
please someone help....


问:
icudt error while installing stringi library in R
I'm writing this because it took me several days to come to this result.

Bottom line:  The stringi library version 1.1.3 (released March 2017) might have issues involving icudt.  You can install stringi 1.1.2 using the following commands:

```<code>packageurl <- "https://cran.r-project.org/src/contrib/Archive/stringi/stringi_1.1.2.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
</code>```

I put this together from some RStudio documentation on how to install an older package.

Background:

I was trying to install the forecast library in R. Originally, I was using R 3.1.2.  I also installed R 3.3.3 and tried to install stringi it.  I'm running CentOS 6.7 and don't have a choice to upgrade.

Forecast failed to install due to issues installing stringi.  The stringi library failed to install due to errors downloading ICU data library (icudt)
It looks like stringi 1.1.3 added download/build logic regarding icudt, and upcoming version 1.1.4 has corrections to this logic (as of date 2017-04-02).

I went to the ICU project site: and downloaded/installed the ICU library that appeared to be specified in the error messages below:

```<code>checking whether we may compile src/icu55/common/umapfile.c... yes
checking whether we may compile src/icu55/common/putil.cpp... yes
checking whether we can fetch icudt... WARNING: ignoring environment value of R_HOME
downloading ICU data library (icudt)
output path: icu55/data/icudt55l.zip
Error in stri_download_icudt("icu55/data") :
  could not find function "dir.exists"
Calls: identical -> stri_download_icudt
Execution halted
*** icudt could not be downloaded. stopping.
ERROR: configuration failed for package ‘stringi’
</code>```

Searches online for icu55, icudt55l.zip, or any procedure that followed to get past this error didn't turn up a procedure that worked.  I downloaded, built, and installed ICU 55.1 and also ICU 58.2.  I also updated gcc and g++.  The CRAN repository install notes for stringi 1.1.3 don't currently give a straightforward set of instructions to successfully install stringi when I have a working internet connection.

I started by asking this as a question and then found my answer.  I'll post it anyways. I had added several links but needed to remove them because I don't have enough cred to get away with them.

答:
The stringi library version 1.1.3 (released March 2017) might have issues involving icudt. You can install stringi 1.1.2 using the following commands:</p>

```<code>packageurl <- "https://cran.r-project.org/src/contrib/Archive/stringi/stringi_1.1.2.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
</code>```

Body:
I'm writing this because it took me several days to come to this result.

Bottom line:  The stringi library version 1.1.3 (released March 2017) might have issues involving icudt.  You can install stringi 1.1.2 using the following commands:

packageurl <- "https://cran.r-project.org/src/contrib/Archive/stringi/stringi_1.1.2.tar.gz"
install.packages(packageurl, repos=NULL, type="source")

I put this together from some RStudio documentation on how to install an older package.

Background:

I was trying to install the forecast library in R. Originally, I was using R 3.1.2.  I also installed R 3.3.3 and tried to install stringi it.  I'm running CentOS 6.7 and don't have a choice to upgrade.

Forecast failed to install due to issues installing stringi.  The stringi library failed to install due to errors downloading ICU data library (icudt)
It looks like stringi 1.1.3 added download/build logic regarding icudt, and upcoming version 1.1.4 has corrections to this logic (as of date 2017-04-02).

I went to the ICU project site: and downloaded/installed the ICU library that appeared to be specified in the error messages below:

checking whether we may compile src/icu55/common/umapfile.c... yes
checking whether we may compile src/icu55/common/putil.cpp... yes
checking whether we can fetch icudt... WARNING: ignoring environment value of R_HOME
downloading ICU data library (icudt)
output path: icu55/data/icudt55l.zip
Error in stri_download_icudt("icu55/data") :
  could not find function "dir.exists"
Calls: identical -> stri_download_icudt
Execution halted
*** icudt could not be downloaded. stopping.
ERROR: configuration failed for package ‘stringi’

Searches online for icu55, icudt55l.zip, or any procedure that followed to get past this error didn't turn up a procedure that worked.  I downloaded, built, and installed ICU 55.1 and also ICU 58.2.  I also updated gcc and g++.  The CRAN repository install notes for stringi 1.1.3 don't currently give a straightforward set of instructions to successfully install stringi when I have a working internet connection.

I started by asking this as a question and then found my answer.  I'll post it anyways. I had added several links but needed to remove them because I don't have enough cred to get away with them.


问:
Make sure that `gem install pg -v '0.18.4'` succeeds before bundling
I get the below error when I execute bundle update:

To see why this extension failed to compile, please check the mkmf.log which can

  be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in

  /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to

  /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

An error occurred while installing pg (0.18.4), and Bundler cannot
  continue.

  Make sure that gem install pg -v '0.18.4' succeeds before bundling.

I don't know why I get this issue. And I execute the gem install pg -v '0.18.4':

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

My Gemfile is this:

```<code>source 'https://gems.ruby-china.org'
gem 'rails', '5.0.0.1'
gem 'puma', '3.4.0'
gem 'sass-rails', '5.0.6'
gem 'uglifier', '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks', '5.0.1'
gem 'jbuilder', '2.4.1'

group :development, :test do
gem 'sqlite3', '1.3.11'
gem 'byebug', '9.0.0', platform: :mri
end

group :development do
  gem 'web-console', '3.1.1'
  gem 'listen', '3.0.8'
  gem 'spring', '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'

end
group :production do gem 'pg', '0.18.4'
end
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

Edit -1

My OS is macOS Sierra

答:
This issue often comes up and mostly results in obsolete version of Postgres.
Try

```<code>brew update
brew install postgresql
bundle install
</code>```

If you still need to use that version of Postgres you can specify the path to the 'pg_config':

```<code>gem install pg -- --with-pg-config=<path to pg_config>
</code>```

Body:
I get the below error when I execute bundle update:

To see why this extension failed to compile, please check the mkmf.log which can

  be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in

  /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to

  /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

An error occurred while installing pg (0.18.4), and Bundler cannot
  continue.

  Make sure that gem install pg -v '0.18.4' succeeds before bundling.

I don't know why I get this issue. And I execute the gem install pg -v '0.18.4':

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

My Gemfile is this:

source 'https://gems.ruby-china.org'
gem 'rails', '5.0.0.1'
gem 'puma', '3.4.0'
gem 'sass-rails', '5.0.6'
gem 'uglifier', '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks', '5.0.1'
gem 'jbuilder', '2.4.1'

group :development, :test do
gem 'sqlite3', '1.3.11'
gem 'byebug', '9.0.0', platform: :mri
end

group :development do
  gem 'web-console', '3.1.1'
  gem 'listen', '3.0.8'
  gem 'spring', '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'

end
group :production do gem 'pg', '0.18.4'
end
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Edit -1

My OS is macOS Sierra

Body:
This issue often comes up and mostly results in obsolete version of Postgres.
Try

brew update
brew install postgresql
bundle install

If you still need to use that version of Postgres you can specify the path to the 'pg_config':

gem install pg -- --with-pg-config=<path to pg_config>


问:
FindByValue on ASP.NET DropDownList
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

```<code>public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}
</code>```

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}
</code>```

答:
see if following code helps you

updated page_load

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindDdlAggerationUnitId();
    }
}

private void BindDdlAggerationUnitId()
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        ListItem item = null;
        if (value.HasValue && ddlAggerationUnitId.Items.Count > 0 && ddlAggerationUnitId.SelectedIndex > 1)
            item = ddlAggerationUnitId.Items.FindByValue(value.ToString());
        if ( item != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}
</code>```

Title: FindByValue on ASP.NET DropDownList

Body:
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

Body:
see if following code helps you

updated page_load

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindDdlAggerationUnitId();
    }
}

private void BindDdlAggerationUnitId()
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        ListItem item = null;
        if (value.HasValue && ddlAggerationUnitId.Items.Count > 0 && ddlAggerationUnitId.SelectedIndex > 1)
            item = ddlAggerationUnitId.Items.FindByValue(value.ToString());
        if ( item != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}


问:
Getting unique column names to allow a creation of a view?
I'm currently trying to create a view from two tables by doing a join, I've methods used here but i'm still getting this error:

Msg 4506, Level 16, State >1, Procedure vw_Employee, Line 3 [Batch Start Line 19]

  Column names in each view or function must be unique. Column name 'empNumber' in view or function 'vw_Employee' is specified more than once.

My view is as follows:

```<code>create view vw_Employee as
(
    select *
    from Employees e1
    inner join EmpInfo e2 on e2.empNumber = e1.empNumber
)
</code>```

答:
It's because both the tables have empNumber column and you are using * to select. There shouldnt be any ambiguity/collisions in column names in the select. Assuming the only common column name is empNumber.

```<code>create view vw_Employee as
(
select * from Employees e1 inner join EmpInfo e2
using (empNumber)
)
</code>```

I'd recommend you to explicitly list all the column names you need.

```<code>create view vw_Employee as
(
select e1.empNumber, . . .
from Employees e1 inner join EmpInfo e2
on e2.empNumber = e1.empNumber
)
</code>```

EDIT:

Based on your comment, try:

```<code>create view vw_Employee
as
(
        select e1.empNumber,
            e1.firstName,
            e1.lastName,
            e1.ssn,
            e1.job,
            e1.projectId,
            e2.[address],
            e2.[state],
            e2.zip,
        from Employees e1
        inner join EmpInfo e2 on e2.empNumber = e1.empNumber
        )
</code>```

Body:
I'm currently trying to create a view from two tables by doing a join, I've methods used here but i'm still getting this error:

Msg 4506, Level 16, State >1, Procedure vw_Employee, Line 3 [Batch Start Line 19]

  Column names in each view or function must be unique. Column name 'empNumber' in view or function 'vw_Employee' is specified more than once.

My view is as follows:

create view vw_Employee as
(
    select *
    from Employees e1
    inner join EmpInfo e2 on e2.empNumber = e1.empNumber
)

Body:
It's because both the tables have empNumber column and you are using * to select. There shouldnt be any ambiguity/collisions in column names in the select. Assuming the only common column name is empNumber.

create view vw_Employee as
(
select * from Employees e1 inner join EmpInfo e2
using (empNumber)
)

I'd recommend you to explicitly list all the column names you need.

create view vw_Employee as
(
select e1.empNumber, . . .
from Employees e1 inner join EmpInfo e2
on e2.empNumber = e1.empNumber
)

EDIT:

Based on your comment, try:

create view vw_Employee
as
(
        select e1.empNumber,
            e1.firstName,
            e1.lastName,
            e1.ssn,
            e1.job,
            e1.projectId,
            e2.[address],
            e2.[state],
            e2.zip,
        from Employees e1
        inner join EmpInfo e2 on e2.empNumber = e1.empNumber
        )


问:
Node.js API to spawn off a call to another API
I created a Node.js API.
When this API gets called I return to the caller fairly quickly.  Which is good.

But now I also want API to call or launch an different API or function or something that will go off and run on it's own. Kind of like calling a child process with child.unref().  In fact, I would use child.spawn() but I don't see how to have spawn() call another API.  Maybe that alone would be my answer?

Of this other process, I don't care if it crashes or finishes without error.
 So it doesn't need to be attached to anything.  But if it does remain attached to the Node.js console then icing on the cake.

I'm still thinking about how to identify & what to do if the spawn somehow gets caught up in running a really long time.  But ready to cross that part of this yet.

Your thoughts on what I might be able to do?

答:
I guess I could child.spawn('node', [somescript])
What do you think?
I would have to explore if my cloud host will permit this too.


问:
searchView in toolbar has a paddingBottom when fitsSystemWindows
In my style.xml:

```<code>    <item name="android:windowTranslucentStatus">true</item>
</code>```

In my toolbar.xml:

```<code>    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay">
</code>```

And when I input something it looks like:
enter image description here

enter image description here

So my question is:
Why it has a bottom padding? And, how to use fitsSystemWindows but make the bottom padding zero?

My temporary solution is:
use android:paddingTop="XXdp" instead of  android:fitsSystemWindows="true"

but it not elegant.

答:
I just search on Baidu and found a perfect solution.

http://www.th7.cn/Program/Android/201603/780326.shtml

just add this to manifast

```<code>android:windowSoftInputMode="adjustPan"
</code>```

Body:
In my style.xml:

    <item name="android:windowTranslucentStatus">true</item>

In my toolbar.xml:

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay">

And when I input something it looks like:
enter image description here

enter image description here

So my question is:
Why it has a bottom padding? And, how to use fitsSystemWindows but make the bottom padding zero?

My temporary solution is:
use android:paddingTop="XXdp" instead of  android:fitsSystemWindows="true"

but it not elegant.

Body:
I just search on Baidu and found a perfect solution.

http://www.th7.cn/Program/Android/201603/780326.shtml

just add this to manifast

android:windowSoftInputMode="adjustPan"


问:
How to customize column mappings with Spark Cassandra Connector in Java?
I wanted to change a column mapping to be append.  Is there a better way to customize the column mappings with Spark Cassandra Connector in Java than the following?

```<code> ColumnName song_id = new ColumnName("song_id", Option.empty());
 CollectionColumnName key_codes = new ColumnName("key_codes", Option.empty()).append();
 List<ColumnRef> collectionColumnNames = Arrays.asList(song_id, key_codes);
 scala.collection.Seq<ColumnRef> columnRefSeq = JavaApiHelper.toScalaSeq(collectionColumnNames);

 javaFunctions(songStream)
                .writerBuilder("demo", "song", mapToRow(PianoSong.class))
                .withColumnSelector(new SomeColumns(columnRefSeq))
                .saveToCassandra();
</code>```

This is taken from this Spark Streaming code sample.

答:
Just make your column ref's using the
CollectionColumnName

Which has a constructor

```<code>case class CollectionColumnName(
    columnName: String,
    alias: Option[String] = None,
    collectionBehavior: CollectionBehavior = CollectionOverwrite) extends ColumnRef
</code>```

You can rename by setting alias and you can change the insert behavior with collectionBehavior which takes the following classes.

Api Link

```<code>/** Insert behaviors for Collections. */
sealed trait CollectionBehavior
case object CollectionOverwrite extends CollectionBehavior
case object CollectionAppend extends CollectionBehavior
case object CollectionPrepend extends CollectionBehavior
case object CollectionRemove extends CollectionBehavior
</code>```

Which means you can just do

```<code>CollectionColumnName appendColumn =
  new CollectionColumnName("ColumnName", Option.empty(), CollectionPrepend$.MODULE$);
</code>```

Which looks a bit more Java-y and is a bit more explicit. Did you have any other goals for this code?

Body:
I wanted to change a column mapping to be append.  Is there a better way to customize the column mappings with Spark Cassandra Connector in Java than the following?

 ColumnName song_id = new ColumnName("song_id", Option.empty());
 CollectionColumnName key_codes = new ColumnName("key_codes", Option.empty()).append();
 List<ColumnRef> collectionColumnNames = Arrays.asList(song_id, key_codes);
 scala.collection.Seq<ColumnRef> columnRefSeq = JavaApiHelper.toScalaSeq(collectionColumnNames);

 javaFunctions(songStream)
                .writerBuilder("demo", "song", mapToRow(PianoSong.class))
                .withColumnSelector(new SomeColumns(columnRefSeq))
                .saveToCassandra();

This is taken from this Spark Streaming code sample.

Body:
Just make your column ref's using the
CollectionColumnName

Which has a constructor

case class CollectionColumnName(
    columnName: String,
    alias: Option[String] = None,
    collectionBehavior: CollectionBehavior = CollectionOverwrite) extends ColumnRef

You can rename by setting alias and you can change the insert behavior with collectionBehavior which takes the following classes.

Api Link

/** Insert behaviors for Collections. */
sealed trait CollectionBehavior
case object CollectionOverwrite extends CollectionBehavior
case object CollectionAppend extends CollectionBehavior
case object CollectionPrepend extends CollectionBehavior
case object CollectionRemove extends CollectionBehavior

Which means you can just do

CollectionColumnName appendColumn =
  new CollectionColumnName("ColumnName", Option.empty(), CollectionPrepend$.MODULE$);

Which looks a bit more Java-y and is a bit more explicit. Did you have any other goals for this code?


问:
Magento2 transtion success_message
how can I set translation for success message. it seems to be defined in
vendor/magento/module-checkout/Controller/Cart/Add.php
You added %1 to your shopping cart.

I tried to add translation csv but it seems not working ...

thanks for help!
martin

答: Solution is : custom theme had own translation code.</p>

Title: Magento2 transtion success_message


问:
Not able to access Android Developer console after original creator's account is expired/blocked
An Android Developer account was created using one of employee's Company account at google play store.
That person had added me as admin and also added 2 more developer accounts.
Now, Original creator has left the company, and his account is locked out.
Now I or any of our developers are not able to access the developer console.

Kindly help me in this regard, and let me know how to gain access to developer console as We have to update the new version of App to Play Store

答:
Answering for anyone who is still stuck. Only google support team can help in this issue.

Enable the expired account with help of Administrator(off-course after getting all approvals).

Ask google support to transfer the play store account to corporate email account(Do not repeat the mistake of making employee email account as Play Store account).

Ownership of account should be of company/department. Use this account for all play store activities(publishing etc)