问:
How to iterate through array of arrays on Rails template?
I've got an array in the following form:

```<code>[["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
</code>```

Is there a way to somehow display this information on a Rails template using iterators? I need something like this:

First - a, b, c

Second - d, e,

Third - g, h, i.

Or this is impossible and I should modify the initial array form?

Thanks in advance.

答:
Without modifing the main array you could try with each_with_index inside each for the main array of arrays, then checking for the first value you can skip it and get the array of letters:

```<code>array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]

array.each do |main|
  main.each_with_index do |value, index|
    next if index.zero?
    p value
  end
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]
</code>```

Or if you want to access it as a hash it'd be easier:

```<code>array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
array.to_h.each do |_, value|
  p value
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]
</code>```

Body:
I've got an array in the following form:

[["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]

Is there a way to somehow display this information on a Rails template using iterators? I need something like this:

First - a, b, c

Second - d, e,

Third - g, h, i.

Or this is impossible and I should modify the initial array form?

Thanks in advance.

Body:
Without modifing the main array you could try with each_with_index inside each for the main array of arrays, then checking for the first value you can skip it and get the array of letters:

array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]

array.each do |main|
  main.each_with_index do |value, index|
    next if index.zero?
    p value
  end
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]

Or if you want to access it as a hash it'd be easier:

array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
array.to_h.each do |_, value|
  p value
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]


来源: stackexchange

问:
Radio button does not stay check after submitting right value
I cannot understand why the radio button does not stay checked after submitting the right value to the database.
I can see in the database the value being updated correctly but the corresponded radio button is empty.
Could you help me?</p>

```<code> <?php

session_start();

include 'connect_to_database.php';
$tbl_name="members"; // Table name
$db = connect_to_database();

$email = $_SESSION['email'];

// To protect MySQL injection (more detail about MySQL injection)

function add_value_to_members($db, $email, $key, $value)
{
    $new_name=$_POST[$value];
    $new_name = stripslashes($new_name);
    $new_name = mysqli_real_escape_string($db, $new_name);
    if (strlen($new_name) > 0){
        $new_name_sql="UPDATE members SET $key='$new_name' WHERE email='$email'";
        $result=mysqli_query($db, $new_name_sql);
        echo $result;
    }
}

add_value_to_members($db, $email, "gender", "new_gender");

header("Location: ../edit_user.php");
exit();

// html

<div class="form-group">
    <label class="col-lg-3 control-label">Gender</label>
    <div class="col-lg-8">
        <div class="radio">
            <label>
                <input type="radio" name="new_gender" value="male" <?php if (isset($_POST['gender']) && $_POST['gender'] == "male") echo "checked"; ?>> Male
            </label>
        </div>
        <div class="radio">
            <label>
                <input type="radio" name="new_gender" value="female" <?php if(isset($_POST['gender']) && $_POST['gender']=="female" ) echo "checked"; ?>> Female
            </label>
        </div>
    </div>
</div>
</code>```

答: Where is your form tag? Anyway i think it has to do with sending a header wich redirects, and doesnt send a post, if this is what you need you could place the radio button value into a session variable right after updating to your database and check in your radio button tag for the session value or you could use a get paramater wich gets sended into the header url</p>

ContentLicense: CC BY-SA 3.0

Body:
I cannot understand why the radio button does not stay checked after submitting the right value to the database.
I can see in the database the value being updated correctly but the corresponded radio button is empty.
Could you help me?

 <?php

session_start();

include 'connect_to_database.php';
$tbl_name="members"; // Table name
$db = connect_to_database();

$email = $_SESSION['email'];

// To protect MySQL injection (more detail about MySQL injection)

function add_value_to_members($db, $email, $key, $value)
{
    $new_name=$_POST[$value];
    $new_name = stripslashes($new_name);
    $new_name = mysqli_real_escape_string($db, $new_name);
    if (strlen($new_name) > 0){
        $new_name_sql="UPDATE members SET $key='$new_name' WHERE email='$email'";
        $result=mysqli_query($db, $new_name_sql);
        echo $result;
    }
}

add_value_to_members($db, $email, "gender", "new_gender");

header("Location: ../edit_user.php");
exit();

// html

    Gender

                <input type="radio" name="new_gender" value="male" <?php if (isset($_POST['gender']) && $_POST['gender'] == "male") echo "checked"; ?>> Male

                <input type="radio" name="new_gender" value="female" <?php if(isset($_POST['gender']) && $_POST['gender']=="female" ) echo "checked"; ?>> Female


问:
Why are my flex items wrapping off the screen?
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <h1>Seraph Chronicles</h1>
  <nav>
    <ul class="main-nav">
      <li class="main-nav-item">Home</li>
      <li class="main-nav-item">About</li>
      <li class="main-nav-item characters">
        Characters
        <ul class="drop-menu">
          <li>Ethan Clarke</li>
          <li>Serena Kiriaga</li>
          <li>Marcus Flynn</li>
          <li>Emily Ashdown</li>
          <li>Director Miles West</li>
        </ul>
      </li>
      <li class="main-nav-item">Author</li>
    </ul>
  </nav>
</header></code>```

https://jsfiddle.net/ca75sqzc/17/

答:
Change the following in your CSS:</p>

```<code>nav ul{
  display: flex;
  /* justify-content: flex-end; */
  margin: 0 8% 0 0;
}
</code>```

Body:
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}

Seraph Chronicles

Home

About

        Characters

Ethan Clarke

Serena Kiriaga

Marcus Flynn

Emily Ashdown

Director Miles West

Author

https://jsfiddle.net/ca75sqzc/17/

Body:
Change the following in your CSS:

nav ul{
  display: flex;
  /* justify-content: flex-end; */
  margin: 0 8% 0 0;
}


问:
Properly assign img src with {{ route(function) }} and parameters using laravel and blade
I got a question using laravel, I am trying to call a function and passing some parameters along with it using the {{ route }} method something along these lines here:

```<code><img src="{{route('cacheImage', ['general', 'mini-logo.png']) }}" />
</code>```

My route in my web.php file looks like this:

```<code>Route::get('/cache/images', ['uses'=>'HomeController@cache_image','as'=>'cacheImage']);
</code>```

As a result, I am getting something like this here when the page loads in my img src:

```<code>http://localhost:8000/cache/images?general&mini-logo.png
</code>```

But this is not what I want, what I would like is to have something along these lines here in my img src:

http://localhost:8000/cache/images/general/mini-logo.png

At the same time I want to call the cacheImage function in my controller and pass it both parameters, which are "general", and "mini-logo.png"

How do I achieve this? Can someone give me an example?

答:
Change your route to this.

```<code>Route::get('/cache/images/{type}/{name}', [
    'uses' => 'HomeController@cache_image',
    'as' => 'cacheImage'
]);
</code>```

Controller method to this to be able to receive the url segments as parameters.

```<code>public function cache_image($type, $name)
{
    dd($type, $name);
}
</code>```

Then you can generate links like so.

```<code>$link = route('cacheImage', ['general', 'mini-logo.png']);
// generates http://example.dev/cache/images/general/mini-logo.png
</code>```

Body:
I got a question using laravel, I am trying to call a function and passing some parameters along with it using the {{ route }} method something along these lines here:

My route in my web.php file looks like this:

Route::get('/cache/images', ['uses'=>'HomeController@cache_image','as'=>'cacheImage']);

As a result, I am getting something like this here when the page loads in my img src:

http://localhost:8000/cache/images?general&mini-logo.png

But this is not what I want, what I would like is to have something along these lines here in my img src:

http://localhost:8000/cache/images/general/mini-logo.png

At the same time I want to call the cacheImage function in my controller and pass it both parameters, which are "general", and "mini-logo.png"

How do I achieve this? Can someone give me an example?

Body:
Change your route to this.

Route::get('/cache/images/{type}/{name}', [
    'uses' => 'HomeController@cache_image',
    'as' => 'cacheImage'
]);

Controller method to this to be able to receive the url segments as parameters.

public function cache_image($type, $name)
{
    dd($type, $name);
}

Then you can generate links like so.

$link = route('cacheImage', ['general', 'mini-logo.png']);
// generates http://example.dev/cache/images/general/mini-logo.png


问:
Returning deleted node from binary search tree
I'm attempting to write a method that would remove node from BST by the given value and I need it to return this deleted value. I found assorted examples of recursive implementations, but because of their nature, they can't return deleted node, but rather the root. Here's what I have now

```<code> public TreeNode remove(TreeNode node, int data) {
        if (null == node) {
            return null;
        }
        if (data < node.st.getkey()) {
            node.left = remove(node.left, data);
        } else if (data > node.st.getkey()) {
            node.right = remove(node.right, data);
        } else { // case for equality

            if (node.left != null && node.right != null) {
                TreeNode minInRightSubTree = min(node.right);

                copyData(node , minInRightSubTree);

                node.right = remove(node.right, minInRightSubTree.st.getkey());
            } else {
                if (node.left == null && node.right == null) {
                    node = null;
                } else {// one child case
                    TreeNode deleteNode = node;
                    node = (node.left != null) ? (node.left) : (node.right);
                    deleteNode = null;
                }
            }
        }
        return node;
    }
</code>```

Can I come up with some hack to make it return deleted node or should I look into iterative algorithm( and if so I would really appreciate it if you could hook me up with the link).

答:
You can return not just root but a pair of root and deleted node (or null if nothing was deleted).
You can use Map.Entry or new class to store 2 fields (I would recommend new class since it's more descriptive).
So your possible new signature will be public Map.Entry<TreeNode, TreeNode> remove(TreeNode node, int data)

Body:
I'm attempting to write a method that would remove node from BST by the given value and I need it to return this deleted value. I found assorted examples of recursive implementations, but because of their nature, they can't return deleted node, but rather the root. Here's what I have now

 public TreeNode remove(TreeNode node, int data) {
        if (null == node) {
            return null;
        }
        if (data < node.st.getkey()) {
            node.left = remove(node.left, data);
        } else if (data > node.st.getkey()) {
            node.right = remove(node.right, data);
        } else { // case for equality

            if (node.left != null && node.right != null) {
                TreeNode minInRightSubTree = min(node.right);

                copyData(node , minInRightSubTree);

                node.right = remove(node.right, minInRightSubTree.st.getkey());
            } else {
                if (node.left == null && node.right == null) {
                    node = null;
                } else {// one child case
                    TreeNode deleteNode = node;
                    node = (node.left != null) ? (node.left) : (node.right);
                    deleteNode = null;
                }
            }
        }
        return node;
    }

Can I come up with some hack to make it return deleted node or should I look into iterative algorithm( and if so I would really appreciate it if you could hook me up with the link).


问:
How to determine an Oracle query without access to source code?
We have a system with an Oracle backend to which we have access (though possibly not administrative access) and a front end to which we do not have the source code. The database is quite large and not easily understood - we have no documentation. I'm also not particularly knowledgable about Oracle in general.

One aspect of the front end queries the database for a particular set of data and displays it. We have a need to determine what query is being made so that we can replicate and automate it without the front end (e.g. by generating a csv file periodically).

What methods would you use to determine the SQL required to retrieve this set of data?

Currently I'm leaning towards the use of an EeePC, Wireshark and a hub (installing Wireshark on the client machines may not be possible), but I'm curious to hear any other ideas and whether anyone can think of any pitfalls with this particular approach.

答:
I have used these instructions successfully several times:
http://www.orafaq.com/wiki/SQL_Trace#Tracing_a_SQL_session</p>

OwnerDisplayName: inferis

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: kogus


问:
jdbc autocommit(false) doesnt work
There is something i don't understand with java.sql.Connection.commit().

I am using Derby(Java DB) as database server.

when I do a setAutoCommit(false) , I expect my query not to work before I explicitly call the commit() method.
but in fact, it still commit even if I don't call commit().
when I call a select * on my table to print the content, I can see that the rows have been added even though i didn't explicitly commit the query.

Could someone give me some explanation please?

```<code>    con.setAutoCommit(false);
    PreparedStatement updateHair = null;
    PreparedStatement addMan = null;
    try {

         String updateString =
                    "update PERSONNE " +
                    "set haircolor = 'RED' where haircolor = 'SHAVE'";

         String updateStatement =
                    "insert into personne values " +
                    "(3,'MICHEL','SHAVE')";

         addMan = con.prepareStatement(updateStatement);
         addMan.executeUpdate();

         updateHair = con.prepareStatement(updateString);
         updateHair.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答:
Auto-commit means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. The default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.

The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode.

```<code>con.setAutoCommit(false);
</code>```

When the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.

-- EDIT_1

Updates may be committed because you're closing your Connection without calling rollback().

If a Connection is closed without an explicit commit or a rollback the behaviour depends on database.

It is strongly recommended that an application explicitly commits or
  rolls back an active transaction prior to calling the close method. If
  the close method is called and there is an active transaction, the
  results are implementation-defined.

Connection.close()

Title: jdbc autocommit(false) doesnt work

Body:
There is something i don't understand with java.sql.Connection.commit().

I am using Derby(Java DB) as database server.

when I do a setAutoCommit(false) , I expect my query not to work before I explicitly call the commit() method.
but in fact, it still commit even if I don't call commit().
when I call a select * on my table to print the content, I can see that the rows have been added even though i didn't explicitly commit the query.

Could someone give me some explanation please?

    con.setAutoCommit(false);
    PreparedStatement updateHair = null;
    PreparedStatement addMan = null;
    try {

         String updateString =
                    "update PERSONNE " +
                    "set haircolor = 'RED' where haircolor = 'SHAVE'";

         String updateStatement =
                    "insert into personne values " +
                    "(3,'MICHEL','SHAVE')";

         addMan = con.prepareStatement(updateStatement);
         addMan.executeUpdate();

         updateHair = con.prepareStatement(updateString);
         updateHair.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Body:
Auto-commit means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. The default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.

The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode.

con.setAutoCommit(false);

When the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.

-- EDIT_1

Updates may be committed because you're closing your Connection without calling rollback().

If a Connection is closed without an explicit commit or a rollback the behaviour depends on database.

It is strongly recommended that an application explicitly commits or
  rolls back an active transaction prior to calling the close method. If
  the close method is called and there is an active transaction, the
  results are implementation-defined.

Connection.close()


问:
How to span elements without making CSS moving them?
I have some centered input boxes.

I am trying to add text to the right side of the bet box. Here is what happens when I do:

How can I fix this? I am using the span element to put them on the same line. What CSS property can fix this?

CODE:

HTML:

```<code><div class="paper">
    <h2>Play</h2>
    <div class="gamebox">
        <h1><i class="fa fa-btc" aria-hidden="true"></i>itcoin dice game</h1>
        <div class="error" id="error">You don't have anymore bitcoins left. Why not deposit some?</div>
        <h3 id="balance">Balance: 1000BTC</h3>
        <form>
            Bet
            <br>
            <span>
                <input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">Error, that bet is not valid.
            </span>
            <br>
            Chance<br>
            <input id ="userchance" value="50" type="text" name="chance">
            <br>
            <h3>Payout: 0BTC</h3>
            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
        </form>
        <button type="button" id="autobet">Autobet</button>
    </div>
</div>
</code>```

CSS:

```<code>input[type=text] {
    width: 20%;
    padding: 12px 20px;
    margin : 0 auto;
    box-sizing: border-box;
    border: 1px solid #555;
    text-align: center;
    display: inline-block;
}
</code>```

答:
Make a span around the other text and set it's position to absolute.

https://jsfiddle.net/xuhdy7Lc/

Body:
I have some centered input boxes.

I am trying to add text to the right side of the bet box. Here is what happens when I do:

How can I fix this? I am using the span element to put them on the same line. What CSS property can fix this?

CODE:

HTML:

Play

itcoin dice game

You don't have anymore bitcoins left. Why not deposit some?

Balance: 1000BTC

        <form>
            Bet

                <input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">Error, that bet is not valid.

            Chance

            <input id ="userchance" value="50" type="text" name="chance">

Payout: 0BTC

            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"> Roll dice!</button>
        </form>
        <button type="button" id="autobet">Autobet</button>

CSS:

input[type=text] {
    width: 20%;
    padding: 12px 20px;
    margin : 0 auto;
    box-sizing: border-box;
    border: 1px solid #555;
    text-align: center;
    display: inline-block;
}


问:
How to ignore .gitignore files in git status?
When I run git status, it lists a bunch of .gitignore files that I am not interested in seeing in the list (they got updated locally by Eclipse).  I browsed numerous posts in regards to this seemingly common issue but none of the suggested solutions worked for me.

E.g. I went into ~/.gitconfig and found that

excludesfile = ~/.gitignore_global

Then I went into that file and added .gitignore at the tail but that did not change anything.

How do I effectively ignore .gitignore files in git status so they don't clutter the view?

答: Simply add the entry '.gitignore' to the .gitignore file.Then 'git status' won't show .gitignore as one of the untracked files. This might be helpful if you don't want to include .gitignore in the source control.</p>


问:
show different view with different tap count from UIBarButtonItem (wrap an UISegmentedControl)
i have read about UITouch and UIGestureRecognizer, but i still really confused what the difference between them.
I have one case. In my app, i have a barbuttonitem, i want to show different view when a tap that button. if i do a singletap, i want to show a textview, but when i do a singletap again, i want to show a popover from that button. is there somebody can give me an example code to do it and give a little explanation about what is the difference between UITouch and UIGestureRecognizer???

UPDATE

the barbuttonitem is a wrapper of UISegmentedControl, here's a pic from the desain

i was try to use touchesBegan:withEvent: and touchesEnded:withEvent: to solve this problem, but i dont know how to connect it to that barbuttonitem.
This is the code i made :

```<code>-(void)addSegment{

NSAutoreleasePool *pool;
int count_doc = [_docsegmentmodels count];
NSLog(@"count doc add segment : %d", count_doc);
pool = [[NSAutoreleasePool alloc] init];
DocSegmentedModel *sl;
NSMutableArray *segmentTextMutable = [NSMutableArray array];

for(int i=0 ;(i<count_doc && i < max_segment);i++){
    sl = [_docsegmentmodels objectAtIndex:i];
    NSString *evalString = [[KoderAppDelegate sharedAppDelegate] setStringWithLength:sl.docSegmentFileName:10];
    [segmentTextMutable addObject:NSLocalizedString(evalString,@"")];

}

NSArray *segmentText = [segmentTextMutable copy];

_docSegmentedControl = [[UISegmentedControl alloc] initWithItems:segmentText];
_docSegmentedControl.selectedSegmentIndex = 0;
_docSegmentedControl.autoresizingMask =  UIViewAutoresizingFlexibleHeight;
_docSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;//UISegmentedControlStylePlain;// UISegmentedControlStyleBar;//UISegmentedControlStyleBezeled;
//docSegmentedControl.frame = CGRectMake(0, 0, 800, 46.0);
[_docSegmentedControl addTarget:self action:@selector(docSegmentAction:) forControlEvents:UIControlEventValueChanged];

// Add the control to the navigation bar
//UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
self.navItem.leftBarButtonItem = segmentItem;
self.navItem.leftBarButtonItem.title = @"";

[pool release];
[segmentItem release];
[_docSegmentedControl release];
</code>```

}

```<code>-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[NSObject cancelPreviousPerformRequestsWithTarget:self
                                         selector:@selector(segmentItemTapped:) object:segmentItem];
</code>```

}

```<code>-(void)touchesEnd:(NSSet *)touches withEvent:(UIEvent *)event{
if (touches.count == 1) {
    if (theTouch.tapCount == 2) {
        [self performSelector:@selector(segmentItemTapped:)withObject:segmentItem afterDelay:0.35];
    }else {
        [self performSelector:@selector(docSegmentAction:) withObject:segmentItem afterDelay:0.0];
    }
}
</code>```

}

```<code>- (IBAction)segmentItemTapped:(id)sender{

if (self.fileProperties == nil) {
    self.fileProperties = [[[FilePropertiesViewController alloc] initWithNibName:@"FilePropertiesViewController" bundle:nil]autorelease];
    fileProperties.delegate = self;
    self.filePropertiesPopover = [[[UIPopoverController alloc] initWithContentViewController:fileProperties]autorelease];
    [_docsegmentmodels objectAtIndex:_docSegmentedControl.selectedSegmentIndex];
}

fileProperties.docProperties = _docsegmentmodels;
fileProperties.index = _docSegmentedControl.selectedSegmentIndex; //index utk nilai2 di textfield
[self.filePropertiesPopover presentPopoverFromBarButtonItem:sender
                                   permittedArrowDirections:UIPopoverArrowDirectionUp
                                                   animated:YES];
</code>```

}

```<code>- (IBAction)docSegmentAction:(id)sender{
NSLog(@"open file");
isFileOpen = YES;
[self.moreFilePopOverController dismissPopoverAnimated:YES];
[self.filePropertiesPopover dismissPopoverAnimated:YES];

[self showTextView];
</code>```

}

is there any mistake in my understanding?

答: In your case you don't need UIGestureRecognizer. Simply set the action of the barbuttonitem to the method that should be called when the button is tapped.  Have the method keep track of the state of the textview and depending on it show it or show the popover.</p>

Body:
i have read about UITouch and UIGestureRecognizer, but i still really confused what the difference between them.
I have one case. In my app, i have a barbuttonitem, i want to show different view when a tap that button. if i do a singletap, i want to show a textview, but when i do a singletap again, i want to show a popover from that button. is there somebody can give me an example code to do it and give a little explanation about what is the difference between UITouch and UIGestureRecognizer???

UPDATE

the barbuttonitem is a wrapper of UISegmentedControl, here's a pic from the desain

i was try to use touchesBegan:withEvent: and touchesEnded:withEvent: to solve this problem, but i dont know how to connect it to that barbuttonitem.
This is the code i made :

-(void)addSegment{

NSAutoreleasePool *pool;
int count_doc = [_docsegmentmodels count];
NSLog(@"count doc add segment : %d", count_doc);
pool = [[NSAutoreleasePool alloc] init];
DocSegmentedModel *sl;
NSMutableArray *segmentTextMutable = [NSMutableArray array];

for(int i=0 ;(i<count_doc && i < max_segment);i++){
    sl = [_docsegmentmodels objectAtIndex:i];
    NSString *evalString = [[KoderAppDelegate sharedAppDelegate] setStringWithLength:sl.docSegmentFileName:10];
    [segmentTextMutable addObject:NSLocalizedString(evalString,@"")];

}

NSArray *segmentText = [segmentTextMutable copy];

_docSegmentedControl = [[UISegmentedControl alloc] initWithItems:segmentText];
_docSegmentedControl.selectedSegmentIndex = 0;
_docSegmentedControl.autoresizingMask =  UIViewAutoresizingFlexibleHeight;
_docSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;//UISegmentedControlStylePlain;// UISegmentedControlStyleBar;//UISegmentedControlStyleBezeled;
//docSegmentedControl.frame = CGRectMake(0, 0, 800, 46.0);
[_docSegmentedControl addTarget:self action:@selector(docSegmentAction:) forControlEvents:UIControlEventValueChanged];

// Add the control to the navigation bar
//UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
self.navItem.leftBarButtonItem = segmentItem;
self.navItem.leftBarButtonItem.title = @"";

[pool release];
[segmentItem release];
[_docSegmentedControl release];

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[NSObject cancelPreviousPerformRequestsWithTarget:self
                                         selector:@selector(segmentItemTapped:) object:segmentItem];

}

-(void)touchesEnd:(NSSet *)touches withEvent:(UIEvent *)event{
if (touches.count == 1) {
    if (theTouch.tapCount == 2) {
        [self performSelector:@selector(segmentItemTapped:)withObject:segmentItem afterDelay:0.35];
    }else {
        [self performSelector:@selector(docSegmentAction:) withObject:segmentItem afterDelay:0.0];
    }
}

}

- (IBAction)segmentItemTapped:(id)sender{

if (self.fileProperties == nil) {
    self.fileProperties = [[[FilePropertiesViewController alloc] initWithNibName:@"FilePropertiesViewController" bundle:nil]autorelease];
    fileProperties.delegate = self;
    self.filePropertiesPopover = [[[UIPopoverController alloc] initWithContentViewController:fileProperties]autorelease];
    [_docsegmentmodels objectAtIndex:_docSegmentedControl.selectedSegmentIndex];
}

fileProperties.docProperties = _docsegmentmodels;
fileProperties.index = _docSegmentedControl.selectedSegmentIndex; //index utk nilai2 di textfield
[self.filePropertiesPopover presentPopoverFromBarButtonItem:sender
                                   permittedArrowDirections:UIPopoverArrowDirectionUp
                                                   animated:YES];

}

- (IBAction)docSegmentAction:(id)sender{
NSLog(@"open file");
isFileOpen = YES;
[self.moreFilePopOverController dismissPopoverAnimated:YES];
[self.filePropertiesPopover dismissPopoverAnimated:YES];

[self showTextView];

}

is there any mistake in my understanding?


问:
rand function value
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this. how can i do this? my code is below </p>

```<code><?php $rand=rand(100000,999999);
$roll=$branch_name.$name.$course.$year.$rand;
echo $roll;
?>
</code>```

答:
I know that i should explain how its works, but its really a big amount of information about this in google...

In a link below i attached the url for it with some explain:

How create a radio button in html5

Title: rand function value

Body:
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this. how can i do this? my code is below

<?php $rand=rand(100000,999999);
$roll=$branch_name.$name.$course.$year.$rand;
echo $roll;
?>


问:
How to implement std::when_any without polling?
Consider http://en.cppreference.com/w/cpp/experimental/when_any. The following is just a naive and simplified implementation:

```<code>#include <future>

template<typename Iterator>
auto when_any(Iterator first, Iterator last)
{
    while (true)
    {
        for (auto pos = first; pos != last; ++pos)
        {
            if (pos->is_ready())
            {
                return std::move(*pos);
            }
        }
    }
}
</code>```

I am not satisfied because it is a busy polling in an infinite loop.

Is there a way to avoid busy polling?

答:
A polling free version would launch 1 thread per future and have them set a condition variable with which future is ready.

Then you "leak" the threads until the futures are ready while returning the fact one is ready.

This sucks.  But no polling.

To do better, you need to have a future with a continuation you can set (and remove ideally).  Then you just ask the futures to notify you when done, then wait .  This requires modifying or writing your own future.

This is one of the reasons both continuations and when_any are both proposed for standarization.  You need them in the future.

Now if you have your own system, you can base it off a thread safe queue delivering stuff rather than futures, implemented via condition variables.  This requires cooperation at the point of "future" creation.

```<code>struct many_waiter_t {
  std::mutex m;
  std::condition_variable cv;
  std::vector<std::size_t> index;

  std::size_t wait() {
    auto l = lock();
    cv.wait(l, [this]{
      return !index.empty();
    });
    auto r = index.back();
    index.pop_back();
    return r;
  }
  void set( std::size_t N ) {
    {
      auto l = lock();
      index.push_back(N);
    }
    cv.notify_one();
  }
};
template<class T>
std::future<T> add_waiter( std::future<T> f, std::size_t i, std::shared_ptr<many_waiter_t> waiter )
{
  return std::async([f = std::move(f), waiter, i]{
    auto r = f.get();
    waiter.set(i);
    return r;
  });
}
</code>```

Consuming an array of futures fs, we can generate a new array of futures f2s and a waiter, such that the waiter can be non-spinlock waited against until a future is ready, and the f2s correspond to the original fs.

You can repeatedly wait on the waiter until the f2s are all ready.

Body:
Consider http://en.cppreference.com/w/cpp/experimental/when_any. The following is just a naive and simplified implementation:

#include <future>

template<typename Iterator>
auto when_any(Iterator first, Iterator last)
{
    while (true)
    {
        for (auto pos = first; pos != last; ++pos)
        {
            if (pos->is_ready())
            {
                return std::move(*pos);
            }
        }
    }
}

I am not satisfied because it is a busy polling in an infinite loop.

Is there a way to avoid busy polling?

Body:
A polling free version would launch 1 thread per future and have them set a condition variable with which future is ready.

Then you "leak" the threads until the futures are ready while returning the fact one is ready.

This sucks.  But no polling.

To do better, you need to have a future with a continuation you can set (and remove ideally).  Then you just ask the futures to notify you when done, then wait .  This requires modifying or writing your own future.

This is one of the reasons both continuations and when_any are both proposed for standarization.  You need them in the future.

Now if you have your own system, you can base it off a thread safe queue delivering stuff rather than futures, implemented via condition variables.  This requires cooperation at the point of "future" creation.

struct many_waiter_t {
  std::mutex m;
  std::condition_variable cv;
  std::vector<std::size_t> index;

  std::size_t wait() {
    auto l = lock();
    cv.wait(l, [this]{
      return !index.empty();
    });
    auto r = index.back();
    index.pop_back();
    return r;
  }
  void set( std::size_t N ) {
    {
      auto l = lock();
      index.push_back(N);
    }
    cv.notify_one();
  }
};
template<class T>
std::future<T> add_waiter( std::future<T> f, std::size_t i, std::shared_ptr<many_waiter_t> waiter )
{
  return std::async([f = std::move(f), waiter, i]{
    auto r = f.get();
    waiter.set(i);
    return r;
  });
}

Consuming an array of futures fs, we can generate a new array of futures f2s and a waiter, such that the waiter can be non-spinlock waited against until a future is ready, and the f2s correspond to the original fs.

You can repeatedly wait on the waiter until the f2s are all ready.


问:
Error on reset() when checking whether client closes connection
I'm writing a simple tcp stream SMTP server. I wrote following code to check if the client connection is still available. Simply peeking one byte to see if socket input stream is working. But when I set in.mark(x) read ahead limit to 1, it shows error when I attempt to send Header for the second time. When it's set to 2, it doesn't seem to have any problem at all. Why is this?

```<code>// check if client disconnected
try {
    in.mark(1); // 1 char read ahead limit
    if (in.read() == -1) {
        System.out.println("CONNECTION CLOSED BY CLIENT!");
        return; // end of thread
    } else {
        in.reset();
    }
} catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
}
</code>```

The error I get is this:

```<code>java.io.IOException: Mark invalid
    at java.io.BufferedReader.reset(BufferedReader.java:512)
    at smtp.server.SocketThread.run(SocketThread.java:59)
</code>```

The entire code is on my github.

答:
Forget it. Just read and write, and deal with the exceptions as they arise.

At present you are engaged in fortune-telling. Even if you find a method that works to tell you whether the client connection is alive now, it could go down between calling this method and the very next line of code.

The only method that actually works of trying to detect whether a resource is available is to try to use it in the normal way.

Body:
I'm writing a simple tcp stream SMTP server. I wrote following code to check if the client connection is still available. Simply peeking one byte to see if socket input stream is working. But when I set in.mark(x) read ahead limit to 1, it shows error when I attempt to send Header for the second time. When it's set to 2, it doesn't seem to have any problem at all. Why is this?

// check if client disconnected
try {
    in.mark(1); // 1 char read ahead limit
    if (in.read() == -1) {
        System.out.println("CONNECTION CLOSED BY CLIENT!");
        return; // end of thread
    } else {
        in.reset();
    }
} catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
}

The error I get is this:

java.io.IOException: Mark invalid
    at java.io.BufferedReader.reset(BufferedReader.java:512)
    at smtp.server.SocketThread.run(SocketThread.java:59)

The entire code is on my github.


问:
How to predict values of column in new Python data frame using info from the old data frame
Let's assume I have two data frames df1 and df2. In df1 I have several columns such as userid, sexid, location and etc. And in df2 I have all the same columns as in df1 except for sexid which I need to fill using some prediction algorithm.
I am just a beginner and I tried another kind of problems. So any advice or useful references which may help me to crack it are welcomed.</p>

答:
A minimal example:

```<code>import pandas as pd
from sklearn.linear_model import LogisticRegression

df1 = pd.DataFrame({'sexid': list('MMFFMFFMMF'), 'x1': [0, 12, 2, 3, 4, 2, 0, 12, 12, 12], 'x2': [0, 1, 1, 1, 0, 1, 1, 0, 0, 1]})

df2 = pd.DataFrame({'x1': [0, 12, 2, 3, 4, 2, 0, 12, 12, 12], 'x2': [0, 1, 1, 1, 0, 1, 1, 0, 0, 1]})

X = df1[['x1', 'x2']]
y = df1['sexid']

model = LogisticRegression()

model.fit(X, y)

model.predict(df2)
</code>```

Which returns:

```<code>array(['F', 'M', 'F', 'F', 'M', 'F', 'F', 'M', 'M', 'M'], dtype=object)
</code>```

I would highly recommend you read this.

Body:
A minimal example:

import pandas as pd
from sklearn.linear_model import LogisticRegression

df1 = pd.DataFrame({'sexid': list('MMFFMFFMMF'), 'x1': [0, 12, 2, 3, 4, 2, 0, 12, 12, 12], 'x2': [0, 1, 1, 1, 0, 1, 1, 0, 0, 1]})

df2 = pd.DataFrame({'x1': [0, 12, 2, 3, 4, 2, 0, 12, 12, 12], 'x2': [0, 1, 1, 1, 0, 1, 1, 0, 0, 1]})

X = df1[['x1', 'x2']]
y = df1['sexid']

model = LogisticRegression()

model.fit(X, y)

model.predict(df2)

Which returns:

array(['F', 'M', 'F', 'F', 'M', 'F', 'F', 'M', 'M', 'M'], dtype=object)

I would highly recommend you read this.


问:
system library call not working in Intel PIN Fini Function
I want to execute one shell command (gcore $pid) at the end of pin tool.

In order to complete this goal, I try to modify the itrace pin tool and do one simple shell command first. I add one statement system("ls > /tmp/test") at the starting of Fini function. Then compile the pin tool again.

Run the pin tool - itrace:

../../../pin -t obj-intel64/itrace.so -- /bin/ls

But there does not exist file - "/tmp/test".

答:
the libc function system() is not yet implemented in PinCRT.
  Please use popen() (which is implemented) instead.

source.


问:
JQuery panel hiding
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html></code>```

答:
put # on  $("btnMLAJournal").click(function(){

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("#btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html></code>```

Title: JQuery panel hiding

Body:
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});

<!DOCTYPE html>

    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

MLA Journal

dadadda

surprise!"

Body:
put # on  $("btnMLAJournal").click(function(){

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("#btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});

<!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html>


问:
Creating key value pairs from json on import
I am new to jquery - I have a valid geojson file whose features I would like to access and convert into an object of key-value pairs.  My objective is to only use properties.cat as the key and properties.name as the value (all other data can be ignored).  Here is a sample:

```<code>{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
"features": [
{ "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
{ "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
{ "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
]
}

  $.getJSON("sample.geojson", function(json) {

    console.log(json.features[0].properties.cat);

      });
</code>```

As was pointed out below, features is an array.
How could one create an object of key value pairs directly from every feature property in the json so as to have the following output:

```<code>{A : Aberdeen, B: Berlin, C: Copenhagen, D: Dublin, E: Edinburgh}
</code>```

答:
The callback function for $.getJson method has response already parsed automatically.

Also, features object is an array. Use this:

```<code>console.log(json.features[0].properties.cat);
</code>```

For making key-value pairs you can use reduce method, which accepts a callback provided method applied for every item.

var json= {
      "type": "FeatureCollection",
      "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
      "features": [
      { "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
      { "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
      { "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
      ]
}
var obj=json.features.reduce(function(obj,item){
  obj[item.properties.cat]=item.properties.name;
  return obj;
},{});
console.log(obj);```

Body:
I am new to jquery - I have a valid geojson file whose features I would like to access and convert into an object of key-value pairs.  My objective is to only use properties.cat as the key and properties.name as the value (all other data can be ignored).  Here is a sample:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
"features": [
{ "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
{ "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
{ "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
]
}

  $.getJSON("sample.geojson", function(json) {

    console.log(json.features[0].properties.cat);

      });

As was pointed out below, features is an array.
How could one create an object of key value pairs directly from every feature property in the json so as to have the following output:

{A : Aberdeen, B: Berlin, C: Copenhagen, D: Dublin, E: Edinburgh}

Body:
The callback function for $.getJson method has response already parsed automatically.

Also, features object is an array. Use this:

console.log(json.features[0].properties.cat);

For making key-value pairs you can use reduce method, which accepts a callback provided method applied for every item.

var json= {
      "type": "FeatureCollection",
      "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
      "features": [
      { "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
      { "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
      { "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
      ]
}
var obj=json.features.reduce(function(obj,item){
  obj[item.properties.cat]=item.properties.name;
  return obj;
},{});
console.log(obj);


问:
c# : How to get response and parse it for below Rest Assured
What below code returns depending on that how to get that response and parse it

How to verify status code, content, url,type etc from response

```<code>new RestAssured()
                    .Given()
                        .Header("Content-Type", "application/json")
                        .Header("Accept-Encoding", "gzip, deflate")
                        .Host("http://qa.services.theknot.com")
                        .Uri("/local-partners/marketplace/v1/storefronts")
                        .Query("apikey", "ca7f6e91ee8134de9717707d86b29100")
                        .Body("{ 'Id': [323920, '3a6b4e0b-8e5c-df11-849b-0014c258f21e'] }")
                    .When()
                    .Post()
                    .Then()
                        .Debug();
</code>```

答: Use .TestBody("string", Func<dynamic, bool>) or TestStatus("string", Func<int, bool>) or refer to documentation .

Body:
What below code returns depending on that how to get that response and parse it

How to verify status code, content, url,type etc from response

new RestAssured()
                    .Given()
                        .Header("Content-Type", "application/json")
                        .Header("Accept-Encoding", "gzip, deflate")
                        .Host("http://qa.services.theknot.com")
                        .Uri("/local-partners/marketplace/v1/storefronts")
                        .Query("apikey", "ca7f6e91ee8134de9717707d86b29100")
                        .Body("{ 'Id': [323920, '3a6b4e0b-8e5c-df11-849b-0014c258f21e'] }")
                    .When()
                    .Post()
                    .Then()
                        .Debug();


问:
How to 'SELECT' data from orient db and display it using php
i am trying to select inserted data from orient db database and to echo it out ?
how can i do this using php ?

This is what i have done so far

```<code>require('OrientDB/OrientDB.php');
$db = new OrientDB('localhost', 2424);

        $connected = $db->connect('root', 'hello');
        $config = $db->DBOpen('tabe', 'root', 'hello');
        if($connected)
        {

              $records = $db->query("select from Nation");

              echo $records;

        }
        else
        {
           die('Server Error');
        }
</code>```

it just prints 'Array' on screen

i am running a Apache php  server on windows machine.
how can i get the data from the databse and print in on the website.

when i use for each loop to print out the element

my script just time out

```<code> $records = $db->query("select from Nation");
              foreach ($records as $v)
                  echo $v;
</code>```

if i use print_r($records);

it gives the following output

```<code>Array ( [0] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 169 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 169:0 [version] => 4 [content:OrientDBRecord:private] => Nation@in_partOf:%AQAAAAIAwQAAAAAAAAAAAMIAAAAAAAAAAA==;,Country_Name:"India",Iso_code:"IN" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [1] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 170 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 170:0 [version] => 4 [content:OrientDBRecord:private] => Nation@Country_Name:"United States of America",Iso_code:"US" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [2] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 171 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 171:0 [version] => 2 [content:OrientDBRecord:private] => Nation@Country_Name:"Canada",Iso_code:"CA" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) )
</code>```

how to convert it in to suitable form . like taking only names from it

this is my table

答:
Better use PhpOrient Library it is the officially supported library by orient db

```<code>    $client = new PhpOrient();
        $client->hostname = 'localhost';
        $client->port     = 2424;
        $client->username = 'your_username';
        $client->password = 'your_password';

        $client->connect();
        $client->dbOpen('Your_db_name');

         $query = "SELECT FROM NATION";
         $result = $client->query($query);

       $result =  json_encode($result);
       $result = json_decode($result);

foreach ($result as $row){
       echo $row->oData->Country_Name;
       echo $row->oData->Iso_code;
}
</code>```

phporient : https://github.com/orientechnologies/PhpOrient.git

ContentLicense: CC BY-SA 4.0

Body:
i am trying to select inserted data from orient db database and to echo it out ?
how can i do this using php ?

This is what i have done so far

require('OrientDB/OrientDB.php');
$db = new OrientDB('localhost', 2424);

        $connected = $db->connect('root', 'hello');
        $config = $db->DBOpen('tabe', 'root', 'hello');
        if($connected)
        {

              $records = $db->query("select from Nation");

              echo $records;

        }
        else
        {
           die('Server Error');
        }

it just prints 'Array' on screen

i am running a Apache php  server on windows machine.
how can i get the data from the databse and print in on the website.

when i use for each loop to print out the element

my script just time out

 $records = $db->query("select from Nation");
              foreach ($records as $v)
                  echo $v;

if i use print_r($records);

it gives the following output

Array ( [0] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 169 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 169:0 [version] => 4 [content:OrientDBRecord:private] => Nation@in_partOf:%AQAAAAIAwQAAAAAAAAAAAMIAAAAAAAAAAA==;,Country_Name:"India",Iso_code:"IN" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [1] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 170 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 170:0 [version] => 4 [content:OrientDBRecord:private] => Nation@Country_Name:"United States of America",Iso_code:"US" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [2] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 171 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 171:0 [version] => 2 [content:OrientDBRecord:private] => Nation@Country_Name:"Canada",Iso_code:"CA" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) )

how to convert it in to suitable form . like taking only names from it

this is my table

Body:
Better use PhpOrient Library it is the officially supported library by orient db

    $client = new PhpOrient();
        $client->hostname = 'localhost';
        $client->port     = 2424;
        $client->username = 'your_username';
        $client->password = 'your_password';

        $client->connect();
        $client->dbOpen('Your_db_name');

         $query = "SELECT FROM NATION";
         $result = $client->query($query);

       $result =  json_encode($result);
       $result = json_decode($result);

foreach ($result as $row){
       echo $row->oData->Country_Name;
       echo $row->oData->Iso_code;
}

phporient : https://github.com/orientechnologies/PhpOrient.git


问:
Python http.server not print log
I am using Git Bash to run a simple local server with $ python3 -m http.server 8000

Git Bash never prints that it is running and does not get a log of the requests. I can access http://localhost:8000/ so the command is working. How do I get git bash to print the log?

答:
From looking at "what" Git Bash, it would seem to be a cut down version of cygwin.  I have just run "python3 -m http.server 8000", and get the following log output:

```<code>$ python3 -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Jun/2017 20:15:10] code 404, message File not found
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [04/Jun/2017 20:15:10] code 404, message File not found
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET /favicon.ico HTTP/1.1" 404 -
</code>```

It would seem that git bash is not logging (outputting) correctly.

Trying running "python3 -m http.server 8000" in virtualbox / vagrant -> with Ubuntu or Centos.

Title: Python http.server not print log

Body:
From looking at "what" Git Bash, it would seem to be a cut down version of cygwin.  I have just run "python3 -m http.server 8000", and get the following log output:

$ python3 -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Jun/2017 20:15:10] code 404, message File not found
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [04/Jun/2017 20:15:10] code 404, message File not found
127.0.0.1 - - [04/Jun/2017 20:15:10] "GET /favicon.ico HTTP/1.1" 404 -

It would seem that git bash is not logging (outputting) correctly.

Trying running "python3 -m http.server 8000" in virtualbox / vagrant -> with Ubuntu or Centos.


问:
Android: custom AlertDialog, viewPager : java.lang.IllegalArgumentException: No view found for id
Android 4.3.

My custom dialogFragment:

```<code>public class IntroductoryTourDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
private int totalPagesCount;
private Activity activity;

private static final String TAG = IntroductoryTourDialogFragment.class.getName();

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity = activity;
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = activity.getLayoutInflater();
    View view = inflater.inflate(R.layout.introductory_tour_layout, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setView(view);
    setCancelable(false);
    init(view);
    return builder.create();
}

private void init(View view) {
    totalPagesCount = getResources().getStringArray(R.array.introductory_tour_images_names).length;
    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
    ViewPager viewPager = (ViewPager) view.findViewById(R.id.introductory_tour_viewPager);
    viewPager.setAdapter(sectionsPagerAdapter);
    viewPager.addOnPageChangeListener(this);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = new IntroductoryTourPageFragment();
        Bundle args = new Bundle();
        String introductory_tour_images_name = getResources().getStringArray(R.array.introductory_tour_images_names)[position];
        args.putString(IntroductoryTourPageFragment.TOUR_PAGE_NAME, introductory_tour_images_name);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return totalPagesCount;
    }
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrollStateChanged(int state) {

}
}
</code>```

My custom xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg">
    <android.support.v4.view.ViewPager
        android:id="@+id/introductory_tour_viewPager"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

But when try run this dialog fragment I get error:

```<code>java.lang.IllegalArgumentException: No view found for id 0x7f0e026e
    (com.my_project:id/introductory_tour_viewPager)
    for fragment IntroductoryTourPageFragment{427e2d10 #2 id=0x7f0e026e android:switcher:2131624558:0}
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
    at android.view.View.measure(View.java:15848)
    at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
    at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1079)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    at android.view.Choreographer.doFrame(Choreographer.java:532)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    at android.os.Handler.handleCallback(Handler.java:730)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5103)
</code>```

答:
The main problem is your dialog View is not created properly. Before creating View, you are trying to initialize ViewPager and set SectionsPagerAdapter to ViewPager.

SOLUTION:

1. First, remove overridden method onCreateDialog().

2. Override onCreateView() and inflate your layout introductory_tour_layout from here:

```<code>    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, container);

        return view;
    }
</code>```

3. When view created successfully, initialize your ViewPager set SectionsPagerAdapter to ViewPager. To do this call method init(view) From onViewCreated():

```<code>    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init(view);
    }
</code>```

4. When creating instance of SectionsPagerAdapter use getChildFragmentManager() instead of getFragmentManager():

```<code>SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
</code>```

Here is the working code:

```<code>public class IntroductoryTourDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {

    private int totalPagesCount;
    private Activity activity;

    private static final String TAG = IntroductoryTourDialogFragment.class.getName();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, container);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init(view);
    }

    private void init(View view) {
        totalPagesCount = getResources().getStringArray(R.array.introductory_tour_images_names).length;
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
        ViewPager viewPager = (ViewPager) view.findViewById(R.id.introductory_tour_viewPager);
        viewPager.setAdapter(sectionsPagerAdapter);
        viewPager.addOnPageChangeListener(this);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            Fragment fragment = new IntroductoryTourPageFragment();
            Bundle args = new Bundle();
            String introductory_tour_images_name = getResources().getStringArray(R.array.introductory_tour_images_names)[position];
            args.putString(IntroductoryTourPageFragment.TOUR_PAGE_NAME, introductory_tour_images_name);
            fragment.setArguments(args);

            return fragment;
        }

        @Override
        public int getCount() {
            return totalPagesCount;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
</code>```

To show IntroductoryTourDialogFragment , use below code in your Activity:

```<code>IntroductoryTourDialogFragment introductoryTourDialogFragment = new IntroductoryTourDialogFragment();
introductoryTourDialogFragment.show(getSupportFragmentManager(), introductoryTourDialogFragment.getTag());
</code>```

This also work (without onViewCreated()):

```<code>    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, null);
        init(view);

        return view;
    }
</code>```

Hope this will help~

Body:
Android 4.3.

My custom dialogFragment:

public class IntroductoryTourDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
private int totalPagesCount;
private Activity activity;

private static final String TAG = IntroductoryTourDialogFragment.class.getName();

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity = activity;
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = activity.getLayoutInflater();
    View view = inflater.inflate(R.layout.introductory_tour_layout, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setView(view);
    setCancelable(false);
    init(view);
    return builder.create();
}

private void init(View view) {
    totalPagesCount = getResources().getStringArray(R.array.introductory_tour_images_names).length;
    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
    ViewPager viewPager = (ViewPager) view.findViewById(R.id.introductory_tour_viewPager);
    viewPager.setAdapter(sectionsPagerAdapter);
    viewPager.addOnPageChangeListener(this);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = new IntroductoryTourPageFragment();
        Bundle args = new Bundle();
        String introductory_tour_images_name = getResources().getStringArray(R.array.introductory_tour_images_names)[position];
        args.putString(IntroductoryTourPageFragment.TOUR_PAGE_NAME, introductory_tour_images_name);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return totalPagesCount;
    }
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrollStateChanged(int state) {

}
}

My custom xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg">
    <android.support.v4.view.ViewPager
        android:id="@+id/introductory_tour_viewPager"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>

But when try run this dialog fragment I get error:

java.lang.IllegalArgumentException: No view found for id 0x7f0e026e
    (com.my_project:id/introductory_tour_viewPager)
    for fragment IntroductoryTourPageFragment{427e2d10 #2 id=0x7f0e026e android:switcher:2131624558:0}
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
    at android.view.View.measure(View.java:15848)
    at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
    at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
    at android.view.View.measure(View.java:15848)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1079)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    at android.view.Choreographer.doFrame(Choreographer.java:532)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    at android.os.Handler.handleCallback(Handler.java:730)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5103)

Body:
The main problem is your dialog View is not created properly. Before creating View, you are trying to initialize ViewPager and set SectionsPagerAdapter to ViewPager.

SOLUTION:

1. First, remove overridden method onCreateDialog().

2. Override onCreateView() and inflate your layout introductory_tour_layout from here:

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, container);

        return view;
    }

3. When view created successfully, initialize your ViewPager set SectionsPagerAdapter to ViewPager. To do this call method init(view) From onViewCreated():

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init(view);
    }

4. When creating instance of SectionsPagerAdapter use getChildFragmentManager() instead of getFragmentManager():

SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());

Here is the working code:

public class IntroductoryTourDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {

    private int totalPagesCount;
    private Activity activity;

    private static final String TAG = IntroductoryTourDialogFragment.class.getName();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, container);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init(view);
    }

    private void init(View view) {
        totalPagesCount = getResources().getStringArray(R.array.introductory_tour_images_names).length;
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
        ViewPager viewPager = (ViewPager) view.findViewById(R.id.introductory_tour_viewPager);
        viewPager.setAdapter(sectionsPagerAdapter);
        viewPager.addOnPageChangeListener(this);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            Fragment fragment = new IntroductoryTourPageFragment();
            Bundle args = new Bundle();
            String introductory_tour_images_name = getResources().getStringArray(R.array.introductory_tour_images_names)[position];
            args.putString(IntroductoryTourPageFragment.TOUR_PAGE_NAME, introductory_tour_images_name);
            fragment.setArguments(args);

            return fragment;
        }

        @Override
        public int getCount() {
            return totalPagesCount;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

To show IntroductoryTourDialogFragment , use below code in your Activity:

IntroductoryTourDialogFragment introductoryTourDialogFragment = new IntroductoryTourDialogFragment();
introductoryTourDialogFragment.show(getSupportFragmentManager(), introductoryTourDialogFragment.getTag());

This also work (without onViewCreated()):

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.introductory_tour_layout, null);
        init(view);

        return view;
    }

Hope this will help~