问:
Show current file's block hierarchy
Is there a way in PhpStorm to show the hierarchy of where I am in the code? I'll often be placed on line 800 of some crappy top-down file and have no idea what block of the file I'm in.

For example, if my code looked like:

```<code>if (a) {
  // ... 200 lines of code ...
  if (unrelated) {
     // ... 200 lines of code ...
  }
  if (b) {
     // ... 200 lines of code ...
  } else {
     // ... 200 lines of code ...
     if (c) {
        switch ($var) {
            case 'a':
               [MY CURRENT CURSOR LOCATION]
        }
     } else {
       // ... 200 lines of code ...
     }
  }
}
</code>```

I'd want to see a summary something like:

```<code>if (a) {
  if (b) {} else {
    if (c) {
      switch case 'a':
</code>```

答:
That is not available for PHP (and I'm not sure if it's present for any other supported "coding" language like JS/Java/Ruby/Python/etc).

For PHP it shows max 3 levels: Namespace, Class and Method. It does not include control/logic flow directives (if/else/for/switch)

For hierarchical/markup languages like HTML/XML/JSON/YAML/CSS (mainly pre-processors that allow nesting) and alike it will show more nodes due to their nature.

The best I can suggest right now that will help a bit (excluding refactoring such code as it's out of the scope and may not always be possible):

CodeGlance plugin (will show scrollable small code overview on a side like Sublime has).

Use code folding to collapse not-needed-at-the-moment nodes (can be standard nodes or custom block of text).

If you hover over closing collapsing mark (that plus/minus clickable element on the left editor edge that expands/collapses the node) IDE will show you top 5 or so lines of the opening block via temp popup at the top -- good to identify what is the closest "branch" you are in.

Partially related existing tickets:

https://youtrack.jetbrains.com/issue/IDEA-173179

https://youtrack.jetbrains.com/issue/WI-22484

Feel free to submit your own Feature Request ticket at PhpStorm's Issue Tracker.

The possible issue with implementing this might be the expected complexity of the "if" conditions (most obvious case) -- quite often it will consist of 2+ conditions that might be quite lengthy (e.g. occupies 2+ lines). Problem arise with "how to display it in that small breadcrumbs area that is available".

Title: Show current file's block hierarchy

Body:
Is there a way in PhpStorm to show the hierarchy of where I am in the code? I'll often be placed on line 800 of some crappy top-down file and have no idea what block of the file I'm in.

For example, if my code looked like:

if (a) {
  // ... 200 lines of code ...
  if (unrelated) {
     // ... 200 lines of code ...
  }
  if (b) {
     // ... 200 lines of code ...
  } else {
     // ... 200 lines of code ...
     if (c) {
        switch ($var) {
            case 'a':
               [MY CURRENT CURSOR LOCATION]
        }
     } else {
       // ... 200 lines of code ...
     }
  }
}

I'd want to see a summary something like:

if (a) {
  if (b) {} else {
    if (c) {
      switch case 'a':


来源: stackexchange

问:
Pass data to model from controller in codeigniter
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

```<code>Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)
</code>```

controller:

```<code>public function postEnquiry()
{
    $data = $this->input->post();
    // echo "```";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}
```

<p>Model:</p>

```<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>
```

答:
You need to load your database library in autoload.php:

$autoload['libraries'] = array('database');

Also, load your model in the constructor or inside your function like this:

```<code>$this->load->model('User');
</code>```

Take a look to a similar question here codeigniter model error: Undefined property

Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)

controller:

public function postEnquiry()
{
    $data = $this->input->post();
    // echo "
";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}

Model:

<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>

Body:
You need to load your database library in autoload.php:

$autoload['libraries'] = array('database');

Also, load your model in the constructor or inside your function like this:

$this->load->model('User');

Take a look to a similar question here codeigniter model error: Undefined property

Hope it helps.

ContentLicense: CC BY-SA 3.0


问:
How to update foreign keys in one table when new record is added in another table
I have two tables:

```<code>Table A (id int pk, value nvarchar(10), version nvarchar(5))

Table B (id2 int pk, value2 nvarchar(20), TableAID int fk(tableA.id), version nvarchar(5))
</code>```

Sample data are:

```<code>Table A
-------
id | value | version
1    a       1
2    b       1

Table B
-------
id | value | TableAID | version
1    c       1             1
2    d       1             1
</code>```

Now if i insert new record with new version in table A, i'm getting following:

```<code>Table A
-------
id | value | version
1    null    1
2    b       1
3    a       2
</code>```

And Table B should look like this:

```<code>Table B
-------
id | value | TableAID | version
1    c       3             1
2    d       3             1
</code>```

(Foreign key field have to change).

How to accomplish that???? I'm filling data and version with cursors.

UPDATE!

The thing is that I have to insert new row for every new version of data in Table A. I'm not allowed to delete old versions, and I have to make them stay as they are. The new versions are inserted as new data but the old version of same data change their value to null.

If I insert new version of data in Table A I that get also a new ID for that value. So I have to update the Table B with that new ID.

答:
I don't think you can achieve this by using foreign key constraints.
I would rather suggest you to use an Insert trigger on table A.
The update statement in the insert trigger would look like below:</p>

```<code>UPDATE B
SET B.TableAID = I.ID
FROM B
INNER JOIN A
 ON A.ID = B.TableAID
INNER JOIN INSERTED I
 ON I.VALUE = A.VALUE
</code>```

Body:
I have two tables:

Table A (id int pk, value nvarchar(10), version nvarchar(5))

Table B (id2 int pk, value2 nvarchar(20), TableAID int fk(tableA.id), version nvarchar(5))

Sample data are:

Table A
-------
id | value | version
1    a       1
2    b       1

Table B
-------
id | value | TableAID | version
1    c       1             1
2    d       1             1

Now if i insert new record with new version in table A, i'm getting following:

Table A
-------
id | value | version
1    null    1
2    b       1
3    a       2

And Table B should look like this:

Table B
-------
id | value | TableAID | version
1    c       3             1
2    d       3             1

(Foreign key field have to change).

How to accomplish that???? I'm filling data and version with cursors.

UPDATE!

The thing is that I have to insert new row for every new version of data in Table A. I'm not allowed to delete old versions, and I have to make them stay as they are. The new versions are inserted as new data but the old version of same data change their value to null.

If I insert new version of data in Table A I that get also a new ID for that value. So I have to update the Table B with that new ID.

Body:
I don't think you can achieve this by using foreign key constraints.
I would rather suggest you to use an Insert trigger on table A.
The update statement in the insert trigger would look like below:

UPDATE B
SET B.TableAID = I.ID
FROM B
INNER JOIN A
 ON A.ID = B.TableAID
INNER JOIN INSERTED I
 ON I.VALUE = A.VALUE


问:
IntelliJ - package org.springframework.stereotype does not exist
I'm just starting to use IntelliJ and working on making a very simple "hello world" application. It looks like a very simple setup issue but I can't find a solution here that works.

Here's the pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jay.jayWorld</groupId>
  <artifactId>simple-project</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>simple-project</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <finalName>Spring4MVCHelloWorldDemo</finalName>
  </build>
</project>
</code>```

Is it because I'm using ${springframework.version}? I've seen from some project that this works but not to be the case in my project. Do i need to define it somewhere?

Here's the screenshot of the error.

答:
You need to define a property named springframework.version in your maven POM. Like this </p>

```<code><properties>
    <springframework.version>4.3.11</springframework.version>
</properties>
</code>```

Body:
I'm just starting to use IntelliJ and working on making a very simple "hello world" application. It looks like a very simple setup issue but I can't find a solution here that works.

Here's the pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jay.jayWorld</groupId>
  <artifactId>simple-project</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>simple-project</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <finalName>Spring4MVCHelloWorldDemo</finalName>
  </build>
</project>

Is it because I'm using ${springframework.version}? I've seen from some project that this works but not to be the case in my project. Do i need to define it somewhere?

Here's the screenshot of the error.

Body:
You need to define a property named springframework.version in your maven POM. Like this

<properties>
    <springframework.version>4.3.11</springframework.version>
</properties>


问:
Chartjs 2: Multi level/hierarchical category axis in chartjs
Is it possible to define a bar chart with a multi level/category axis?

For instance I'd like to display the Region/Province categories like in this Excel chart:

I found this example using multiple xAxes.

```<code>xAxes:[
    {
      id:'xAxis1',
      type:"category",
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          return month;
        }
      }
    },
    {
      id:'xAxis2',
      type:"category",
      gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
      },
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          if(month === "February"){
            return year;
          }else{
            return "";
          }
        }
      }
    }
  ]
</code>```

The problem is it seems that the two axes are not really linked and the alignment of second axis is based on values instead of aligning in middle of lower level category. this case cause issues

Is there a clean way to achieve this in chart.js?

Update:
I ended up creating a feature request on chartjs.

答: This should work as per your requirement http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#8-grouped-bar-chart</p>

Body:
Is it possible to define a bar chart with a multi level/category axis?

For instance I'd like to display the Region/Province categories like in this Excel chart:

I found this example using multiple xAxes.

xAxes:[
    {
      id:'xAxis1',
      type:"category",
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          return month;
        }
      }
    },
    {
      id:'xAxis2',
      type:"category",
      gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
      },
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          if(month === "February"){
            return year;
          }else{
            return "";
          }
        }
      }
    }
  ]

The problem is it seems that the two axes are not really linked and the alignment of second axis is based on values instead of aligning in middle of lower level category. this case cause issues

Is there a clean way to achieve this in chart.js?

Update:
I ended up creating a feature request on chartjs.


问:
Difference between honor, verified, audit and staff in openedx
Can anyone explain to me the difference between each user type (honor, verified, audit and staff) and they roles ? (a brief explanation of each user and what they can do).

I searched in the official documentation, but i found nothing !

Thanks.

答:
I've had a related issue before, that I found some users are enrolled as audit and others are enrolled as honor in a course, and I searched a lot and read Drakes answer.

After a lot of research and investigation, I noticed that users enrollment can be related to course mode. I used to add honor mode to courses to django admin panel, so if a user enrolled in a course before I added honor mode, he will be enrolled as audit.

Just added this answer to indicate this link for future visitors.
And I'm now looking for a way to move audit students to honor, because, in the latest openedx release, they don't get certificates.

Edit: seems we found what we were looking for in:
theSite/admin/student/courseenrollment/


问:
Read file contents and create Map of filename and contents
I want to read files from given directory then read contents from file and create Map of filename as key and its contetns as value.

I did not got any success but I have tried like this,

```<code>   def getFileLists(): List[File] = {
      val directory = "./input"
    //  print(new File(directory).listFiles().toList)
      return new File(directory).listFiles().toList
    }

    val contents = getFileLists().map(file => Source.fromFile(file).getLines())
    print(contents)
</code>```

答:
you can change your following line

```<code>val contents = getFileLists().map(file => Source.fromFile(file).getLines())
</code>```

to

```<code>val contents = getFileLists().map(file => (file.getName, Source.fromFile(file).getLines()))
</code>```

which would give you

```<code>contents: List[(String, Iterator[String])]
</code>```

Furthermore you can add .toMap method call as

```<code>val contents = getFileLists().map(file => (file.getName, Source.fromFile(file).getLines())).toMap
</code>```

which would give you

```<code>contents: scala.collection.immutable.Map[String,Iterator[String]]
</code>```

Body:
I want to read files from given directory then read contents from file and create Map of filename as key and its contetns as value.

I did not got any success but I have tried like this,

   def getFileLists(): List[File] = {
      val directory = "./input"
    //  print(new File(directory).listFiles().toList)
      return new File(directory).listFiles().toList
    }

    val contents = getFileLists().map(file => Source.fromFile(file).getLines())
    print(contents)

Body:
you can change your following line

val contents = getFileLists().map(file => Source.fromFile(file).getLines())

to

val contents = getFileLists().map(file => (file.getName, Source.fromFile(file).getLines()))

which would give you

contents: List[(String, Iterator[String])]

Furthermore you can add .toMap method call as

val contents = getFileLists().map(file => (file.getName, Source.fromFile(file).getLines())).toMap

which would give you

contents: scala.collection.immutable.Map[String,Iterator[String]]


问:
Laravel stuck cache keeps displaying what's not there
So I'm creating a web application and got stuck trying to fix this error

"Use of undefined constant images - assumed 'images' (View: /Users/ernest/Diplomska/bazar/resources/views/pages/welcome.blade.php)"

I used Chrome and Safari to see if the problem was in browser cache. Then I stopped, updated and restarted Valet. After that failed I cleared composer cache and updated it and still nothing. I also tried rebooting the system just in case to no avail.

My current code:

```<code>    <!-- First row -->
    <div class="row" style="text-align: center;">
      <div class="col-sm-2 offset-sm-1">
        <a href="#">
          <img src="{{ url('/public/images/literature.jpeg') }}">
          <p>Literature</p>
        </a>
      </div>
      <div class="col-sm-2 offset-sm-2">
        <a href="#">
          <img src="{{ url('/public/images/music.jpeg') }}">
          <p>Music</p>
         </a>
       </div>
       <div class="col-sm-2 offset-sm-2">
          <a href="#" id="categoryId">
            <img src="{{ url('/public/images/graphics.jpeg') }}">
            <p>Graphics</p>
          </a>
        </div>
      </div>
</code>```

What browser thinks my code is (displayed in error on any browser):

```<code>    1       <!-- Choose category -->
    2       <div class="container" style="padding-top: 70px; padding-bottom: 70px; border-bottom: 1px solid #d6dbe0;">
    3          <h1 style="text-align: center; color: #a7a7a7; padding-bottom: 40px;">Choose category</h1>
    4          <div style="margin: auto;">
    5
    6             <!-- First row -->
    7             <div class="row" style="text-align: center;">
    8               <div class="col-sm-2 offset-sm-1">
    9                 <a href="#">
    10                  <img src="<?php echo e(asset(images/literature.jpeg)); ?>">
    11                  <p>Literature</p>
    12                </a>
    13              </div>
    14              <div class="col-sm-2 offset-sm-2">
    15                <a href="#">
    16                  <img src="public/music.jpeg">
    17                  <p>Music</p>
    18                </a>
    19              </div>
    20              </a>
    21              <div class="col-sm-2 offset-sm-2">
    22                <a href="#" id="categoryId">
</code>```

So my question is how do I tell browser to recheck the written code because it keeps insisting on asset() which is no longer there.

答:
Make sure you are looking at the right file. There might be a different welcome file some place else.

Use View::render function to see what the output of the file is rather than debugging it on your browser.

Body:
So I'm creating a web application and got stuck trying to fix this error

"Use of undefined constant images - assumed 'images' (View: /Users/ernest/Diplomska/bazar/resources/views/pages/welcome.blade.php)"

I used Chrome and Safari to see if the problem was in browser cache. Then I stopped, updated and restarted Valet. After that failed I cleared composer cache and updated it and still nothing. I also tried rebooting the system just in case to no avail.

My current code:

Literature

Music

Graphics

What browser thinks my code is (displayed in error on any browser):

    1
    2

    3
Choose category

    4

    5
    6
    7

    8

    9
    10                  <img src="<?php echo e(asset(images/literature.jpeg)); ?>">
    11
Literature

    12
    13

    14

    15
    16
    17
Music

    18
    19

    20
    21

    22

So my question is how do I tell browser to recheck the written code because it keeps insisting on asset() which is no longer there.


问:
Way to have compiled python files in a separate folder?
Is it possible to have Python save the .pyc files to a separate folder location that is in sys.path?

```<code>/code
    foo.py
    foo.pyc
    bar.py
    bar.pyc
</code>```

To:

```<code>/code
   foo.py
   bar.py
/code_compiled
   foo.pyc
   bar.pyc
</code>```

I would like this because I feel it'd be more organized. Thanks for any help you can give me.

答:
I agree, distributing your code as an egg is a great way to keep it organized. What could be more organized than a single-file containing all of the code and meta-data you would ever need. Changing the way the bytecode compiler works is only going to cause confusion.

If you really do not like the location of those pyc files, an alternative is to run from a read-only folder. Since python will not be able to write, no pyc files ever get made. The hit you take is that every python file will have to be re-compiled as soon as it is loaded, regardless of whether you have changed it or not. That means your start-up time will be a lot worse.

OwnerDisplayName: Evan Fosmark

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to have Python save the .pyc files to a separate folder location that is in sys.path?

/code
    foo.py
    foo.pyc
    bar.py
    bar.pyc

To:

/code
   foo.py
   bar.py
/code_compiled
   foo.pyc
   bar.pyc

I would like this because I feel it'd be more organized. Thanks for any help you can give me.

OwnerDisplayName: Salim Fadhley

LastEditorDisplayName: Salim Fadhley


问:
how do we represent an edge list given that we have a graph with nodes and edges.am not talking about adjacency lists
what is an edge list?not an adjacency list..
and how do we represent an edge list in C programming provided that we are given a graph with nodes and edges?</p>

答:
Using the definition of edge list found here, and assuming undirected edges, emulating the "human" representation would be a good first attempt:

```<code>typedef struct UndirectedEdge {
    int ends[2];
};
</code>```

Where your vertices are all numbered within the range of int. If they're directed:

```<code>typedef struct DirectedEdge {
    int from;
    int to;
}
</code>```

Add other properties as required, with type appropriate to your problem:

```<code>typedef struct WeightedEdge {
    size_t from;
    size_t to;
    double weight;
}
</code>```

Note that a list of vertices isn't required, unless to map integer vertex indices to human-readable labels if they exist in your initial problem. Furthermore, you should define a suitable comparison function for your edge list to ensure uniqueness of your edges depending on properties of your graph, such as directedness.

```<code>typedef struct EdgeList {
    size_t edge_count;
    EdgeType *edges;
}

_Bool undirected_edge_equal(UndirectedEdge *this, UndirectedEdge *other) {
    return this->ends[0] == other->ends[0] && this->ends[1] == other->ends[1]
        || this->ends[0] == other->ends[1] && this->ends[1] == other->ends[0]
}

_Bool directed_edge_equal(DirectedEdge *this, DirectedEdge *other) {
    return this->from == other->from && this->to == other->to;
}
</code>```

Body:
Using the definition of edge list found here, and assuming undirected edges, emulating the "human" representation would be a good first attempt:

typedef struct UndirectedEdge {
    int ends[2];
};

Where your vertices are all numbered within the range of int. If they're directed:

typedef struct DirectedEdge {
    int from;
    int to;
}

Add other properties as required, with type appropriate to your problem:

typedef struct WeightedEdge {
    size_t from;
    size_t to;
    double weight;
}

Note that a list of vertices isn't required, unless to map integer vertex indices to human-readable labels if they exist in your initial problem. Furthermore, you should define a suitable comparison function for your edge list to ensure uniqueness of your edges depending on properties of your graph, such as directedness.

typedef struct EdgeList {
    size_t edge_count;
    EdgeType *edges;
}

_Bool undirected_edge_equal(UndirectedEdge *this, UndirectedEdge *other) {
    return this->ends[0] == other->ends[0] && this->ends[1] == other->ends[1]
        || this->ends[0] == other->ends[1] && this->ends[1] == other->ends[0]
}

_Bool directed_edge_equal(DirectedEdge *this, DirectedEdge *other) {
    return this->from == other->from && this->to == other->to;
}


问:
how do i build a list of maps in terraform
i would like to build a list of maps in terraform. Is there an operation that would let me do that.

eg: i would like to build the structure (from aws_instance.test.*.private_ip)

```<code>addresses = [
   {
     address = private_ip-1
   },
   {
     address = private_ip-2
   }
   ...
]
</code>```

答:
With terraform 10.8 you can

```<code>  output "private_subnets" {
      value = [
          "${aws_subnet.private.*.id}"
      ]
   }
</code>```

https://github.com/hashicorp/terraform/issues/7430

Body:
i would like to build a list of maps in terraform. Is there an operation that would let me do that.

eg: i would like to build the structure (from aws_instance.test.*.private_ip)

addresses = [
   {
     address = private_ip-1
   },
   {
     address = private_ip-2
   }
   ...
]

Body:
With terraform 10.8 you can

  output "private_subnets" {
      value = [
          "${aws_subnet.private.*.id}"
      ]
   }

https://github.com/hashicorp/terraform/issues/7430


问:
Infinite scroll of finite items
I have a GridView that has items inside 5x50.

I need to scroll them in all directions and instead of stopping when reached the end just start from the top/left.

for example left-to-right scroll

before scroll

```<code>1 2 3 4 5
6 7 8 9 10
</code>```

after scroll to the right

```<code>5 1 2 3 4
10 6 7 8 9
</code>```

and for top-to-bottom (or bottom-to-top)

before scroll to the bottom

```<code>1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
</code>```

after scroll

```<code>6 7 8 9 10
11 12 13 14 15
1 2 3 4 5
</code>```

I try to make it smooth scroll as GridView native scroll.

答:
Having specified following view hierarchy in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>
</code>```

And a basic list item - a TextView, inside item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"/>
</code>```

Then in the activity:

```<code>public class MainActivity extends AppCompatActivity {

    private static final int spanCount = 5;
    private static final int totalItemCount = 15;

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

        RecyclerView recyclerView = findViewById(R.id.recycler);
        // Shamelessly stolen from devunwired bit.ly/2yCqVIp
        recyclerView.addItemDecoration(new GridDividerDecoration(this));
        recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(new MyAdapter(totalItemCount));
    }

    static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        private final int totalSizeOfItems;
        private boolean hasBeenSetup = false;

        MyAdapter(int totalSizeOfItems) {
            this.totalSizeOfItems = totalSizeOfItems;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            final int cellSize = parent.getMeasuredWidth() / spanCount;
            view.setMinimumWidth(cellSize);
            view.setMinimumHeight(cellSize);
            setupRecyclerHeightIfNeeded(parent, cellSize);
            return new MyViewHolder(view);
        }

        // We need to perform this operation once, not each time `onCreateViewHolder` is called
        private void setupRecyclerHeightIfNeeded(View parent, int cellSize) {
            if (hasBeenSetup) return;
            hasBeenSetup = true;
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            int numOfRows = (int) (totalItemCount / (double) spanCount);
            params.height = numOfRows * cellSize;
            new Handler().post(parent::requestLayout);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int pos) {
            int position = holder.getAdapterPosition() % totalSizeOfItems;
            holder.textView.setText(Integer.toString(position + 1));
        }

        @Override
        public int getItemCount() {
            // this will result the list to be "infinite"
            return Integer.MAX_VALUE;
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}
</code>```

On output you'll get:

Taking care of the horizontal scroll would require a small amount of changes:

orientation of GridLayoutManager should be changed to HORIZONTAL

inside adapter appropriate width/height setters should be substituted

Other than that - everything should be similar.

Title: Infinite scroll of finite items

Body:
I have a GridView that has items inside 5x50.

I need to scroll them in all directions and instead of stopping when reached the end just start from the top/left.

for example left-to-right scroll

before scroll

1 2 3 4 5
6 7 8 9 10

after scroll to the right

5 1 2 3 4
10 6 7 8 9

and for top-to-bottom (or bottom-to-top)

before scroll to the bottom

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

after scroll

6 7 8 9 10
11 12 13 14 15
1 2 3 4 5

I try to make it smooth scroll as GridView native scroll.

Body:
Having specified following view hierarchy in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

And a basic list item - a TextView, inside item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"/>

Then in the activity:

public class MainActivity extends AppCompatActivity {

    private static final int spanCount = 5;
    private static final int totalItemCount = 15;

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

        RecyclerView recyclerView = findViewById(R.id.recycler);
        // Shamelessly stolen from devunwired bit.ly/2yCqVIp
        recyclerView.addItemDecoration(new GridDividerDecoration(this));
        recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(new MyAdapter(totalItemCount));
    }

    static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        private final int totalSizeOfItems;
        private boolean hasBeenSetup = false;

        MyAdapter(int totalSizeOfItems) {
            this.totalSizeOfItems = totalSizeOfItems;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            final int cellSize = parent.getMeasuredWidth() / spanCount;
            view.setMinimumWidth(cellSize);
            view.setMinimumHeight(cellSize);
            setupRecyclerHeightIfNeeded(parent, cellSize);
            return new MyViewHolder(view);
        }

        // We need to perform this operation once, not each time `onCreateViewHolder` is called
        private void setupRecyclerHeightIfNeeded(View parent, int cellSize) {
            if (hasBeenSetup) return;
            hasBeenSetup = true;
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            int numOfRows = (int) (totalItemCount / (double) spanCount);
            params.height = numOfRows * cellSize;
            new Handler().post(parent::requestLayout);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int pos) {
            int position = holder.getAdapterPosition() % totalSizeOfItems;
            holder.textView.setText(Integer.toString(position + 1));
        }

        @Override
        public int getItemCount() {
            // this will result the list to be "infinite"
            return Integer.MAX_VALUE;
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}

On output you'll get:

Taking care of the horizontal scroll would require a small amount of changes:

orientation of GridLayoutManager should be changed to HORIZONTAL

inside adapter appropriate width/height setters should be substituted

Other than that - everything should be similar.


问:
CSS3 Styling text transform for multiple words
```<code><li><a>BACKGROUND SCORE</a></li>

i would like to transform this word into

<li><a>Background Score</a></li>

i have tried this

li>a { text-transform: lowercase }
li>a:first-letter { text-transform: capitalize}
</code>```

bt output is changes only frst word of frst letter

```<code><li><a>Background score</a></li>
</code>```

答:
Try do it that way:

```<code><html>
    <head>
        <style>
        li>a { text-transform: lowercase;
        display: inline-block;}
li>a:first-letter { text-transform: capitalize;}
        </style>
    </head>
    <body>
            <li><a>BACKGROUND SCORE</a></li>
    </body>

</html>
</code>```

You will get what you want.

Body:
BACKGROUND SCORE

i would like to transform this word into

Background Score

i have tried this

li>a { text-transform: lowercase }
li>a:first-letter { text-transform: capitalize}

bt output is changes only frst word of frst letter

Background score

Body:
Try do it that way:

<html>
    <head>
        <style>
        li>a { text-transform: lowercase;
        display: inline-block;}
li>a:first-letter { text-transform: capitalize;}
        </style>
    </head>
    <body>
            <li><a>BACKGROUND SCORE</a></li>
    </body>

</html>

You will get what you want.


问:
PHP is_numeric or preg_match 0-9 validation
This isn't a big issue for me (as far as I'm aware), it's more of something that's interested me. But what is the main difference, if any, of using is_numeric over preg_match (or vice versa) to validate user input values.

Example One:

```<code><?php
    $id = $_GET['id'];
    if (!preg_match('/^[0-9]*$/', $id)) {
        // Error
    } else {
        // Continue
    }
?>
</code>```

Example Two:

```<code><?php
    $id = $_GET['id'];
    if (!is_numeric($id)) {
        // Error
    } else {
        // Continue
    }
?>
</code>```

I assume both do exactly the same but is there any specific differences which could cause problems later somehow? Is there a "best way" or something I'm not seeing which makes them different.

答:
You can use this code for number validation:</p>

```<code>if (!preg_match("/^[0-9]+$/i", $phone)) {
        $errorMSG = 'Invalid Number!';
        $error    = 1;
    }
</code>```

Body:
This isn't a big issue for me (as far as I'm aware), it's more of something that's interested me. But what is the main difference, if any, of using is_numeric over preg_match (or vice versa) to validate user input values.

Example One:

<?php
    $id = $_GET['id'];
    if (!preg_match('/^[0-9]*$/', $id)) {
        // Error
    } else {
        // Continue
    }
?>

Example Two:

<?php
    $id = $_GET['id'];
    if (!is_numeric($id)) {
        // Error
    } else {
        // Continue
    }
?>

I assume both do exactly the same but is there any specific differences which could cause problems later somehow? Is there a "best way" or something I'm not seeing which makes them different.

Body:
You can use this code for number validation:

if (!preg_match("/^[0-9]+$/i", $phone)) {
        $errorMSG = 'Invalid Number!';
        $error    = 1;
    }


问:
Why I am receiving duplicate rows in following query , Table structure is attached
How to remove duplicate rows?

Query is->

```<code> SELECT       ps.Project_Brief_Description ,mscd.Brief_Description, Tbl_MilestoneCategory_Master.MileStoneCategory_Name, ps.AR_No_Perm, ptm.ProjectType_Name, mscd.Project_Id, mscd.MilestoneCategory_ID, mscd.MilestoneSubCategory_Id,
                         mscd.MeasurementUnit, mscd.TotalWorkMeasure, mscd.WorkMeasureCompletion, mscd.TaskStartDate, mscd.TaskEndDate, mscd.ActualStartDate, mscd.ActualEndDate, mscd.ReasonForDelay,
                         ps.Project_Id AS Expr1, ps.Executor_Dept_Id, ps.ProjectType_ID,ps.Project_Id, mscd.MilestoneCategory_ID
FROM            Tbl_Project_MilestoneSubCategoryDetails AS mscd INNER JOIN
                         Tbl_Project_Summary AS ps ON mscd.Project_Id = ps.Project_Id INNER JOIN
                         Tbl_Project_Budget AS pb ON ps.Project_Id = pb.Project_Id INNER JOIN
                         Tbl_ProjectType_Master AS ptm ON ps.ProjectType_ID = ptm.ProjectType_Id INNER JOIN
                         Tbl_MilestoneCategory_Master ON mscd.MilestoneCategory_ID = Tbl_MilestoneCategory_Master.MilestoneCategory_Id
</code>```

DataBase Structure snapshot

Kindly note that, table with alias mscd has no primary key

答:
First select distinct row from Tbl_Project_MilestoneSubCategoryDetails- table</p>

```<code> SELECT distinct
   ps.Project_Brief_Description ,
   mscd.Brief_Description,
   Tbl_MilestoneCategory_Master.MileStoneCategory_Name,
   ps.AR_No_Perm,
  ptm.ProjectType_Name,
  mscd.Project_Id,
  mscd.MilestoneCategory_ID,
  mscd.MilestoneSubCategory_Id,
  mscd.MeasurementUnit,
  mscd.TotalWorkMeasure,
  mscd.WorkMeasureCompletion,
  mscd.TaskStartDate,
  mscd.TaskEndDate,
  mscd.ActualStartDate,
  mscd.ActualEndDate,
  mscd.ReasonForDelay,
   ps.Project_Id AS Expr1,
   ps.Executor_Dept_Id,
   ps.ProjectType_ID,
   ps.Project_Id,
   mscd.MilestoneCategory_ID
   FROM
 --First select distinct row from this table
  (SELECT distinct Brief_Description,
  Project_Id,
  MilestoneCategory_ID,
  MilestoneSubCategory_Id,
  MeasurementUnit,
  TotalWorkMeasure,
  WorkMeasureCompletion,
  TaskStartDate,
  TaskEndDate,
  ActualStartDate,
  ActualEndDate,
  ReasonForDelay,
  MilestoneCategory_ID
 from Tbl_Project_MilestoneSubCategoryDetails) AS mscd
 INNER JOIN Tbl_Project_Summary            AS ps
 ON
  mscd.Project_Id = ps.Project_Id
 INNER JOIN Tbl_Project_Budget AS pb
 ON
 ps.Project_Id = pb.Project_Id
INNER JOIN Tbl_ProjectType_Master AS ptm
ON
  ps.ProjectType_ID = ptm.ProjectType_Id
INNER JOIN Tbl_MilestoneCategory_Master
ON
  mscd.MilestoneCategory_ID =
  Tbl_MilestoneCategory_Master.MilestoneCategory_Id
</code>```

Body:
How to remove duplicate rows?

Query is->

 SELECT       ps.Project_Brief_Description ,mscd.Brief_Description, Tbl_MilestoneCategory_Master.MileStoneCategory_Name, ps.AR_No_Perm, ptm.ProjectType_Name, mscd.Project_Id, mscd.MilestoneCategory_ID, mscd.MilestoneSubCategory_Id,
                         mscd.MeasurementUnit, mscd.TotalWorkMeasure, mscd.WorkMeasureCompletion, mscd.TaskStartDate, mscd.TaskEndDate, mscd.ActualStartDate, mscd.ActualEndDate, mscd.ReasonForDelay,
                         ps.Project_Id AS Expr1, ps.Executor_Dept_Id, ps.ProjectType_ID,ps.Project_Id, mscd.MilestoneCategory_ID
FROM            Tbl_Project_MilestoneSubCategoryDetails AS mscd INNER JOIN
                         Tbl_Project_Summary AS ps ON mscd.Project_Id = ps.Project_Id INNER JOIN
                         Tbl_Project_Budget AS pb ON ps.Project_Id = pb.Project_Id INNER JOIN
                         Tbl_ProjectType_Master AS ptm ON ps.ProjectType_ID = ptm.ProjectType_Id INNER JOIN
                         Tbl_MilestoneCategory_Master ON mscd.MilestoneCategory_ID = Tbl_MilestoneCategory_Master.MilestoneCategory_Id

DataBase Structure snapshot

Kindly note that, table with alias mscd has no primary key

Body:
First select distinct row from Tbl_Project_MilestoneSubCategoryDetails- table

 SELECT distinct
   ps.Project_Brief_Description ,
   mscd.Brief_Description,
   Tbl_MilestoneCategory_Master.MileStoneCategory_Name,
   ps.AR_No_Perm,
  ptm.ProjectType_Name,
  mscd.Project_Id,
  mscd.MilestoneCategory_ID,
  mscd.MilestoneSubCategory_Id,
  mscd.MeasurementUnit,
  mscd.TotalWorkMeasure,
  mscd.WorkMeasureCompletion,
  mscd.TaskStartDate,
  mscd.TaskEndDate,
  mscd.ActualStartDate,
  mscd.ActualEndDate,
  mscd.ReasonForDelay,
   ps.Project_Id AS Expr1,
   ps.Executor_Dept_Id,
   ps.ProjectType_ID,
   ps.Project_Id,
   mscd.MilestoneCategory_ID
   FROM
 --First select distinct row from this table
  (SELECT distinct Brief_Description,
  Project_Id,
  MilestoneCategory_ID,
  MilestoneSubCategory_Id,
  MeasurementUnit,
  TotalWorkMeasure,
  WorkMeasureCompletion,
  TaskStartDate,
  TaskEndDate,
  ActualStartDate,
  ActualEndDate,
  ReasonForDelay,
  MilestoneCategory_ID
 from Tbl_Project_MilestoneSubCategoryDetails) AS mscd
 INNER JOIN Tbl_Project_Summary            AS ps
 ON
  mscd.Project_Id = ps.Project_Id
 INNER JOIN Tbl_Project_Budget AS pb
 ON
 ps.Project_Id = pb.Project_Id
INNER JOIN Tbl_ProjectType_Master AS ptm
ON
  ps.ProjectType_ID = ptm.ProjectType_Id
INNER JOIN Tbl_MilestoneCategory_Master
ON
  mscd.MilestoneCategory_ID =
  Tbl_MilestoneCategory_Master.MilestoneCategory_Id


问:
ASP.NET validation: gathering information from client-side validation
I'd like to implement ajax message box that will gather information from validators on a page when client-side validation fires.
Like: I have left some text fields blank then press submit button and appropriate RequiredFieldValidators show messages. I would like my message box shows those messages too. I am looking for appropriate way to hook on validators JS event or something.

Thanks!

答:
Would something like this fit the bill?

http://wiki.asp.net/page.aspx/308/validationsummary/


问:
Pandas extracting substring
I have a column containing dates, which could look like 2017-10-12. I want to create a new column containing the day, which in my case would be the number between the two -'s. I've tried various .str.extract() queries, but I can't seem to get it right.

```<code>df['days'] = df['dates'].str.extract('(-*)')
</code>```

Any hints?

答:
Use split and select second list by str[1]:

```<code>df['days'] = df['dates'].str.split('-').str[1]
</code>```

Or to_datetime with format parameter + dt.day:

```<code>df['days'] = pd.to_datetime(df['dates'], format='%Y-%d-%m').dt.day
</code>```

Title: Pandas extracting substring

Body:
I have a column containing dates, which could look like 2017-10-12. I want to create a new column containing the day, which in my case would be the number between the two -'s. I've tried various .str.extract() queries, but I can't seem to get it right.

df['days'] = df['dates'].str.extract('(-*)')

Any hints?

Body:
Use split and select second list by str[1]:

df['days'] = df['dates'].str.split('-').str[1]

Or to_datetime with format parameter + dt.day:

df['days'] = pd.to_datetime(df['dates'], format='%Y-%d-%m').dt.day


问:
glmnet: Convert predicted probabilities to predicted classes
I ran cv.glmnet using a Poisson distribution for a binary outcome. The predict function returns predicted probabilities, but not predicted classes. How do I convert the probabilities into classes so I might generate a confusionMatrix to determine AUC, etc.? NB. At least one predicted probability is > 1.

```<code>cv <- cv.glmnet(deriv.x, deriv.y, foldid = foldid, weights = wts, family = "poisson")
pred <- predict.cv.glmnet(cv, newx = valid.x, s = "lambda.min", "response")
confusionMatrix(pred, valid.y)
Error in confusionMatrix.default(pred, valid.y) :
  the data cannot have more levels than the reference
</code>```

答:
It's because you're returning probabilities, not classes, so try it:

```<code>cv <- cv.glmnet(deriv.x, deriv.y, foldid = foldid, weights = wts, family = "poisson")
pred <- predict.cv.glmnet(cv, newx = valid.x, s = "lambda.min", "response")

pred <- ifelse(pred > 0.5,1,0)

confusionMatrix(pred, valid.y)
</code>```

You can choose your own value for rounding off.

Body:
I ran cv.glmnet using a Poisson distribution for a binary outcome. The predict function returns predicted probabilities, but not predicted classes. How do I convert the probabilities into classes so I might generate a confusionMatrix to determine AUC, etc.? NB. At least one predicted probability is > 1.

cv <- cv.glmnet(deriv.x, deriv.y, foldid = foldid, weights = wts, family = "poisson")
pred <- predict.cv.glmnet(cv, newx = valid.x, s = "lambda.min", "response")
confusionMatrix(pred, valid.y)
Error in confusionMatrix.default(pred, valid.y) :
  the data cannot have more levels than the reference

Body:
It's because you're returning probabilities, not classes, so try it:

cv <- cv.glmnet(deriv.x, deriv.y, foldid = foldid, weights = wts, family = "poisson")
pred <- predict.cv.glmnet(cv, newx = valid.x, s = "lambda.min", "response")

pred <- ifelse(pred > 0.5,1,0)

confusionMatrix(pred, valid.y)

You can choose your own value for rounding off.


问:
Storing data in a table
I am trying to create a user table for my website, where the user can see their first name and last name in a table after they register and login. The user detail is stored in the HTML5 Local Storage. Is there a better way to update the table with more users, rather than creating more .

Here is my table:

```<code><table id="rankTable">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Top Score</th>
    </tr>
    <tr>
        <td id="_firstName"></td>
        <td id="_lastName"></td>
        <td></td>
    </tr>
</table>
</code>```

Here is the full working snippet: https://jsfiddle.net/MuddasarAshfaq/r62zmjw4/9/

答:
Assuming that u have stored your stored firstname and lastname as "fname" and "lname" in your localStorage</p>

```<code>var table = document.getElementById("rankTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = localStorage.getItem("fname");
cell2.innerHTML = localStorage.getItem("lname");
</code>```

Title: Storing data in a table

Body:
I am trying to create a user table for my website, where the user can see their first name and last name in a table after they register and login. The user detail is stored in the HTML5 Local Storage. Is there a better way to update the table with more users, rather than creating more .

Here is my table:

        First Name
        Last Name
        Top Score

Here is the full working snippet: https://jsfiddle.net/MuddasarAshfaq/r62zmjw4/9/

Body:
Assuming that u have stored your stored firstname and lastname as "fname" and "lname" in your localStorage

var table = document.getElementById("rankTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = localStorage.getItem("fname");
cell2.innerHTML = localStorage.getItem("lname");


问:
Getting Started with Unreal Engine
I am new to game development. I had recently worked with Unity 3D but its not free so I switched over to Unreal Engine. Documentation on Epic Games's website is not in detail and hard to understand for new game developers. </p>

答:
When I was new to Unreal Engine, I looked into the following video playlist.
Have a look. It is collection of 208 Videos.

https://www.youtube.com/playlist?list=PLZlv_N0_O1gaCL2XjKluO7N2Pmmw9pvhE

Title: Getting Started with Unreal Engine


问:
Weblogic JMS client threads stuck while refreshing connection
Greetings,

We are using Spring to integrate with Weblogic JMS server using wlfullclient.jar. Every once in a while, the jmsListenerthreads get stuck. We have observed that this happens while refreshing the connection.

Versions used:
wlfullClient.jar : 10.0.1
Spring : 3.0.3

Stack trace for a couple of stuck threads:

```<code>    Name: jmsListenerContainer-1770
State: WAITING on weblogic.jms.client.JMSSession@35c0fb37
Total blocked: 3,681  Total waited: 3,664

Stack trace:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:485)
weblogic.jms.client.JMSSession.waitForState(JMSSession.java:4239)
weblogic.jms.client.JMSSession.close(JMSSession.java:1259)
weblogic.jms.client.JMSConnection.closeSessions(JMSConnection.java:1076)
weblogic.jms.client.JMSConnection.mergedCloseAndOnException(JMSConnection.java:950)
   - locked weblogic.jms.client.JMSConnection@3263f76c
weblogic.jms.client.JMSConnection.close(JMSConnection.java:763)
weblogic.jms.client.ReconnectController.close(ReconnectController.java:426)
org.springframework.jms.connection.ConnectionFactoryUtils.releaseConnection(ConnectionFactoryUtils.java:80)
org.springframework.jms.listener.AbstractJmsListeningContainer.refreshSharedConnection(AbstractJmsListeningContainer.java:385)
   - locked java.lang.Object@51ce8880
org.springframework.jms.listener.DefaultMessageListenerContainer.refreshConnectionUntilSuccessful(DefaultMessageListenerContainer.java:856)
org.springframework.jms.listener.DefaultMessageListenerContainer.recoverAfterListenerSetupFailure(DefaultMessageListenerContainer.java:838)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:969)
   - locked java.lang.Object@c2330fa
java.lang.Thread.run(Thread.java:619)

Name: jmsListenerContainer-1755
State: TIMED_WAITING on java.lang.Object@b5c4560
Total blocked: 3,588  Total waited: 3,605

Stack trace:
java.lang.Object.wait(Native Method)
weblogic.jms.client.ReconnectController.waitForStateInternal(ReconnectController.java:309)
weblogic.jms.client.ReconnectController.analyzeExceptionAndReconnect(ReconnectController.java:525)
weblogic.jms.client.ReconnectController.computeJMSConsumer(ReconnectController.java:652)
weblogic.jms.client.WLConsumerImpl.receive(WLConsumerImpl.java:166)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveMessage(AbstractPollingMessageListenerContainer.java:405)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:308)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:261)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1056)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1048)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:947)
java.lang.Thread.run(Thread.java:619)

Name: jmsListenerContainer-1732
State: BLOCKED on java.lang.Object@51ce8880 owned by: jmsListenerContainer-1770
Total blocked: 3,586  Total waited: 3,584

Stack trace:
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.clearResources(DefaultMessageListenerContainer.java:1096)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:958)
java.lang.Thread.run(Thread.java:619)
</code>```

Spring configurations:

```<code><bean id="messageListener"
  class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
  <constructor-arg>
   <bean class="com.eharmony.matching.mnssender.jms.DefaultDtoDelegate" />
  </constructor-arg>
  <property name="defaultListenerMethod" value="receive" />
  <property name="messageConverter">
   <bean class="com.eharmony.matching.mnssender.jms.Converter" />
  </property>
 </bean>

 <bean id="jmsListenerContainer"
  class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="concurrentConsumers" value="${MNSClient.jms.concurrent.consumers}" />
  <property name="connectionFactory" ref="jmsQueueConnectionFactory" />
  <property name="destination" ref="queue" />
  <property name="sessionTransacted" value="true" />
  <property name="messageListener" ref="messageListener" />
 </bean>

 <bean id="jmsQueueConnectionFactory"
  class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
  <property name="targetConnectionFactory">
   <ref bean="internalJmsQueueConnectionFactory" />
  </property>
  <property name="username">
   <value>${MNSClient.receive.jms.user}</value>
  </property>
  <property name="password">
   <value>${MNSClient.receive.jms.password}</value>
  </property>
 </bean>

 <bean id="internalJmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate" />
  </property>
  <property name="jndiName">
   <value>${MNSClient.receive.jms.connectionFactoryName}</value>
  </property>
 </bean>

 <!-- RECEIVING JMS MESSAGE -->
 <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
  <property name="environment">
   <props>
    <prop key="java.naming.factory.initial">${MNSClient.receive.jms.initialFactoryName}</prop>
    <prop key="java.naming.provider.url">${MNSClient.receive.jms.providerUrl}</prop>
   </props>
  </property>
 </bean>
 <bean id="queue" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate" />
  </property>
  <property name="jndiName">
   <value>${MNSClient.receive.jms.queueName}</value>
  </property>
 </bean>
</code>```

Any pointers will be highly appreciated!

Regards.

答:
Are both those threads calling methods on the same Session (or Consumer/Producer derived from the same session)?  Session and anything derived from it (Producer, Consumer, etc) are not thread-safe, so you need to protect against multiple threads simultaneously operating on them.  Either by serializing access through your own locking or by creating different Sessions for each Producer/Consumer.

Don't forget the implicit thread involved in async message processing (onMessage() use) when counting whether you're accessing a session from multiple threads.

If you're violating that rule, expect bad things (like deadlocks).

Body:
Greetings,

We are using Spring to integrate with Weblogic JMS server using wlfullclient.jar. Every once in a while, the jmsListenerthreads get stuck. We have observed that this happens while refreshing the connection.

Versions used:
wlfullClient.jar : 10.0.1
Spring : 3.0.3

Stack trace for a couple of stuck threads:

    Name: jmsListenerContainer-1770
State: WAITING on weblogic.jms.client.JMSSession@35c0fb37
Total blocked: 3,681  Total waited: 3,664

Stack trace:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:485)
weblogic.jms.client.JMSSession.waitForState(JMSSession.java:4239)
weblogic.jms.client.JMSSession.close(JMSSession.java:1259)
weblogic.jms.client.JMSConnection.closeSessions(JMSConnection.java:1076)
weblogic.jms.client.JMSConnection.mergedCloseAndOnException(JMSConnection.java:950)
   - locked weblogic.jms.client.JMSConnection@3263f76c
weblogic.jms.client.JMSConnection.close(JMSConnection.java:763)
weblogic.jms.client.ReconnectController.close(ReconnectController.java:426)
org.springframework.jms.connection.ConnectionFactoryUtils.releaseConnection(ConnectionFactoryUtils.java:80)
org.springframework.jms.listener.AbstractJmsListeningContainer.refreshSharedConnection(AbstractJmsListeningContainer.java:385)
   - locked java.lang.Object@51ce8880
org.springframework.jms.listener.DefaultMessageListenerContainer.refreshConnectionUntilSuccessful(DefaultMessageListenerContainer.java:856)
org.springframework.jms.listener.DefaultMessageListenerContainer.recoverAfterListenerSetupFailure(DefaultMessageListenerContainer.java:838)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:969)
   - locked java.lang.Object@c2330fa
java.lang.Thread.run(Thread.java:619)

Name: jmsListenerContainer-1755
State: TIMED_WAITING on java.lang.Object@b5c4560
Total blocked: 3,588  Total waited: 3,605

Stack trace:
java.lang.Object.wait(Native Method)
weblogic.jms.client.ReconnectController.waitForStateInternal(ReconnectController.java:309)
weblogic.jms.client.ReconnectController.analyzeExceptionAndReconnect(ReconnectController.java:525)
weblogic.jms.client.ReconnectController.computeJMSConsumer(ReconnectController.java:652)
weblogic.jms.client.WLConsumerImpl.receive(WLConsumerImpl.java:166)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveMessage(AbstractPollingMessageListenerContainer.java:405)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:308)
org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:261)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1056)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1048)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:947)
java.lang.Thread.run(Thread.java:619)

Name: jmsListenerContainer-1732
State: BLOCKED on java.lang.Object@51ce8880 owned by: jmsListenerContainer-1770
Total blocked: 3,586  Total waited: 3,584

Stack trace:
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.clearResources(DefaultMessageListenerContainer.java:1096)
org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:958)
java.lang.Thread.run(Thread.java:619)

Spring configurations:

<bean id="messageListener"
  class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
  <constructor-arg>
   <bean class="com.eharmony.matching.mnssender.jms.DefaultDtoDelegate" />
  </constructor-arg>
  <property name="defaultListenerMethod" value="receive" />
  <property name="messageConverter">
   <bean class="com.eharmony.matching.mnssender.jms.Converter" />
  </property>
 </bean>

 <bean id="jmsListenerContainer"
  class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="concurrentConsumers" value="${MNSClient.jms.concurrent.consumers}" />
  <property name="connectionFactory" ref="jmsQueueConnectionFactory" />
  <property name="destination" ref="queue" />
  <property name="sessionTransacted" value="true" />
  <property name="messageListener" ref="messageListener" />
 </bean>

 <bean id="jmsQueueConnectionFactory"
  class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
  <property name="targetConnectionFactory">
   <ref bean="internalJmsQueueConnectionFactory" />
  </property>
  <property name="username">
   <value>${MNSClient.receive.jms.user}</value>
  </property>
  <property name="password">
   <value>${MNSClient.receive.jms.password}</value>
  </property>
 </bean>

 <bean id="internalJmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate" />
  </property>
  <property name="jndiName">
   <value>${MNSClient.receive.jms.connectionFactoryName}</value>
  </property>
 </bean>

 <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
  <property name="environment">
   <props>
    <prop key="java.naming.factory.initial">${MNSClient.receive.jms.initialFactoryName}</prop>
    <prop key="java.naming.provider.url">${MNSClient.receive.jms.providerUrl}</prop>
   </props>
  </property>
 </bean>
 <bean id="queue" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate" />
  </property>
  <property name="jndiName">
   <value>${MNSClient.receive.jms.queueName}</value>
  </property>
 </bean>

Any pointers will be highly appreciated!

Regards.


问:
expect: Parse variables from stdin
I am running an expect script that will generate some dynamic input coming from stdin.

Is there a way/pattern that addresses the concept of reading from the stdin and storing (?) somewhere the relevant input to be processed/parsed in a latter step?

example:

```<code>./myexpectscript.sh arg1 arg2 ..

Running command with id 9494
Running command with id 9494
Running command with id 9494
Running command with id 9494
Command execution finished
</code>```

I actually want to store the above id,9494.

The script actually runs an api call to a remote server and has a duration of several seconds (for what that matters).

edit: the following snippet does not seem to resolve the issue:

```<code>expect -re Running command with id [0-9]+

set output \$expect_out(1,string)
</code>```

as it gives me an error:

```<code>invalid command name "0-9"
    while executing
"0-9"
    invoked from within
"expect -re Running command with id [0-9]+"
    (file "./myexpectscript.sh" line 17)
</code>```

have also tried it with quotes, i.e.

```<code>expect -re "Running command with id [0-9]+"
</code>```

答:
Use {...} to define your regex, use \d for decimal number, and capture the string with (...).

Set a variable with the captured string with $expect_out.

```<code>expect -re {Running command with id (\d+)} {
    set cmd_id $expect_out(1,string)
}
puts $cmd_id
</code>```

Title: expect: Parse variables from stdin

Body:
I am running an expect script that will generate some dynamic input coming from stdin.

Is there a way/pattern that addresses the concept of reading from the stdin and storing (?) somewhere the relevant input to be processed/parsed in a latter step?

example:

./myexpectscript.sh arg1 arg2 ..

Running command with id 9494
Running command with id 9494
Running command with id 9494
Running command with id 9494
Command execution finished

I actually want to store the above id,9494.

The script actually runs an api call to a remote server and has a duration of several seconds (for what that matters).

edit: the following snippet does not seem to resolve the issue:

expect -re Running command with id [0-9]+

set output \$expect_out(1,string)

as it gives me an error:

invalid command name "0-9"
    while executing
"0-9"
    invoked from within
"expect -re Running command with id [0-9]+"
    (file "./myexpectscript.sh" line 17)

have also tried it with quotes, i.e.

expect -re "Running command with id [0-9]+"

Body:
Use {...} to define your regex, use \d for decimal number, and capture the string with (...).

Set a variable with the captured string with $expect_out.

expect -re {Running command with id (\d+)} {
    set cmd_id $expect_out(1,string)
}
puts $cmd_id


问:
How to check session expiration on close of browser in Django?
Here is the scenario I wish to handle in Django application

User logs in web application.

SESSION_EXPIRE_AT_BROWSER_CLOSE is set to true.

User closes the browser window.

Now how to know receive the session info that session has been killed/Destroyed?

答: Obviously, you can't know that in Django since it is up to the browser to remove the cookie when session ends (browser is closed). If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, cookie will not include Expire value, which specifies lifetime of the cookie, and will thus be removed by browser when session ends.


问:
Where can I to write my logic in APIView?
In the CreateAPIView I can override the create method to add my logic:

```<code>class OpenstackAccountCreateAPIView(CreateAPIView):
    """
    create openstack account
    """
    serializer_class = OpenstackAccountCreateSerializer

    def create(self, request, *args, **kwargs):
        # put my logic here
        ......
</code>```

But if I have a APIView, where can I to write my logic?

```<code>class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer
    # where can I put my login logic?
</code>```

My OpenstackAccountLoginSerializer in serializers.py:

```<code>class OpenstackAccountLoginSerializer(Serializer):
    password = serializers.CharField()
</code>```

答:
You can overide the method of the verb you want. Probably to create an account you'll want POST. Like this:

```<code>class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer

    def post(self, request, format=None):
        # Logic goes here, defining resp with whatever you want to respond.
        return Response(resp)
</code>```

Than you can call it with the POST verb, same as when using create with CreateAPIView as in the documentation here.

Body:
In the CreateAPIView I can override the create method to add my logic:

class OpenstackAccountCreateAPIView(CreateAPIView):
    """
    create openstack account
    """
    serializer_class = OpenstackAccountCreateSerializer

    def create(self, request, *args, **kwargs):
        # put my logic here
        ......

But if I have a APIView, where can I to write my logic?

class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer
    # where can I put my login logic?

My OpenstackAccountLoginSerializer in serializers.py:

class OpenstackAccountLoginSerializer(Serializer):
    password = serializers.CharField()

Body:
You can overide the method of the verb you want. Probably to create an account you'll want POST. Like this:

class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer

    def post(self, request, format=None):
        # Logic goes here, defining resp with whatever you want to respond.
        return Response(resp)

Than you can call it with the POST verb, same as when using create with CreateAPIView as in the documentation here.


问:
Spring cloud - Zuul cannot set timeout
I have a zuul server with a config file as:

```<code>server:
  port: 9090
eureka:
  client:
    serviceUrl:
      defaultZone: http://172.16.5.147:8761/eureka/
  instance:
    leaseRenewalIntervalInSeconds: 30
    hostname: dev-zuulserver
    non-secure-port: 80
zuul:
          prefix: /v1
          sensitiveHeaders: Cookie, Set-Cookie
          ignoredHeaders: Access-Control-Allow-Origin
          host:
            connect-timeout-millis: 60000 # starting the connection
            socket-timeout-millis: 120000  # monitor the continuous incoming data flow
        ribbon:
          eureka:
            enabled: true
            ReadTimeout: 120000
            ConnectTimeout: 3000
        hystrix:
          command:
            default:
              execution:
                isolation:
                  strategy: THREAD
                  thread:
                    timeoutInMilliseconds: 60000
</code>```

And I have some queries with longer timeout (more than one minute). But, all my requests always error out with a time out, request time always is less than 6000 ms.

And zuul show this exception:

Caused by: java.lang.RuntimeException: java.net.SocketTimeoutException: Read timed out

at rx.exceptions.Exceptions.propagate(Exceptions.java:58) ~[rxjava-1.1.10.jar!/:1.1.10]

  at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:465) ~[rxjava-1.1.10.jar!/:1.1.10]
              at rx.observables.BlockingObservable.single(BlockingObservable.java:342) ~[rxjava-1.1.10.jar!/:1.1.10]
              at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:117) ~[ribbon-loadbalancer-2.2.2.jar!/:2.2.2]
              ... 133 common frames omitted
      Caused by: java.net.SocketTimeoutException: Read timed out
              at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_131]
              at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_131]
              at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_131]
              at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_131]
              at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:282) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:165) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) ~[httpcore-4.4.6.jar!/:4.4.6]

Does anyone have a solution for this case?

Thank you!

答:
Try by adding timeout for Ribbon in ZUUL config.

Following will set timeout of 2min.

```<code>ribbon:
  ConnectTimeout: 120000
  ReadTimeout: 120000
</code>```

Title: Spring cloud - Zuul cannot set timeout

Body:
I have a zuul server with a config file as:

server:
  port: 9090
eureka:
  client:
    serviceUrl:
      defaultZone: http://172.16.5.147:8761/eureka/
  instance:
    leaseRenewalIntervalInSeconds: 30
    hostname: dev-zuulserver
    non-secure-port: 80
zuul:
          prefix: /v1
          sensitiveHeaders: Cookie, Set-Cookie
          ignoredHeaders: Access-Control-Allow-Origin
          host:
            connect-timeout-millis: 60000 # starting the connection
            socket-timeout-millis: 120000  # monitor the continuous incoming data flow
        ribbon:
          eureka:
            enabled: true
            ReadTimeout: 120000
            ConnectTimeout: 3000
        hystrix:
          command:
            default:
              execution:
                isolation:
                  strategy: THREAD
                  thread:
                    timeoutInMilliseconds: 60000

And I have some queries with longer timeout (more than one minute). But, all my requests always error out with a time out, request time always is less than 6000 ms.

And zuul show this exception:

Caused by: java.lang.RuntimeException: java.net.SocketTimeoutException: Read timed out

at rx.exceptions.Exceptions.propagate(Exceptions.java:58) ~[rxjava-1.1.10.jar!/:1.1.10]

  at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:465) ~[rxjava-1.1.10.jar!/:1.1.10]
              at rx.observables.BlockingObservable.single(BlockingObservable.java:342) ~[rxjava-1.1.10.jar!/:1.1.10]
              at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:117) ~[ribbon-loadbalancer-2.2.2.jar!/:2.2.2]
              ... 133 common frames omitted
      Caused by: java.net.SocketTimeoutException: Read timed out
              at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_131]
              at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_131]
              at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_131]
              at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_131]
              at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:282) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:165) ~[httpclient-4.5.3.jar!/:4.5.3]
              at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273) ~[httpcore-4.4.6.jar!/:4.4.6]
              at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) ~[httpcore-4.4.6.jar!/:4.4.6]

Does anyone have a solution for this case?

Thank you!

Body:
Try by adding timeout for Ribbon in ZUUL config.

Following will set timeout of 2min.

ribbon:
  ConnectTimeout: 120000
  ReadTimeout: 120000


问:
Create an Item/Project Template in Visual Studio
I'm trying to figure out how to create an Item Template but according to the online articles I've encountered so far, all of the articles point you to an Export Template Wizard tool under the File menu option.  My problem is that this feature doesn't exist and I can't seem to find it.

I'm using Visual Studio Team System 2008.

So I'm wondering a couple of things.  Does VSTS 2008 not include this option intentionally?  Or do you go about creating Item/Project templates in a different manner?

答: Using VS 2010 you can do lot more...You can get the complete example implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample</p>

OwnerDisplayName: coson


问:
Xcode UI Testing: Automatically taking snapshot when predicates fail?
Xcode UI Testing takes automatic screenshots for viewing in the results navigator whenever a test fails, which is greatly helpful. However, that does not include tests that fail because a predicate is failed. Since predicates are often for basic checks (such as if an element exists or not on a current view), that is a huge drawback because a screenshot would be useful in diagnosing what was happening in the app when the test failed.

Does anyone know how to force a screenshot? Does this require integrating the Fastlane Snapshot tool?

答:
On tearDown you can check if test failed (that's helpful if you are not discarding screenshots when tests pass.)

```<code>if let failureCount = testRun?.failureCount, failureCount > 0 {
  takeScreenshot()
}
</code>```

If you are using Xcode 9 already, the takeScreenshot function can use the new API (If not, then use the workaround mentioned by the other answer) :

```<code>let screenshot = XCUIScreen.main.screenshot()
let attach = XCTAttachment(screenshot: screenshot)
add(attach)
</code>```

You can also name the attach and change its lifetime ;)

See Apple's documentation for how to use and where to find them (the "Report navigator" in View > Navigators > Reports) in more detail.

Body:
On tearDown you can check if test failed (that's helpful if you are not discarding screenshots when tests pass.)

if let failureCount = testRun?.failureCount, failureCount > 0 {
  takeScreenshot()
}

If you are using Xcode 9 already, the takeScreenshot function can use the new API (If not, then use the workaround mentioned by the other answer) :

let screenshot = XCUIScreen.main.screenshot()
let attach = XCTAttachment(screenshot: screenshot)
add(attach)

You can also name the attach and change its lifetime ;)

See Apple's documentation for how to use and where to find them (the "Report navigator" in View > Navigators > Reports) in more detail.


问:
how to replace char with other in hexdecimal
I'm a new user who using mainframe, I have a file and I need to change all dots '.' in file with space, I was trying to write this statement on command </p>

```<code>change X'05' X'40' all
</code>```

<p>after I converted the file to hexdecimal, but It doesn't work.
How can I change all the dots with space in file, in simple way please? </p>

答:
The dots are non-displayable characters. You can match them using picture strings in the ISPF editor (which is what I assume you're trying to use to edit the file?)

Try the command

```<code>change p'.' ' ' all
</code>```

The "p'.'" part will match any non-displayable character and change it to a blank.

Body:
I'm a new user who using mainframe, I have a file and I need to change all dots '.' in file with space, I was trying to write this statement on command

change X'05' X'40' all

after I converted the file to hexdecimal, but It doesn't work.
How can I change all the dots with space in file, in simple way please?

Body:
The dots are non-displayable characters. You can match them using picture strings in the ISPF editor (which is what I assume you're trying to use to edit the file?)

Try the command

change p'.' ' ' all

The "p'.'" part will match any non-displayable character and change it to a blank.


问:
Plotting a 2D gaussian in MATLAB in one color but varaying levels of transparency
I want to plot 2D representation of a Gaussian wave function in MATLAB. I want the 2D plot to be in one color (green), which gets transparent away from the center of the Gaussian.

When I use imagesc (like in the next code) I get a Gaussian over a black square (as shown in the figure below).

I do not want the black backgrount, and I want the Gaussian to be in one color, but gets transparent away from the center, so that I won't get the black square, only green circle (over a white background) where the circle gets transparent away from its center.

How can I do that ???

```<code>close all;clc

figure
xlim_min=-4;
xlim_max=4;
ylim_min=-4;
ylim_max=4;

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])

x=-1:0.001:1;
y=-1:0.001:1;
[X,Y]=meshgrid(x,y);

c1=10;
c1_new=c1*0.3;
x_offset=0;
y_offset=0;

w_function=0.5*0.25*exp(-c1_new*((X+x_offset).^2+...
                                      (Y+y_offset).^2));

imagesc(x,y,w_function);

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])
</code>```

答:
To obtain transparency, use the AlphaData and AlphaDataMapping properties of the image. In the following, I'm explicitly computing the transparency (alpha) as an affine function of the data values, in order to specify minimum and maximum transparency values; and I set AlphaDataMapping to none so those values are used without any modifications.

So, replace your line

imagesc(x,y,w_function);

by

```<code>min_alpha = .2; % desired minimum alpha
max_alpha = 1; % desired maximum alpha
alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha
</code>```

Note how the blue part is more transparent (smaller alpha) than the yellow part.

To have the color blend smoothly with the outer region, set a mininum alpha of 0 and define the function on a larger grid. You can also change the colormap if desired. Since the transparency already varies, you probably want constant color in the colormap.

```<code>close all;clc

figure
xlim_min=-4;
xlim_max=4;
ylim_min=-4;
ylim_max=4;

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])

x=-2:0.001:2; % large enough that the function approximately ...
y=-2:0.001:2; % ... reaches 0 within this rectangle
[X,Y]=meshgrid(x,y);

c1=10;
c1_new=c1*0.3;
x_offset=0;
y_offset=0;

w_function=0.5*0.25*exp(-c1_new*((X+x_offset).^2+...
                                      (Y+y_offset).^2));

min_alpha = 0; % desired minimum alpha: set to 0
max_alpha = 1; % desired maximum alpha
alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha
cm = [0 .7 0]; % define colormap: single color, dark green
colormap(cm) % apply colormap

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])
</code>```

Body:
I want to plot 2D representation of a Gaussian wave function in MATLAB. I want the 2D plot to be in one color (green), which gets transparent away from the center of the Gaussian.

When I use imagesc (like in the next code) I get a Gaussian over a black square (as shown in the figure below).

I do not want the black backgrount, and I want the Gaussian to be in one color, but gets transparent away from the center, so that I won't get the black square, only green circle (over a white background) where the circle gets transparent away from its center.

How can I do that ???

close all;clc

figure
xlim_min=-4;
xlim_max=4;
ylim_min=-4;
ylim_max=4;

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])

x=-1:0.001:1;
y=-1:0.001:1;
[X,Y]=meshgrid(x,y);

c1=10;
c1_new=c1*0.3;
x_offset=0;
y_offset=0;

w_function=0.5*0.25*exp(-c1_new*((X+x_offset).^2+...
                                      (Y+y_offset).^2));

imagesc(x,y,w_function);

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])

Body:
To obtain transparency, use the AlphaData and AlphaDataMapping properties of the image. In the following, I'm explicitly computing the transparency (alpha) as an affine function of the data values, in order to specify minimum and maximum transparency values; and I set AlphaDataMapping to none so those values are used without any modifications.

So, replace your line

imagesc(x,y,w_function);

by

min_alpha = .2; % desired minimum alpha
max_alpha = 1; % desired maximum alpha
alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha

Note how the blue part is more transparent (smaller alpha) than the yellow part.

To have the color blend smoothly with the outer region, set a mininum alpha of 0 and define the function on a larger grid. You can also change the colormap if desired. Since the transparency already varies, you probably want constant color in the colormap.

close all;clc

figure
xlim_min=-4;
xlim_max=4;
ylim_min=-4;
ylim_max=4;

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])

x=-2:0.001:2; % large enough that the function approximately ...
y=-2:0.001:2; % ... reaches 0 within this rectangle
[X,Y]=meshgrid(x,y);

c1=10;
c1_new=c1*0.3;
x_offset=0;
y_offset=0;

w_function=0.5*0.25*exp(-c1_new*((X+x_offset).^2+...
                                      (Y+y_offset).^2));

min_alpha = 0; % desired minimum alpha: set to 0
max_alpha = 1; % desired maximum alpha
alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha
cm = [0 .7 0]; % define colormap: single color, dark green
colormap(cm) % apply colormap

ylim([ylim_min ylim_max])
xlim([xlim_min xlim_max])


问:
Hero Unit Styles not being applied
I am starting a conversation of a psd to html using bootstrap but my hero unit is not getting its default style

        <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.css" >

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

          Get Started

        Learn More

    ```

You will see here in the image its getting the style of the images ok but ntot the hero unit does anybody have an idea as to why?.

答:
Perhaps you are refering to this CSS: https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css

In case you want to use the hero-unit class, which is bootstrap v2, stylesheet this one.

If you use bootstrap 3, i suggest to use jumbotron as scaisEdge noticed.

If this did not answer your question, you might want to create your own CSS so you can style it the way you want it.

Title: Hero Unit Styles not being applied

Body:
I am starting a conversation of a psd to html using bootstrap but my hero unit is not getting its default style

        <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.css" >

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

          Get Started

        Learn More

You will see here in the image its getting the style of the images ok but ntot the hero unit does anybody have an idea as to why?.


问:
how to capture Build Info using Gradle and Spring Boot
I am trying to get access to build info values such as version in my Java main application using Spring Boot and Gradle.

I can't find any documentation / examples of how to configure the

build.gradle

application.yml (if required)

Java main class

could someone please help with a small code example for the above files.

In my build.gradle file I will have the version entry, so how to get this into Java main class using Spring Boot and Gradle.

build.gradle

```<code>version=0.0.1-SNAPSHOT
</code>```

I've tried adding

build.gradle

```<code>apply plugin: 'org.springframework.boot'

springBoot {
    buildInfo()
}
</code>```

but the buildInfo() isn't recognised as a keyword in Intellij

In my Java main class I have the following:

```<code>public class MyExampleApplication implements CommandLineRunner {
    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(MyExampleApplication.class, args);
    }

    @Override
    public void run(String[] args) throws Exception{
        Environment env = (Environment) context.getBean("environment");
        displayInfo(env);
    }

    private static void displayInfo(Environment env) {
       log.info("build version is <" + env.getProperty("version")
    }
</code>```

But when I run this - the output from env.getProperty("version") is showing as null.

答:
Spring Boot auto-configures a BuildProperties bean with the information generated by buildInfo().

So to get the information use context.getBean(BuildProperties.class).getVersion();.

Body:
I am trying to get access to build info values such as version in my Java main application using Spring Boot and Gradle.

I can't find any documentation / examples of how to configure the

build.gradle

application.yml (if required)

Java main class

could someone please help with a small code example for the above files.

In my build.gradle file I will have the version entry, so how to get this into Java main class using Spring Boot and Gradle.

build.gradle

version=0.0.1-SNAPSHOT

I've tried adding

build.gradle

apply plugin: 'org.springframework.boot'

springBoot {
    buildInfo()
}

but the buildInfo() isn't recognised as a keyword in Intellij

In my Java main class I have the following:

public class MyExampleApplication implements CommandLineRunner {
    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(MyExampleApplication.class, args);
    }

    @Override
    public void run(String[] args) throws Exception{
        Environment env = (Environment) context.getBean("environment");
        displayInfo(env);
    }

    private static void displayInfo(Environment env) {
       log.info("build version is <" + env.getProperty("version")
    }

But when I run this - the output from env.getProperty("version") is showing as null.


问:
Django qs1.difference(qs2, qs3) not supported by backend
I need to check a table from a remote db and update another table in my db. The models have same fields but checking with difference method will return an error:

qs1 get the data from one postgresql db

qs2 get the data from one mysql db

```<code>qs1 = (Local.objects
            .values_list('ref')
)
qs2 = (Remote.objects
            .filter()
            .values_list('ref'))

>>> qs1.difference(qs1, qs2)
</code>```

DatabaseError: intersection not supported on this database backend.

答:
```<code>check = Qs1.objects.all()
prg=[]
[prg.append(x.ref) for x in check]
difference = (Qs2.objects
        .exclude(ref__in=prg)
        .values()
)
</code>```

Maybe it's not elegant, but it just works.

Body:
I need to check a table from a remote db and update another table in my db. The models have same fields but checking with difference method will return an error:

qs1 get the data from one postgresql db

qs2 get the data from one mysql db

qs1 = (Local.objects
            .values_list('ref')
)
qs2 = (Remote.objects
            .filter()
            .values_list('ref'))

>>> qs1.difference(qs1, qs2)

DatabaseError: intersection not supported on this database backend.

Body:
check = Qs1.objects.all()
prg=[]
[prg.append(x.ref) for x in check]
difference = (Qs2.objects
        .exclude(ref__in=prg)
        .values()
)

Maybe it's not elegant, but it just works.