问:
Nesting a second query inside a list of unique column values
Beginner here, be gentle please. I have a table in which one column is book titles and another is their corresponding authors. I'm using PDO to connect to the database and display the results of a query on a webpage. Basically I want each UNIQUE author displayed once, and then a list of each book title that author wrote beneath, like so:

```<code>Author 1
title1
title2

Author 2
title3
title4
</code>```

Query to get a list of distinct authors:

```<code><?php try {

$connection = new PDO($dsn, $username, $password, $options);

$sql = "SELECT DISTINCT author FROM booktable;"

$statement = $connection->prepare($sql);

$result = $statement->fetchAll();

} ?>
</code>```

Foreach loop to display each author:

```<code><?php foreach ($result as $row) { ?>

     <p><?php echo ($row["author"]); ?></p>

<?php } ?>
</code>```

So far so good, this gives me a list of unique authors. For the titles, I was trying to do another foreach loop nested inside the first to display a second query, but I can't figure out how to get only the author the loop is currently on. I tried setting a variable inside the loop like so:

```<code><?php foreach ($result as $row) { ?>

     <p><?php echo ($row["author"]); ?></p>

     <?php $currentauthor = ($row["author"]); ?>

     <?php foreach ($result2 as $row2) { ?>

          <p><?php echo ($row2["title"]); ?></p>

     <?php } ?>

<?php } ?>
</code>```

And then adding another query in my original TRY (along with a corresponding new connection and fetch statement):

```<code>$sql2 = "SELECT * FROM booktable WHERE author = '$currentauthor'";)
</code>```

But that returns nothing because the $currentauthor variable doesn't exist outside the foreach loop. So there's my issue. Am I going about this the wrong way?

答:
It looks like you should be able to do what you are attempting with a single, non-joining query. You can use SELECT * FROM booktable ORDER BY author, and loop through it's results, only outputting author data when you detect the current record has a different author than the previous one (and for the first record obviously).

A note since you're new: the * in SELECT * is generally considered bad form for final, deployed queries; I merely used it here as a placeholder since I do not know all the fields you want data from. It is best to specify all the fields you will be using, as it: (1) documents the data used without having to inspect all code that works with the data, (2) makes the query less fragile by not depending on the table definition for column order, (3) makes the query break if a used field is removed from the table, rather than later code that assumes the value will be there (which then has to be tracked back to the query), (4) keeps the amount of data that needs to be collected together and transferred to only what is needed, and (5) more...

Body:
Beginner here, be gentle please. I have a table in which one column is book titles and another is their corresponding authors. I'm using PDO to connect to the database and display the results of a query on a webpage. Basically I want each UNIQUE author displayed once, and then a list of each book title that author wrote beneath, like so:

Author 1
title1
title2

Author 2
title3
title4

Query to get a list of distinct authors:

<?php try {

$connection = new PDO($dsn, $username, $password, $options);

$sql = "SELECT DISTINCT author FROM booktable;"

$statement = $connection->prepare($sql);

$result = $statement->fetchAll();

} ?>

Foreach loop to display each author:

<?php foreach ($result as $row) { ?>

<?php echo ($row["author"]); ?>

<?php } ?>

So far so good, this gives me a list of unique authors. For the titles, I was trying to do another foreach loop nested inside the first to display a second query, but I can't figure out how to get only the author the loop is currently on. I tried setting a variable inside the loop like so:

<?php foreach ($result as $row) { ?>

<?php echo ($row["author"]); ?>

     <?php $currentauthor = ($row["author"]); ?>

     <?php foreach ($result2 as $row2) { ?>

<?php echo ($row2["title"]); ?>

     <?php } ?>

<?php } ?>

And then adding another query in my original TRY (along with a corresponding new connection and fetch statement):

$sql2 = "SELECT * FROM booktable WHERE author = '$currentauthor'";)

But that returns nothing because the $currentauthor variable doesn't exist outside the foreach loop. So there's my issue. Am I going about this the wrong way?


来源: stackexchange

问:
What does 'polling' refer to and what is this code doing exactly?
I am currently building a python script that enables and disables certain ports on switches to see how the switch will act for quality assurance purposes. I've been using a Python library called paramiko which implements SSH to connect to whichever devices I want and I'm referring to legacy code handed by one of my teammates to write more scripts. In one of the legacy code files, there is a function called _run_poll and I'm not understanding what it's doing exactly.

I have tried do some research on what "polling" means in regards to SSH, but I am still not understanding what is going when we are running the "poll". The definition for it seems a little vague. Here is the function:

```<code>def _run_poll(self, session, timeout, input_data):

    interval = 0.1
    maxseconds = timeout
    maxcount = maxseconds / interval

    i = 0
    timeout_flag = False
    self.info('polling (%d, %d)' % (maxseconds, maxcount))
    start = datetime.datetime.now()
    start_secs = time.mktime(start.timetuple())
    output = ''
    session.setblocking(0)
    while True:
        if session.recv_ready(): # returns true if data has been buffered
            data = session.recv(self.bufsize) # receive data from the channel
            output += data
            self.info('read %d bytes, total %d' % (len(data), len(output)))

            if session.send_ready():
                # We received a potential prompt.
                # In the future this could be made to work more like
                # pexpect with pattern matching.
                if i < len(input_data):
                    data = input_data[input_idx] + '\n'
                    i += 1
                    self.info('sending input data %d' % (len(data)))
                    session.send(data)

        self.info('session.exit_status_ready() = %s' % (str(session.exit_status_ready())))
        if session.exit_status_ready():
            break

        # Timeout check
        now = datetime.datetime.now()
        now_secs = time.mktime(now.timetuple())
        et_secs = now_secs - start_secs
        self.info('timeout check %d %d' % (et_secs, maxseconds))
        if et_secs > maxseconds:
            self.info('polling finished - timeout')
            timeout_flag = True
            break
        time.sleep(0.200)

    self.info('polling loop ended')
    if session.recv_ready():
        data = session.recv(self.bufsize)
        output += data
        self.info('read %d bytes, total %d' % (len(data), len(output)))

    self.info('polling finished - %d output bytes' % (len(output)))
    if timeout_flag:
        self.info('appending timeout message')
        output += '\nERROR: timeout after %d seconds\n' % (timeout)
        session.close()

    return output
</code>```

I'm not able to find a lot of online resources to describe what is going on here or about "polling" in general. Can anyone help me explain what exactly is "polling" and what is going on here ?

答:
There are two ways to handle asynchronous events in programming.

One way is to use interrupts: you have code that is not executing until "woken up" by some mechanism, and then it executes. This mechanism must be supported at a lower level than where your code executes. Microcontrollers, for example, have specific hardware built into them which can interrupt the application and jump to a specific address to start executing instructions in order to handle the interrupt.

Building an interrupt system is hard, and takes a significant amount of work. For some applications, it's just not possible. It's nearly always easier (albeit less efficient) to poll, or check a condition repeatedly until it becomes True, then go on to execute something else.

In your example, notice how he uses a while True: loop. True will never be False, so this while loop can only be broken by a break statement. We find that break statement at

if session.exit_status_ready():
            break
```

<p>So the writer of that code decided to do something continuously until <code>session.exit_status_ready()</code> was True. As this is paramiko, it's likely that he executed a remote command over SSH and is waiting until the command finishes and returns an exit code. The point of this loop is to keep the program stuck in the loop until the command has finished executing and returns a result. It also can time out:</p>

<pre class="lang-py prettyprint-override"><code>if et_secs > maxseconds:
            self.info('polling finished - timeout')
            timeout_flag = True
            break
</code>```

So if the command takes more than maxseconds the program won't sit and wait forever.

Once it exits the loop, it prints:

self.info('polling loop ended')
```

So when you see this message, you know that the remote command finished executing or timed out.

The point of polling is to check something repeatedly until a certain condition occurs. In your case, that condition is a "a remote command has finished executing" or "a certain amount of time has passed."

ContentLicense: CC BY-SA 4.0

Body:
I am currently building a python script that enables and disables certain ports on switches to see how the switch will act for quality assurance purposes. I've been using a Python library called paramiko which implements SSH to connect to whichever devices I want and I'm referring to legacy code handed by one of my teammates to write more scripts. In one of the legacy code files, there is a function called _run_poll and I'm not understanding what it's doing exactly.

I have tried do some research on what "polling" means in regards to SSH, but I am still not understanding what is going when we are running the "poll". The definition for it seems a little vague. Here is the function:

def _run_poll(self, session, timeout, input_data):

    interval = 0.1
    maxseconds = timeout
    maxcount = maxseconds / interval

    i = 0
    timeout_flag = False
    self.info('polling (%d, %d)' % (maxseconds, maxcount))
    start = datetime.datetime.now()
    start_secs = time.mktime(start.timetuple())
    output = ''
    session.setblocking(0)
    while True:
        if session.recv_ready(): # returns true if data has been buffered
            data = session.recv(self.bufsize) # receive data from the channel
            output += data
            self.info('read %d bytes, total %d' % (len(data), len(output)))

            if session.send_ready():
                # We received a potential prompt.
                # In the future this could be made to work more like
                # pexpect with pattern matching.
                if i < len(input_data):
                    data = input_data[input_idx] + '\n'
                    i += 1
                    self.info('sending input data %d' % (len(data)))
                    session.send(data)

        self.info('session.exit_status_ready() = %s' % (str(session.exit_status_ready())))
        if session.exit_status_ready():
            break

        # Timeout check
        now = datetime.datetime.now()
        now_secs = time.mktime(now.timetuple())
        et_secs = now_secs - start_secs
        self.info('timeout check %d %d' % (et_secs, maxseconds))
        if et_secs > maxseconds:
            self.info('polling finished - timeout')
            timeout_flag = True
            break
        time.sleep(0.200)

    self.info('polling loop ended')
    if session.recv_ready():
        data = session.recv(self.bufsize)
        output += data
        self.info('read %d bytes, total %d' % (len(data), len(output)))

    self.info('polling finished - %d output bytes' % (len(output)))
    if timeout_flag:
        self.info('appending timeout message')
        output += '\nERROR: timeout after %d seconds\n' % (timeout)
        session.close()

    return output

I'm not able to find a lot of online resources to describe what is going on here or about "polling" in general. Can anyone help me explain what exactly is "polling" and what is going on here ?

Body:
There are two ways to handle asynchronous events in programming.

One way is to use interrupts: you have code that is not executing until "woken up" by some mechanism, and then it executes. This mechanism must be supported at a lower level than where your code executes. Microcontrollers, for example, have specific hardware built into them which can interrupt the application and jump to a specific address to start executing instructions in order to handle the interrupt.

Building an interrupt system is hard, and takes a significant amount of work. For some applications, it's just not possible. It's nearly always easier (albeit less efficient) to poll, or check a condition repeatedly until it becomes True, then go on to execute something else.

In your example, notice how he uses a while True: loop. True will never be False, so this while loop can only be broken by a break statement. We find that break statement at

if session.exit_status_ready():
            break

So the writer of that code decided to do something continuously until session.exit_status_ready() was True. As this is paramiko, it's likely that he executed a remote command over SSH and is waiting until the command finishes and returns an exit code. The point of this loop is to keep the program stuck in the loop until the command has finished executing and returns a result. It also can time out:

if et_secs > maxseconds:
            self.info('polling finished - timeout')
            timeout_flag = True
            break

So if the command takes more than maxseconds the program won't sit and wait forever.

Once it exits the loop, it prints:

self.info('polling loop ended')

So when you see this message, you know that the remote command finished executing or timed out.

The point of polling is to check something repeatedly until a certain condition occurs. In your case, that condition is a "a remote command has finished executing" or "a certain amount of time has passed."


问:
Nested replies almost done, only need to arrange them in view
I'm currently doing a small forum in Laravel. This will include(ofcourse) commenting on posts. I also done replies on top of comments. I've done this by adding post_id, commenter_id and parent_id field in Comment model. And that's all alright.And i also done small margin that each reply have depending on their parent .What i have trouble with is displaying appropriate reply, for example: Comment1, then reply to comm.1, then another reply to that reply and so on, then another direct reply on Comment1, every subsequent reply to reply after second direct comment on Comment1 isn't grouped with other replies. How to achieve that?

Here is image of what i'm trying to achieve:

Here is Comment model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Post;
use App\User;

class Comment extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'parent_id',
        'body'
    ];

    public function commentPost(){
        return $this->belongsTo("App\Post","post_id");
    }

    public function commentAuthor(){
        return $this->belongsTo("App\User","commenter_id");
    }

    public function replies() {
        return $this->hasMany('App\Comment', 'parent_id');
    }
}
</code>```

Here is show view:

```<code>@extends("layouts.app")

@section("content")
    <?php
        /*Pregleda zasebno za title i description da li ima gresaka.
        Ukoliko ih ima, dodeljume im klasu(crveni border).*/
        $errBody = $errors->has('body') ? 'shake' : '';
    ?>
    <a href="/posts" class="btn btn-outline-info btn-sm">Go Back</a>
    <div style="float:right;">
        <a href="/posts/{{$prev}}" class="btn btn-outline-success"><i class="fas fa-arrow-left"></i></a>
        <a href="/posts/{{$next}}" class="btn btn-outline-info"><i class="fas fa-arrow-right"></i></a>
    </div>
    <h1>{{$post->title}}</h1>
    <div class="postContainer">
        <img class="postCover" src="/storage/cover_images/{{$post->cover_image}}">

            <div>
            <!--Ovako prikazuje html kod.-->
            <!--{{$post->body}}-->
                {!!$post->body!!}
            </div>

            <small class="timestamp">Written on {{$post->created_at}}</small>
    </div>

    @if(!Auth::guest())
        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
            <hr>
            <a href="/posts/{{$post->id}}/edit" class="btn btn-outline-primary btn-sm">Edit</a>

            <form action="/posts/{{$post->id}}" method="post" class="float-right">
                @csrf
                {{method_field("DELETE")}}

                <!-- The Modal -->
                <div class="modal" id="myModal">
                    <div class="modal-dialog">
                    <div class="modal-content">

                        <!-- Modal Header -->
                        <div class="modal-header">
                        <h4 class="modal-title">Are yoy sure you want to delete this post?</h4>
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        </div>

                        <!-- Modal body -->
                        <div class="modal-body">
                            <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
                        </div>

                        <!-- Modal footer -->
                        <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                        </div>

                    </div>
                    </div>
                </div>

            </form>

            <button class="btn btn-outline-danger btn-sm float-right" data-toggle="modal" data-target="#myModal">Delete</button>
        @endif
    @endif

    @auth
    <hr>

    @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
        <form method="POST" action="/posts/{{$post->id}}/comments">
            @csrf
            <!-- https://laravel.com/docs/5.7/validation#available-validation-rules -->

            <div class="form-group animated {{$errBody}}">
                <textarea id="ckeditor" class="form-control" name="body" placeholder="Post body" required value=""></textarea>
            </div>

            <div>
                <button type="submit" class="btn btn-outline-success btn-sm">Post comment</button>
            </div>

        </form>
    @endif

    <hr>
    @endauth
    <h6 style="border-bottom: 1px solid whitesmoke;">Comments <span class="badge" style="background-color: whitesmoke; border: 1px solid silver;vertical-align: top;">{{count($comments)}}</span></h6>
    <div class="container commContainer">

        <ul class="list-group" style="list-style-type:none">
            @if(count($comments) > 0)
                @foreach ($comments as $index => $comment)

                    <li>

                        @if($index>0)
                            <div class="horDiv"></div>
                        @endif

                        {{$comment->commentAuthor->name}} has said parent_id: {{$comment->parent_id}}
                    </li>
                    <li class="list-group-item py-2 commBody" style="margin-left: calc({{$comment->parent_id}}*10px) !important" parent_id="{{$comment->parent_id}}" id="{{$comment->id}}">My id: {{$comment->id}} {!!$comment->body!!}
                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
                            <br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $comment->id }}')";>reply</span>
                            @include('inc.replyForm')
                        @endif
                    </li>

                @endforeach

            @endif

        </ul>

    </div>

@endsection
</code>```

I'm just guessing, but can it be done by in view itself?I tried grouping and ordering before controller passes it to view, but nothing had desired effect. I appreciate every point in right direction.

Edit:
Here is store method in CommentsController.

```<code>public function store(Request $request, $id)
    {
        $this->validate($request, [
            "body" => "required"

        ]);

        $data = array(
            "body" => $request->input("body"),
            "post_id" => intval($id),
            "commenter_id" => Auth::user()->id,
            "imParent_id" => $request->input("comment_id")
        );
        //dd($data);
        $comment = new Comment;
        $comment->body = $data["body"];
        $comment->post_id = $data["post_id"];
        $comment->commenter_id = $data["commenter_id"];
        $comment->parent_id = $data["imParent_id"];

        $comment->save();

        $post = Post::find($id);
        $comments = $post->comments;
        //return redirect("/posts/{{$id}}")->with("success", "Post Created")->with('comments', $comments);
        //return view("posts.show")->with(compact('post', 'comments'));
        //with(['replies' => function($comments){ $comments->orderBy('parent_id') } ])
        return back()->with('comments', $comments);
    }
</code>```

Edit2:

And here is show method in PostController:

```<code>public function show($id)
    {

        $post = Post::find($id);

        $comments = $post->comments;

        $prev = $post->prev($post);
        $next = $post->next($post);

        return view("posts.show")->with(compact("post", "prev", "next", "comments"));
    }
</code>```

Edit3:

Here is rather flawed attempt(in show view):

```<code>@if(count($comments) > 0)

                @for($i=0;$i<count($comments);$i++)

                    @if(!$comments[$i]->parent_id)
                        <li class="list-group-item py-2 commBody" parent_id="{{$comments[$i]->parent_id}}" id="{{$comments[$i]->id}}">
                            {!!$comments[$i]->body!!}
                        </li>
                        @for($k=0;$k<count($comments);$k++)

                            @if($comments[$i]->id==$comments[$k]->parent_id)
                            <?php array_push($myArray,$comments[$i]->id); ?>
                                <li class="list-group-item py-2 commBody" style="margin-left: calc({{$comments[$k]->parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
                                    {!!$comments[$k]->body!!}
                                </li>
                            @endif

                        @endfor
                        {{"///////////////////////////////////////////////"}}
                    @endif

                    @if(array_search($comments[$i]->parent_id,$myArray)===false)

                        @for($k=0;$k<count($comments);$k++)

                            @if($comments[$i]->id==$comments[$k]->parent_id)

                            <li class="list-group-item py-2 commBody" style="margin-left: calc({{$comments[$k]->parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
                                {!!$comments[$k]->body!!}
                            </li>

                            @endif

                        @endfor

                    @endif

                @endfor
@endif
</code>```

And how it looks along with duplicates:

Edit4:

Followed Tim Lewis advice of separating comments(parentless) from replies(with parents), here's how to displayed them and sending additional parameter to reply form partial:

```<code><ul class="list-group" style="list-style-type:none">
            @if(count($comms) > 0)

                @for($i=0;$i<count($comms);$i++)

                    <li class="list-group-item py-2 commBody" style="margin-left: calc({{"0"}}*10px) !important" parent_id="{{$comms[$i]->parent_id}}" id="{{$comms[$i]->id}}">

                        {{$comms[$i]->body}}

                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

                            <br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $comms[$i]->id }}')";>reply</span>
                            @include('inc.replyForm', array('par' => $comms[$i]))

                        @endif

                    </li>

                    <li>@if($i>0) <div class="horDiv"></div> @endif </li>

                    @if(count($replies) > 0)

                        @for($j=0;$j<count($replies);$j++)

                            @if($comms[$i]->id==$replies[$j]->parent_id)
                                <li class="list-group-item py-2 commBody" style="margin-left: calc({{$comms[$i]->id}}*10px) !important" parent_id="{{$replies[$j]->parent_id}}" id="{{$replies[$j]->id}}">

                                    {{$replies[$j]->body}}

                                    @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

                                        <br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $replies[$j]->id }}')";>reply</span>
                                        @include('inc.replyForm', array('par' => $replies[$j]))

                                    @endif

                                </li>
                                <li>@if($j>0) <div class="horDiv"></div> @endif </li>
                            @endif

                            @for($k=$j;$k<count($replies);$k++)

                                @if($replies[$k]->parent_id==$replies[$j]->id)
                                    <li class="list-group-item py-2 commBody" style="margin-left: calc({{$replies[$j]->id}}*10px) !important" parent_id="{{$replies[$k]->parent_id}}" id="{{$replies[$k]->id}}">

                                        {{$replies[$k]->body}}

                                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

                                            <br><span class="btn btn-outline-primary btn-sm" style="width: 40px;height: 20px;line-height: 5px;padding: 5px;" onclick="reply('reply{{ $replies[$k]->id }}')";>reply</span>
                                            @include('inc.replyForm', array('par' => $replies[$k]))

                                        @endif

                                    </li>
                                    <li>@if($k>0) <div class="horDiv"></div> @endif </li>
                                @endif

                            @endfor

                        @endfor

                    @endif

                @endfor

            @endif
        </ul>
</code>```

答:
I did it before for making categories. Here is a tip:</p>

```<code><select name="category_id" class="form-control chosen-select" required value="{{ old('category_id') }}">
            @foreach(App\Category::where('parent_id',0)->get() as $c)
                <option value="{{$c->id}}">*{{$c->name}}</option>
                @foreach(App\Category::where('parent_id',$c->id)->get() as $d1)
                    <option value="{{$d1->id}}"> - {{$d1->name}}</option>
                @endforeach
            @endforeach
        </select>
</code>```

Body:
I'm currently doing a small forum in Laravel. This will include(ofcourse) commenting on posts. I also done replies on top of comments. I've done this by adding post_id, commenter_id and parent_id field in Comment model. And that's all alright.And i also done small margin that each reply have depending on their parent .What i have trouble with is displaying appropriate reply, for example: Comment1, then reply to comm.1, then another reply to that reply and so on, then another direct reply on Comment1, every subsequent reply to reply after second direct comment on Comment1 isn't grouped with other replies. How to achieve that?

Here is image of what i'm trying to achieve:

Here is Comment model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Post;
use App\User;

class Comment extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'parent_id',
        'body'
    ];

    public function commentPost(){
        return $this->belongsTo("App\Post","post_id");
    }

    public function commentAuthor(){
        return $this->belongsTo("App\User","commenter_id");
    }

    public function replies() {
        return $this->hasMany('App\Comment', 'parent_id');
    }
}

Here is show view:

@extends("layouts.app")

@section("content")
    <?php
        /*Pregleda zasebno za title i description da li ima gresaka.
        Ukoliko ih ima, dodeljume im klasu(crveni border).*/
        $errBody = $errors->has('body') ? 'shake' : '';
    ?>
    Go Back

{{$post->title}}

        cover_image}}">

                {!!$post->body!!}

            Written on {{$post->created_at}}

    @if(!Auth::guest())
        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

            id}}/edit" class="btn btn-outline-primary btn-sm">Edit

            <form action="/posts/{{$post->id}}" method="post" class="float-right">
                @csrf
                {{method_field("DELETE")}}

Are yoy sure you want to delete this post?

                        <button type="button" class="close" data-dismiss="modal">×</button>

                            <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>

                        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

            </form>

            <button class="btn btn-outline-danger btn-sm float-right" data-toggle="modal" data-target="#myModal">Delete</button>
        @endif
    @endif

    @auth

    @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)
        <form method="POST" action="/posts/{{$post->id}}/comments">
            @csrf

                <textarea id="ckeditor" class="form-control" name="body" placeholder="Post body" required value=""></textarea>

                <button type="submit" class="btn btn-outline-success btn-sm">Post comment</button>

        </form>
    @endif

    @endauth

Comments {{count($comments)}}

            @if(count($comments) > 0)
                @foreach ($comments as $index => $comment)

                        @if($index>0)

                        @endif

                        {{$comment->commentAuthor->name}} has said parent_id: {{$comment->parent_id}}

parent_id}}*10px) !important" parent_id="{{$comment->parent_id}}" id="{{$comment->id}}">My id: {{$comment->id}} {!!$comment->body!!}
                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

id }}')";>reply
                            @include('inc.replyForm')
                        @endif

                @endforeach

            @endif

@endsection

I'm just guessing, but can it be done by in view itself?I tried grouping and ordering before controller passes it to view, but nothing had desired effect. I appreciate every point in right direction.

Edit:
Here is store method in CommentsController.

public function store(Request $request, $id)
    {
        $this->validate($request, [
            "body" => "required"

        ]);

        $data = array(
            "body" => $request->input("body"),
            "post_id" => intval($id),
            "commenter_id" => Auth::user()->id,
            "imParent_id" => $request->input("comment_id")
        );
        //dd($data);
        $comment = new Comment;
        $comment->body = $data["body"];
        $comment->post_id = $data["post_id"];
        $comment->commenter_id = $data["commenter_id"];
        $comment->parent_id = $data["imParent_id"];

        $comment->save();

        $post = Post::find($id);
        $comments = $post->comments;
        //return redirect("/posts/{{$id}}")->with("success", "Post Created")->with('comments', $comments);
        //return view("posts.show")->with(compact('post', 'comments'));
        //with(['replies' => function($comments){ $comments->orderBy('parent_id') } ])
        return back()->with('comments', $comments);
    }

Edit2:

And here is show method in PostController:

public function show($id)
    {

        $post = Post::find($id);

        $comments = $post->comments;

        $prev = $post->prev($post);
        $next = $post->next($post);

        return view("posts.show")->with(compact("post", "prev", "next", "comments"));
    }

Edit3:

Here is rather flawed attempt(in show view):

@if(count($comments) > 0)

                @for($i=0;$i<count($comments);$i++)

                    @if(!$comments[$i]->parent_id)

parent_id}}" id="{{$comments[$i]->id}}">
                            {!!$comments[$i]->body!!}

                        @for($k=0;$k<count($comments);$k++)

                            @if($comments[$i]->id==$comments[$k]->parent_id)
                            <?php array_push($myArray,$comments[$i]->id); ?>

parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
                                    {!!$comments[$k]->body!!}

                            @endif

                        @endfor
                        {{"///////////////////////////////////////////////"}}
                    @endif

                    @if(array_search($comments[$i]->parent_id,$myArray)===false)

                        @for($k=0;$k<count($comments);$k++)

                            @if($comments[$i]->id==$comments[$k]->parent_id)

parent_id}}*10px) !important" parent_id="{{$comments[$k]->parent_id}}" id="{{$comments[$k]->id}}">
                                {!!$comments[$k]->body!!}

                            @endif

                        @endfor

                    @endif

                @endfor
@endif

And how it looks along with duplicates:

Edit4:

Followed Tim Lewis advice of separating comments(parentless) from replies(with parents), here's how to displayed them and sending additional parameter to reply form partial:

            @if(count($comms) > 0)

                @for($i=0;$i<count($comms);$i++)

parent_id}}" id="{{$comms[$i]->id}}">

                        {{$comms[$i]->body}}

                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

id }}')";>reply
                            @include('inc.replyForm', array('par' => $comms[$i]))

                        @endif

@if($i>0)

 @endif

                    @if(count($replies) > 0)

                        @for($j=0;$j<count($replies);$j++)

                            @if($comms[$i]->id==$replies[$j]->parent_id)

id}}*10px) !important" parent_id="{{$replies[$j]->parent_id}}" id="{{$replies[$j]->id}}">

                                    {{$replies[$j]->body}}

                                    @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

id }}')";>reply
                                        @include('inc.replyForm', array('par' => $replies[$j]))

                                    @endif

@if($j>0)

 @endif

                            @endif

                            @for($k=$j;$k<count($replies);$k++)

                                @if($replies[$k]->parent_id==$replies[$j]->id)

id}}*10px) !important" parent_id="{{$replies[$k]->parent_id}}" id="{{$replies[$k]->id}}">

                                        {{$replies[$k]->body}}

                                        @if(Auth::check() && Auth::user()->role_id<3 && Auth::user()->role_id>0)

id }}')";>reply
                                            @include('inc.replyForm', array('par' => $replies[$k]))

                                        @endif

@if($k>0)

 @endif

                                @endif

                            @endfor

                        @endfor

                    @endif

                @endfor

            @endif

Body:
I did it before for making categories. Here is a tip:

<select name="category_id" class="form-control chosen-select" required value="{{ old('category_id') }}">
            @foreach(App\Category::where('parent_id',0)->get() as $c)
                <option value="{{$c->id}}">*{{$c->name}}</option>
                @foreach(App\Category::where('parent_id',$c->id)->get() as $d1)
                    <option value="{{$d1->id}}"> - {{$d1->name}}</option>
                @endforeach
            @endforeach
        </select>


问:
How can I sum the outputs of a function in a loop?
I am trying to simply sum all of the "LengthofRoute" numbers for iterations 1 to 1000, so I can then calculate the average LengthofRoute over the 1000 iterations. How can I do this? I have scoured the internet and cannot find the correct procedure. Dijsktra1 executes and returns an integer normally less than 4. </p>

```<code>J=0;
f = 0;
nf = 0;
while J<1000
    LengthofRoute = [];
    B = RandomMatrix(0,1,10,10);
    J=J+1;
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRoute = LengthofRoute + LengthofRoute
end
</code>```

答:
You should just use a separate accumulator for summing LengthofRoute:

Assume LengthofRouteSum is accumulating the sum.

Initialize LengthofRouteSum before the loop: LengthofRouteSum = 0;

Accumulate LengthofRoute at the bottom of the loop: LengthofRouteSum = LengthofRouteSum + LengthofRoute;

The following code should get the job done:

```<code>J=0;
f = 0;
nf = 0;
LengthofRouteSum = 0;
while J<1000

    B = RandomMatrix(0,1,10,10);
    J=J+1;
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRouteSum = LengthofRouteSum + LengthofRoute;
end
</code>```

Body:
I am trying to simply sum all of the "LengthofRoute" numbers for iterations 1 to 1000, so I can then calculate the average LengthofRoute over the 1000 iterations. How can I do this? I have scoured the internet and cannot find the correct procedure. Dijsktra1 executes and returns an integer normally less than 4.

J=0;
f = 0;
nf = 0;
while J<1000
    LengthofRoute = [];
    B = RandomMatrix(0,1,10,10);
    J=J+1;
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRoute = LengthofRoute + LengthofRoute
end

Body:
You should just use a separate accumulator for summing LengthofRoute:

Assume LengthofRouteSum is accumulating the sum.

Initialize LengthofRouteSum before the loop: LengthofRouteSum = 0;

Accumulate LengthofRoute at the bottom of the loop: LengthofRouteSum = LengthofRouteSum + LengthofRoute;

The following code should get the job done:

J=0;
f = 0;
nf = 0;
LengthofRouteSum = 0;
while J<1000

    B = RandomMatrix(0,1,10,10);
    J=J+1;
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRouteSum = LengthofRouteSum + LengthofRoute;
end


问:
passing URL variables to exec() with php
I have a dedicated server that I use to crunch lots of data. The way I have it now, I can open a script with a process ID like example.php?ex_pid=123 and just let it go. It downloads a small portion of data, processes it, then uploads it into a database then starts again.

Ideally, I would like to call example.php?ex_pid=123 directly and not by passing a variable to example.php like exec('./example.php'.' '.EscapeShellArg($variable)); to keep it from acting globally.

I don't care about the output, if it could execute in the background, that would be brilliant. The server is an Ubuntu distribution btw.

Is this even possible? If so, any help and examples would be more then appreciated.

答:
I had completely forgotten about this question until @Andrew Waugh commented on it (and I got an email reminder).

Anyways, this question stemmed from a misunderstanding as to how the $argv array is communicated to the script when using CLI. You can pretty much use as many arguments as you need. The way I accomplish this now is like:

```<code>if (isset($argv)) {
    switch ($argv[1]) {
        case "a_distinguishing_name_goes_here":
            $pid = $argv[2];
            sample_function($pid);
            break;
        case "another_name_goes_here":
            do_something_else($argv[2]);
            break;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I had completely forgotten about this question until @Andrew Waugh commented on it (and I got an email reminder).

Anyways, this question stemmed from a misunderstanding as to how the $argv array is communicated to the script when using CLI. You can pretty much use as many arguments as you need. The way I accomplish this now is like:

if (isset($argv)) {
    switch ($argv[1]) {
        case "a_distinguishing_name_goes_here":
            $pid = $argv[2];
            sample_function($pid);
            break;
        case "another_name_goes_here":
            do_something_else($argv[2]);
            break;
    }
}


问:
Change Index Type in Pandas
I am using Pandas in Python 3,

I have a dataframe whose index is like '20160727', but the datatype is 'object'.

I am trying to convert it into string type.

I tried:

```<code>data.index.astye(str, copy=False)
</code>```

and data.index = data.index.map(str)

But even after these two operations,

I get:

```<code>data.index.dtype is dtype('O')
</code>```

I want to use sort after converting the index to string. How can I convert the index to string datatype so that I can process it like a string?

答:
In pandas, object is type string.

dtype('O') means it is a python type object.
You can see more info about this here

As an example of what you want to achieve:

```<code>data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=[20160103, 20160102, 20160104, 20160101])
df.index =  pd.to_datetime(df.index, format='%Y%m%d')
df.sort_index()
</code>```

Title: Change Index Type in Pandas

Body:
I am using Pandas in Python 3,

I have a dataframe whose index is like '20160727', but the datatype is 'object'.

I am trying to convert it into string type.

I tried:

data.index.astye(str, copy=False)

and data.index = data.index.map(str)

But even after these two operations,

I get:

data.index.dtype is dtype('O')

I want to use sort after converting the index to string. How can I convert the index to string datatype so that I can process it like a string?

Body:
In pandas, object is type string.

dtype('O') means it is a python type object.
You can see more info about this here

As an example of what you want to achieve:

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=[20160103, 20160102, 20160104, 20160101])
df.index =  pd.to_datetime(df.index, format='%Y%m%d')
df.sort_index()


问:
How can I hide JavaScript from older browsers?
Because not all browsers support JavaScript, we need a way to hide JavaScript from those browsers. If we do not JavaScript from those browsers, those browsers will treat JavaScript as page's content and thus display that code on the web page. How could i do that?</p>

答:
HTML comment can be used in the script tag :

```

OwnerDisplayName: Nikos Belegrinos

Body:
HTML comment can be used in the script tag :

<script language="JavaScript">
 <!--
  document.write(new Date( ));
 // -->
</script>


问:
Redim'd array error in commodore 64 basic?
I am getting a redim'd array error in my commodore 64 basic project

I am not however re dimensioning my 2d array nor do I go through the line of code more than once!

Error is on line 1140

Can anyone help me out?

Thanks!

Code:

```<code>10 print "start"
20 rem: go to line 1100 in order to fill board with "."s because this is
30 rem: the board's initialization
40 gosub 1100
50 rem: looping from i to x allows for horizontal aspect of board to be printed
60 rem: x represents the width dimension of board, in this case, 8
70 for i = 1 to x
80 rem: looping from j to x allows for vertical aspect of board to be printed
90 rem: x represents the height dimension of board, in this case, 8
100 for j = 1 to x
110 rem: board initialized with "."s is printed
120 print b3$(i,j),
130 rem: end of first for loop, looping from i to x put on 130; , USED 4 TAB
140 next
150 print
160 rem: end of second for loop, looping from j to x
170 next
180 rem: checks what at the random number is equal to; places word vertically
190 rem: if rand is < 50 and places the word horizontally if rand is > 50
200 if r1 < 50 then gosub 1510
210 if r1 > 50 then print "no"

1000 rem: random num generator generates a random integer
1050 rem: between 0 and 100
1040 rem: values between 0 and 100, inclusive
1050 r1 = int(100*rnd(1))+1

1060 rem: Subroutine Fill
1070 rem: Purpose: read and data construct which fills b3$(x,x) with
1080 rem: either "."s or other random words depending on whether or not
1090 rem: the subroutine has been run before.
1100 x = 8
1110 rem: x represents the dimension for the board; in this case,8
1120 rem: took out
1130 rem: array b3 = board = specifications for width and height (8)
1140 dim b3$(x, x)
rem: i to x allows the horizontal aspect of board to be filled with "."s
1150 for i = 0 to x
1160 rem: j to x allows the vertical aspect of board to be filled with "."s
1170 for j = 0 to x
1180 rem: board filled with dots horizontally and vertically
1190 b3$(i, j) = "."
1200 rem: end of first nested for loop
1210 next
1220 rem: end of second nested for loop
1230 next
1240 return
</code>```

答:
Line 200 looks suspect, because line 1510 doesn't exist.</p>

```<code>200 if r1 < 50 then gosub 1510
</code>```

Body:
I am getting a redim'd array error in my commodore 64 basic project

I am not however re dimensioning my 2d array nor do I go through the line of code more than once!

Error is on line 1140

Can anyone help me out?

Thanks!

Code:

10 print "start"
20 rem: go to line 1100 in order to fill board with "."s because this is
30 rem: the board's initialization
40 gosub 1100
50 rem: looping from i to x allows for horizontal aspect of board to be printed
60 rem: x represents the width dimension of board, in this case, 8
70 for i = 1 to x
80 rem: looping from j to x allows for vertical aspect of board to be printed
90 rem: x represents the height dimension of board, in this case, 8
100 for j = 1 to x
110 rem: board initialized with "."s is printed
120 print b3$(i,j),
130 rem: end of first for loop, looping from i to x put on 130; , USED 4 TAB
140 next
150 print
160 rem: end of second for loop, looping from j to x
170 next
180 rem: checks what at the random number is equal to; places word vertically
190 rem: if rand is < 50 and places the word horizontally if rand is > 50
200 if r1 < 50 then gosub 1510
210 if r1 > 50 then print "no"

1000 rem: random num generator generates a random integer
1050 rem: between 0 and 100
1040 rem: values between 0 and 100, inclusive
1050 r1 = int(100*rnd(1))+1

1060 rem: Subroutine Fill
1070 rem: Purpose: read and data construct which fills b3$(x,x) with
1080 rem: either "."s or other random words depending on whether or not
1090 rem: the subroutine has been run before.
1100 x = 8
1110 rem: x represents the dimension for the board; in this case,8
1120 rem: took out
1130 rem: array b3 = board = specifications for width and height (8)
1140 dim b3$(x, x)
rem: i to x allows the horizontal aspect of board to be filled with "."s
1150 for i = 0 to x
1160 rem: j to x allows the vertical aspect of board to be filled with "."s
1170 for j = 0 to x
1180 rem: board filled with dots horizontally and vertically
1190 b3$(i, j) = "."
1200 rem: end of first nested for loop
1210 next
1220 rem: end of second nested for loop
1230 next
1240 return

Body:
Line 200 looks suspect, because line 1510 doesn't exist.

200 if r1 < 50 then gosub 1510


问:
How to fix CopyFile() error 5 - access denied error
I am trying to write a copy file function that can be used on both Linux and Windows. It works on Linux, but on Windows, I get error code 5 when trying to use the WinApi function CopyFile().

In header File.h

This is the custom defined function in the File namespace that I should be able to use on both Linux and windows.

```<code>class File
{
public:
    static bool copyFile(std::string source, std::string destination);
private:
}
</code>```

In File.cpp

For Linux it is simple:

```<code>#ifdef __unix__
  #include "File.h"
  bool File::copyFile(std::string source, std::string destination)
  {
      std::string arg = source + " " + destination;
      return launchProcess("cp", arg);
  }
#endif
</code>```

In the Windows specific block of code, I use the WinAPI (#include < windows.h >) function CopyFile(). This accepts LPCWSTR data types instead of strings. To overcome this I have created a function that converts strings to LPCWSTR types.

```<code>#ifdef _WIN32
  #include "File.h"
  #include <Windows.h>
  std::wstring strtowstr(const std::string &str)
  {
      // Convert an ASCII string to a Unicode String
      std::wstring wstrTo;
      wchar_t *wszTo = new wchar_t[str.length() + 1];
      wszTo[str.size()] = L'\0';
      MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo,(int)str.length());
      wstrTo = wszTo;
      delete[] wszTo;
      return wstrTo;
  }

  bool File::copyFile(std::string source, std::string destination)
  {
      std::wstring wsource = strtowstr(source);
      std::wstring wdestination = strtowstr(destination);

      int result = CopyFileW(wsource.c_str(), wdestination.c_str(), TRUE);

          //for debugging...
          std::wcout << "The error is " << GetLastError() <<std::endl;
          std::wcout  << wsource.c_str() << std::endl;
          std::wcout << wdestination.c_str() << std::endl;

      if (result == 0)
      {
          return false;
      }
      return true;
  }
#endif
</code>```

In my Test Programme

```<code>TEST(all,main_copy_file)
{
    std::cout << "Testing copyFile() function..." << std::endl;

    std::string srcDir = File::currentWorkingDirectory() + "srcDir";
    File::makeDirectory(srcDir);

    std::string destDir = File::currentWorkingDirectory() + "destDir/";
    File::makeDirectory(destDir);

    File::makeFile(srcDir, "testFile", ".txt");

    ASSERT_TRUE(File::fileExists(srcDir + "/testFile.txt")) << "Error: Test file has not been generated" << std::endl;
    ASSERT_TRUE(File::directoryExists(destDir)) << "Error: Destination directory does not exist" <<std::endl;

    ASSERT_TRUE(File::copyFile(srcDir + "/testFile.txt", destDir)) << "Error: Coppy unsucsessfull" << std::endl;
    ASSERT_TRUE(File::fileExists(destDir + "/testFile.txt")) << "Error: CoppyFile() flagged as sucsessfull but file does not exist" << std::endl;

}
</code>```

In the application Output (on Windows)

```<code>/*
Testing copyFile() function...
The error is 5
C:\GIT\CorteX\Externals\OSAL\build\Debug/srcDir/testFile.txt
C:\GIT\CorteX\Externals\OSAL\build\Debug/destDir/

error: Value of: File::copyFile(srcDir + "/testFile.txt", destDir)
Actual: false
Expected: true
Error: Coppy unsucsessfull
*/
</code>```

Error code 5 is an access denied error. I think it gives this error when either the directory does not exist, the directory is open somewhere else, or I do not have permissions.

Since I have tested that the directory does exist, I think it must be one of the latter two. I might only have restricted Admin rights (I don't know), but I can paste into the "destDir" without admin permission. So maybe it thinks the directory is open? Is there a command that exists to make sure the directory is closed?

The test is successful when running on Linux.

答:
I know this is an old post, but for anyone who stumbles here needing more help:

CopyFile has the following constraints which if not met can give access denied error:

Insufficient permissions for the current user

File is in use

Filepath is a directory and not a file

File is read-only

In my case all the above were met, still I kept getting the same error. What helped me was a simple
SetFileAttributes(filePath,FILE_ATTRIBUTE_NORMAL)

Retrieving and Changing File Attributes

SetFileAttributes

Body:
I am trying to write a copy file function that can be used on both Linux and Windows. It works on Linux, but on Windows, I get error code 5 when trying to use the WinApi function CopyFile().

In header File.h

This is the custom defined function in the File namespace that I should be able to use on both Linux and windows.

class File
{
public:
    static bool copyFile(std::string source, std::string destination);
private:
}

In File.cpp

For Linux it is simple:

#ifdef __unix__
  #include "File.h"
  bool File::copyFile(std::string source, std::string destination)
  {
      std::string arg = source + " " + destination;
      return launchProcess("cp", arg);
  }
#endif

In the Windows specific block of code, I use the WinAPI (#include < windows.h >) function CopyFile(). This accepts LPCWSTR data types instead of strings. To overcome this I have created a function that converts strings to LPCWSTR types.

#ifdef _WIN32
  #include "File.h"
  #include <Windows.h>
  std::wstring strtowstr(const std::string &str)
  {
      // Convert an ASCII string to a Unicode String
      std::wstring wstrTo;
      wchar_t *wszTo = new wchar_t[str.length() + 1];
      wszTo[str.size()] = L'\0';
      MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo,(int)str.length());
      wstrTo = wszTo;
      delete[] wszTo;
      return wstrTo;
  }

  bool File::copyFile(std::string source, std::string destination)
  {
      std::wstring wsource = strtowstr(source);
      std::wstring wdestination = strtowstr(destination);

      int result = CopyFileW(wsource.c_str(), wdestination.c_str(), TRUE);

          //for debugging...
          std::wcout << "The error is " << GetLastError() <<std::endl;
          std::wcout  << wsource.c_str() << std::endl;
          std::wcout << wdestination.c_str() << std::endl;

      if (result == 0)
      {
          return false;
      }
      return true;
  }
#endif

In my Test Programme

TEST(all,main_copy_file)
{
    std::cout << "Testing copyFile() function..." << std::endl;

    std::string srcDir = File::currentWorkingDirectory() + "srcDir";
    File::makeDirectory(srcDir);

    std::string destDir = File::currentWorkingDirectory() + "destDir/";
    File::makeDirectory(destDir);

    File::makeFile(srcDir, "testFile", ".txt");

    ASSERT_TRUE(File::fileExists(srcDir + "/testFile.txt")) << "Error: Test file has not been generated" << std::endl;
    ASSERT_TRUE(File::directoryExists(destDir)) << "Error: Destination directory does not exist" <<std::endl;

    ASSERT_TRUE(File::copyFile(srcDir + "/testFile.txt", destDir)) << "Error: Coppy unsucsessfull" << std::endl;
    ASSERT_TRUE(File::fileExists(destDir + "/testFile.txt")) << "Error: CoppyFile() flagged as sucsessfull but file does not exist" << std::endl;

}

In the application Output (on Windows)

/*
Testing copyFile() function...
The error is 5
C:\GIT\CorteX\Externals\OSAL\build\Debug/srcDir/testFile.txt
C:\GIT\CorteX\Externals\OSAL\build\Debug/destDir/

error: Value of: File::copyFile(srcDir + "/testFile.txt", destDir)
Actual: false
Expected: true
Error: Coppy unsucsessfull
*/

Error code 5 is an access denied error. I think it gives this error when either the directory does not exist, the directory is open somewhere else, or I do not have permissions.

Since I have tested that the directory does exist, I think it must be one of the latter two. I might only have restricted Admin rights (I don't know), but I can paste into the "destDir" without admin permission. So maybe it thinks the directory is open? Is there a command that exists to make sure the directory is closed?

The test is successful when running on Linux.


问:
Using pointer to a struct to create linked list and Memory allocation in C
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

```<code>node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)
</code>```

答:
There are several possible scenarios:

The linked list is using malloc. The linked list is then responsible for the allocation and de-allocation of nodes. This is the standard implementation.

The linked list is using a statically allocated chunk of memory, ie a static array of fixed size. Such a linked list is more complex, as you would have to keep track of which parts of the array that contain data. You will also need to keep track of the linked list size.

The linked list is an "array of nodes with index lookup table". It is then not allocating any data, but instead every node contains contains array indices. The linked list will need to keep track of the list size.

The linked list is not performing any allocation. Allocation is done by the caller (statically or dynamically). In this case the linked list only keeps track of the next pointers and allocates nothing. This version is poor object-oriented design, as it breaks the private encapsulation of data.

EDIT after op change:
Seems you are using version 3 above then. Google for "linked list using array" or similar.

Body:
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)


问:
How to install vuetify 2.0 beta to the new vue cli project?
Vuetify 2.0.0-beta.0 has just been released and I want to try it out and play around in a new vue test application.
But I get errors when I try to install it in a fresh new project. Here are the steps I've taken.

I use @vue/cli v3.8.2 to create a new project with default settings:

```<code>vue create testapp
</code>```

which gives me successful result:

```<code>  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve
</code>```

Then I add vuetify plugin to the project with default (recommended) preset:

```<code>cd testapp
vue add vuetify
</code>```

which gives me success:

```<code>  Installing vue-cli-plugin-vuetify...

+ vue-cli-plugin-vuetify@0.5.0
added 1 package from 1 contributor and audited 23942 packages in 9.235s
found 0 vulnerabilities

✔  Successfully installed plugin: vue-cli-plugin-vuetify

? Choose a preset: Default (recommended)

  Invoking generator for vue-cli-plugin-vuetify...
  Installing additional dependencies...

added 11 packages from 49 contributors and audited 23980 packages in 9.252s
found 0 vulnerabilities

⚓  Running completion hooks...

✔  Successfully invoked generator for plugin: vue-cli-plugin-vuetify
</code>```

Now in package.json I see vuetify version:
"vuetify": "^1.5.5"

I now update it to the v2.0.0-beta.0 like this:

```<code>npm install vuetify@2.0.0-beta.0
</code>```

I get success again:

```<code>+ vuetify@2.0.0-beta.0
updated 1 package and audited 23980 packages in 10.302s
found 0 vulnerabilities
</code>```

Now when I try to run it:

```<code>npm run serve
</code>```

I get error:

```<code>> testapp@0.1.0 serve c:\temp\testapp
> vue-cli-service serve

 INFO  Starting development server...
 98% after emitting CopyPlugin

 ERROR  Failed to compile with 99 errors                                                                                6:17:04 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl
Failed to resolve loader: sass-loader
You may need to install it.
</code>```

If I install sass-loader like this:

```<code>npm i -D node-sass sass-loader
</code>```

I get success. Then I try to run it again:

```<code>npm run serve
</code>```

Now again I get different error:

```<code>  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve
</code>```0

I am stuck here as I don't know how to fix this error. npm install --save vuetify/src/stylus/app.styl obviously don't work. Also I couldn't make it work neither by following official vuetify page for this beta release.

答:
Don't include .styl files, it's deprecated basically.

Remove node-sass and install sass

$ npm uninstall node-sass
$ npm i -D sass
```

<p>And modify your <code>plugins/vuetify.js</code> file</p>

<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)
export default new Vuetify({ theme: { ... } })

</code>```

And main.js

new Vue({
  ...
  vuetify, // we add vuetify here
  render: (h) => h(App),
}).$mount('#app')
```

<p>Note theme options changed in v2, dark theme can now be customized, e.g. </p>

<pre class="lang-js prettyprint-override"><code>theme: {
  dark: true,
  themes: {
    light: {
      primary: '#42a5f5',
      //...
    },
    dark: {
      primary: '#2196F3.
    },
  },
},
options: {
  customProperties: true,
},
icons: {
  iconfont: 'md', // default is 'mdi'
}
</code>```

More in docs, and new style docs with regards to sass.

Body:
Vuetify 2.0.0-beta.0 has just been released and I want to try it out and play around in a new vue test application.
But I get errors when I try to install it in a fresh new project. Here are the steps I've taken.

I use @vue/cli v3.8.2 to create a new project with default settings:

vue create testapp

which gives me successful result:

  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve

Then I add vuetify plugin to the project with default (recommended) preset:

cd testapp
vue add vuetify

which gives me success:

  Installing vue-cli-plugin-vuetify...

+ vue-cli-plugin-vuetify@0.5.0
added 1 package from 1 contributor and audited 23942 packages in 9.235s
found 0 vulnerabilities

✔  Successfully installed plugin: vue-cli-plugin-vuetify

? Choose a preset: Default (recommended)

  Invoking generator for vue-cli-plugin-vuetify...
  Installing additional dependencies...

added 11 packages from 49 contributors and audited 23980 packages in 9.252s
found 0 vulnerabilities

⚓  Running completion hooks...

✔  Successfully invoked generator for plugin: vue-cli-plugin-vuetify

Now in package.json I see vuetify version:
"vuetify": "^1.5.5"

I now update it to the v2.0.0-beta.0 like this:

npm install vuetify@2.0.0-beta.0

I get success again:

+ vuetify@2.0.0-beta.0
updated 1 package and audited 23980 packages in 10.302s
found 0 vulnerabilities

Now when I try to run it:

npm run serve

I get error:

> testapp@0.1.0 serve c:\temp\testapp
> vue-cli-service serve

 INFO  Starting development server...
 98% after emitting CopyPlugin

 ERROR  Failed to compile with 99 errors                                                                                6:17:04 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl
Failed to resolve loader: sass-loader
You may need to install it.

If I install sass-loader like this:

npm i -D node-sass sass-loader

I get success. Then I try to run it again:

npm run serve

Now again I get different error:

 ERROR  Failed to compile with 1 errors                                                                                6:27:06 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl

I am stuck here as I don't know how to fix this error. npm install --save vuetify/src/stylus/app.styl obviously don't work. Also I couldn't make it work neither by following official vuetify page for this beta release.

Body:
Don't include .styl files, it's deprecated basically.

Remove node-sass and install sass

$ npm uninstall node-sass
$ npm i -D sass

And modify your plugins/vuetify.js file

import Vue from 'vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)
export default new Vuetify({ theme: { ... } })

And main.js

new Vue({
  ...
  vuetify, // we add vuetify here
  render: (h) => h(App),
}).$mount('#app')

Note theme options changed in v2, dark theme can now be customized, e.g.

theme: {
  dark: true,
  themes: {
    light: {
      primary: '#42a5f5',
      //...
    },
    dark: {
      primary: '#2196F3.
    },
  },
},
options: {
  customProperties: true,
},
icons: {
  iconfont: 'md', // default is 'mdi'
}

More in docs, and new style docs with regards to sass.


问:
Why does React Hooks Axios API call return twice?
Why does React Hooks Axios API Call return twice.. even with a check if it's loaded?

I am used to this.setState but trying to understand the reason behind this why it's showing up twice inside my console log.

My code:

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const [users, setUsers] = useState({ results: [] });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      await axios
        .get("https://jsonplaceholder.typicode.com/users/")
        .then(result => setUsers(result));

      setIsLoading(false);
    };

    fetchData();
  }, []);

  console.log(
    users.status === 200 && users.data.map(name => console.log(name))
  );

  return <h2>App</h2>;
};

export default App;
</code>```

答:
This is actually normal behavior. This is just how functional components work with useEffect(). In a class component the "this" keyword is mutated when the state changes. In functional components with hooks the function is called again, and each function has its own state. Since you updated state twice the function was called twice.

You can read these 2 very in dept articles by one of the creators of react hooks for more details.

https://overreacted.io/a-complete-guide-to-useeffect/

https://overreacted.io/how-are-function-components-different-from-classes/

Body:
Why does React Hooks Axios API Call return twice.. even with a check if it's loaded?

I am used to this.setState but trying to understand the reason behind this why it's showing up twice inside my console log.

My code:

import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const [users, setUsers] = useState({ results: [] });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      await axios
        .get("https://jsonplaceholder.typicode.com/users/")
        .then(result => setUsers(result));

      setIsLoading(false);
    };

    fetchData();
  }, []);

  console.log(
    users.status === 200 && users.data.map(name => console.log(name))
  );

  return
App
;
};

export default App;


问:
How do i find a value in column G of another sheet using vlookup?
I am working on a sheet called "Master Filtered" in which the values of column K should be filled with a lookup value from sheet "Ndex Positions" column G.

This is the piece of code I wrote

```<code>Sub MTL_OR_TOR()
Dim AcctNb As String
Dim result As String
Dim myRange As Range

Dim lastrow As Long
lastrow = Worksheets("Master Filtered").Cells(Rows.Count, 1).End(xlUp).Row

Worksheets("Master Filtered").Range("K3").Value = "MTL OR TOR"

Set myRange = Worksheets("Ndex Positions").Range("A2:G9000") 'Range in which the table MTL or TOR should be entered

For G = 4 To lastrow

AcctNb = Worksheets("Master Filtered").Cells(G, 3).Value
result = Application.WorksheetFunction.VLookup(AcctNb, myRange, 7, False)

Worksheets("Master Filtered").Range("K" & G).Value = result
Next

End Sub
</code>```

But this does not seem to work ("Unable to get the Vlookup property of the WorksheetFucntion class")

I don't know what is my error. If that helps, when I substitues the number 7 by the number 2 in the following line: "result = Application.WorksheetFunction.VLookup(AcctNb, myRange, 7, False) " everything works perfectly. But it is taking values from column B rather than column G. That's why I replaced the 2 by a 7 (index of letter  G in the alphabet). However, this does not seem to work.

Please let me know if you have any idea where my error could possibly be.

Thanks :)

答:
Try using Index/Match to be make exact references...

```<code>Application.Index(OutputRange, Application.Match(LookupVal, LookupRange,0))
</code>```

With your data, assuming I get the correct Match range (assuming you find your AcctNb in column A):

```<code>AcctNb = Worksheets("Master Filtered").Cells(G, 3).Value
With Worksheets("Ndex Positions")
    Application.Index(.Range("G:G"), Application.Match(AcctNb, .Range("A:A"),0))
End With
</code>```

Note the 0 in the Match means "exact match"

Body:
I am working on a sheet called "Master Filtered" in which the values of column K should be filled with a lookup value from sheet "Ndex Positions" column G.

This is the piece of code I wrote

Sub MTL_OR_TOR()
Dim AcctNb As String
Dim result As String
Dim myRange As Range

Dim lastrow As Long
lastrow = Worksheets("Master Filtered").Cells(Rows.Count, 1).End(xlUp).Row

Worksheets("Master Filtered").Range("K3").Value = "MTL OR TOR"

Set myRange = Worksheets("Ndex Positions").Range("A2:G9000") 'Range in which the table MTL or TOR should be entered

For G = 4 To lastrow

AcctNb = Worksheets("Master Filtered").Cells(G, 3).Value
result = Application.WorksheetFunction.VLookup(AcctNb, myRange, 7, False)

Worksheets("Master Filtered").Range("K" & G).Value = result
Next

End Sub

But this does not seem to work ("Unable to get the Vlookup property of the WorksheetFucntion class")

I don't know what is my error. If that helps, when I substitues the number 7 by the number 2 in the following line: "result = Application.WorksheetFunction.VLookup(AcctNb, myRange, 7, False) " everything works perfectly. But it is taking values from column B rather than column G. That's why I replaced the 2 by a 7 (index of letter  G in the alphabet). However, this does not seem to work.

Please let me know if you have any idea where my error could possibly be.

Thanks :)

Body:
Try using Index/Match to be make exact references...

Application.Index(OutputRange, Application.Match(LookupVal, LookupRange,0))

With your data, assuming I get the correct Match range (assuming you find your AcctNb in column A):

AcctNb = Worksheets("Master Filtered").Cells(G, 3).Value
With Worksheets("Ndex Positions")
    Application.Index(.Range("G:G"), Application.Match(AcctNb, .Range("A:A"),0))
End With

Note the 0 in the Match means "exact match"


问:
Update a property value without adding an additional value, in gremlin_node
I have written this gremlin query to update a property:

```<code>g.V("7cb57dad-d261-29cb-b886-affcd7442b73").property('tname', "updated tribename")
</code>```

Is this the correct way to update a property in gremlin-node? Or do I have to pass in single property to update a property without adding additional value?

答:
If you want to replace the prior value then you need the single keyword to be explicitly specified as in:

```<code>g.V("7cb57dad-d261-29cb-b886-affcd7442b73").
  property(single, 'tname', "updated tribename")
</code>```

Body:
I have written this gremlin query to update a property:

g.V("7cb57dad-d261-29cb-b886-affcd7442b73").property('tname', "updated tribename")

Is this the correct way to update a property in gremlin-node? Or do I have to pass in single property to update a property without adding additional value?

Body:
If you want to replace the prior value then you need the single keyword to be explicitly specified as in:

g.V("7cb57dad-d261-29cb-b886-affcd7442b73").
  property(single, 'tname', "updated tribename")


问:
python __init__ method in inherited class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3
</code>```

Thank you

答:
First of all you're mixing __init__ and __new__, they are different things. __new__ doesn't take instance (self) as argument, it takes class (cls).
As for the main part of your question, what you have to do is use super to invoke superclass' __init__.

Your code should look like this:

```<code>class initialclass(object):
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __init__(self):
        self.attr3 = 'three'
        super(inheritedclass, self).__init__()
</code>```

Body:
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

Thank you

Body:
First of all you're mixing __init__ and __new__, they are different things. __new__ doesn't take instance (self) as argument, it takes class (cls).
As for the main part of your question, what you have to do is use super to invoke superclass' __init__.

Your code should look like this:

class initialclass(object):
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __init__(self):
        self.attr3 = 'three'
        super(inheritedclass, self).__init__()


问:
How can I Fix an ImportError
So I am stuck on how can I fix the import error for imresize. I installed all the things I needed like installing Pillow but I haven't been able to find a solution. Also the code that I trying to run is from this github link https://github.com/CSAILVision/IBD
Also side note I do not own this code nor was not the original arthor of it. This is for a research project that I am apart of. In addition I try asked the original arthor with a fix but haven't heard back from them at all.

Installing Pillow, Replacing with code: from scipy.misc.pilutil import imread, installing Pillow-3.3.1-cp27-cp27m-win32.whl, Unninstall Pil and installing Pillow, Reinstalling Pillow.

```<code>from util.image_operation import *
from PIL import Image
import numpy as np
from imageio import imresize, imread
from visualize.plot import random_color
from torch.autograd import Variable as V
import torch
</code>```

I expect it to run but print out the image but it doesn't.

```<code>Traceback (most recent call last):

     File "test.py", line 4, in <module>
        from loader.model_loader import loadmodel

      File "/home/joshuayun/Desktop/IBD/loader/model_loader.py", line 5, in <module>

     from util.feature_operation import hook_feature, hook_grad
      File "/home/joshuayun/Desktop/IBD/util/feature_operation.py", line 6, in <module>
        from imageio import imresize, imread, imsave
    ImportError: cannot import name 'imresize'
</code>```

答:
If you want to work with the code as is, i would recommend creating a new environment, and installing an old version of scipy (0.19.1 should do the trick). In your new environment, assuming you are using conda, do:

```<code>conda install scipy==0.19.1
</code>```

If you use pip instead:

```<code>pip install scipy==0.19.1
</code>```

Title: How can I Fix an ImportError

Body:
So I am stuck on how can I fix the import error for imresize. I installed all the things I needed like installing Pillow but I haven't been able to find a solution. Also the code that I trying to run is from this github link https://github.com/CSAILVision/IBD
Also side note I do not own this code nor was not the original arthor of it. This is for a research project that I am apart of. In addition I try asked the original arthor with a fix but haven't heard back from them at all.

Installing Pillow, Replacing with code: from scipy.misc.pilutil import imread, installing Pillow-3.3.1-cp27-cp27m-win32.whl, Unninstall Pil and installing Pillow, Reinstalling Pillow.

from util.image_operation import *
from PIL import Image
import numpy as np
from imageio import imresize, imread
from visualize.plot import random_color
from torch.autograd import Variable as V
import torch

I expect it to run but print out the image but it doesn't.

Traceback (most recent call last):

     File "test.py", line 4, in <module>
        from loader.model_loader import loadmodel

      File "/home/joshuayun/Desktop/IBD/loader/model_loader.py", line 5, in <module>

     from util.feature_operation import hook_feature, hook_grad
      File "/home/joshuayun/Desktop/IBD/util/feature_operation.py", line 6, in <module>
        from imageio import imresize, imread, imsave
    ImportError: cannot import name 'imresize'

Body:
If you want to work with the code as is, i would recommend creating a new environment, and installing an old version of scipy (0.19.1 should do the trick). In your new environment, assuming you are using conda, do:

conda install scipy==0.19.1

If you use pip instead:

pip install scipy==0.19.1


问:
How to combine multiple arrays in javascript?
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

```<code>var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];
</code>```

And I want this output:

```<code>var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];
</code>```

答:
If you expect to always have the same number of arrays, I find this more readable though a bit redundant:

let arr1 = [
  'a', 'b'
];
let arr2 = [
  'c', 'd'
];
let arr3 = [
  'e'
];

let result = arr1.flatMap(one =>
    arr2.flatMap(two =>
        arr3.map(three => [one, two, three])));
console.log(result);```
</div>
</div>
</p>

<p>If you're not always expecting 3 arrays or prefer a generic func to multiply an arbitrary number of arrays:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr1 = [
  'a', 'b'
];
let arr2 = [
  'c', 'd'
];
let arr3 = [
  'e'
];

let multiply = (...arrays) =>
    arrays.reduce((results, array) =>
        results.flatMap(result => array.map(a => [...result, a])), ['']);

let results = multiply(arr1, arr2, arr3);
console.log(results);</code>```

Body:
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];

And I want this output:

var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];

Body:
If you expect to always have the same number of arrays, I find this more readable though a bit redundant:

let arr1 = [
  'a', 'b'
];
let arr2 = [
  'c', 'd'
];
let arr3 = [
  'e'
];

let result = arr1.flatMap(one =>
    arr2.flatMap(two =>
        arr3.map(three => [one, two, three])));
console.log(result);

If you're not always expecting 3 arrays or prefer a generic func to multiply an arbitrary number of arrays:

let arr1 = [
  'a', 'b'
];
let arr2 = [
  'c', 'd'
];
let arr3 = [
  'e'
];

let multiply = (...arrays) =>
    arrays.reduce((results, array) =>
        results.flatMap(result => array.map(a => [...result, a])), ['']);

let results = multiply(arr1, arr2, arr3);
console.log(results);


问:
Resource with a single attribute. Sign that something smells?
I have a book model and a notes model. Each book can have many notes.

```<code># note.rb
id | book_id | content | page_number | author_id |
</code>```

I want to run a lot of queries like

Get all the notes for page 43 of a certain book

Show all the noted pages of a certain book

These types of queries seem to favor making a separate noted_pages model so that a book can have many noted_pages and each noted_page can have many notes. This is fine but my noted_pages table would effectively just have an id column and a page_number column which doesn't sit right with me.

Is there a more standard way to implement this kind of setup or is my thinking ok?

答:
If you want a many to many relationship, as in a book can have many notes, and notes can have many books, you must have a join table like you stated.

It would look like:

```<code>noted_page
--------------
id   book_id note_id
</code>```

This is just general practice, whenever you have a many-to-many relationship you MUST have a join table.

(Some frameworks/orm's don't require you to have a id column, but as far as I know, Rails/ActiveRecord does require it.)

Body:
I have a book model and a notes model. Each book can have many notes.

# note.rb
id | book_id | content | page_number | author_id |

I want to run a lot of queries like

Get all the notes for page 43 of a certain book

Show all the noted pages of a certain book

These types of queries seem to favor making a separate noted_pages model so that a book can have many noted_pages and each noted_page can have many notes. This is fine but my noted_pages table would effectively just have an id column and a page_number column which doesn't sit right with me.

Is there a more standard way to implement this kind of setup or is my thinking ok?

Body:
If you want a many to many relationship, as in a book can have many notes, and notes can have many books, you must have a join table like you stated.

It would look like:

noted_page
--------------
id   book_id note_id

This is just general practice, whenever you have a many-to-many relationship you MUST have a join table.

(Some frameworks/orm's don't require you to have a id column, but as far as I know, Rails/ActiveRecord does require it.)


问:
Accounting for "missing" values, dealing with instances when 0's should be entered
Okay, so I know this looks like a million other problems of the same type. But I dont think I've seen one with this exact issue so here I am  haha.

Lets say you have a dataframe of sales by customer, sku and date. All is good in the world. But what if you had this df, it was huge (hundreds of customers, and if we wanted to punish ourselves further, hundreds of skus each, every week). Then, after grouping by customer, sku, and week, then summarizing, we realize that not all skus are bought by all customers, every week. This complicates things.

For example, without a line entry for each week by customer with a revenue value of 0 for every sku that wasnt bought, plotting with geom_line and geom_smooth becomes inaccurate. the lines continue on their trajectory, instead of dropping to zero.

I might just be very stupid right now, but how do I introduce all these entries with 0 revenue every time there is a week where a sku wasnt bought by any given customer so that I get the appropriate graphs I would need? Or is there an entirely different way of dealing with this sort of thing?

```<code># Extremely simplified
# Plot from DF WO zeros

df_plot<- data.frame(x=c(1,2,3,4,5,10), y=c(1,2,3,4,5,10))
ggplot(df_plot,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()

# Theoretical plot where we have zeros where no sales were made

df_plot2<- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(1,2,3,4,5,0,0,0,0,10))
ggplot(df_plot2,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()
</code>```

I dont know if theres just an easy way for dealing with this in the graph? Otherwise I need to add 0's in the revenue column for every week a sku wasnt bought by the customer. If that's the case, is there an efficient way of doing that? Thanks as always!

答:
You can fill missing values for levels of a factor variable or continuous variable that are not present in the data set with tidyr::complete and tidyr::full_seq.

In your case, I think you want:

```<code># Load required packages.
library(ggplot2)
library(tidyr)

# Create data frame with 0 values omitted.
df_plot<- data.frame(x=c(1,2,3,4,5,10), y=c(1,2,3,4,5,10))
ggplot(df_plot,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()

# Fill gap in continuous variable with 0's and plot.
df_plot %>%
  complete(x = full_seq(x, 1), fill = list(y = 0)) %>%
  ggplot(., aes(x, y)) +
  geom_point() +
  geom_smooth() +
  geom_line()
</code>```

Alternatively, you can do this with the statar package's fill_gap function:

```<code>df_plot %>%
statar::fill_gap(x, full = TRUE) %>%
  replace_na(list(y = 0)) %>%
  ggplot(., aes(x, y)) +
  geom_point() +
  geom_smooth() +
  geom_line()
</code>```

Body:
Okay, so I know this looks like a million other problems of the same type. But I dont think I've seen one with this exact issue so here I am  haha.

Lets say you have a dataframe of sales by customer, sku and date. All is good in the world. But what if you had this df, it was huge (hundreds of customers, and if we wanted to punish ourselves further, hundreds of skus each, every week). Then, after grouping by customer, sku, and week, then summarizing, we realize that not all skus are bought by all customers, every week. This complicates things.

For example, without a line entry for each week by customer with a revenue value of 0 for every sku that wasnt bought, plotting with geom_line and geom_smooth becomes inaccurate. the lines continue on their trajectory, instead of dropping to zero.

I might just be very stupid right now, but how do I introduce all these entries with 0 revenue every time there is a week where a sku wasnt bought by any given customer so that I get the appropriate graphs I would need? Or is there an entirely different way of dealing with this sort of thing?

# Extremely simplified
# Plot from DF WO zeros

df_plot<- data.frame(x=c(1,2,3,4,5,10), y=c(1,2,3,4,5,10))
ggplot(df_plot,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()

# Theoretical plot where we have zeros where no sales were made

df_plot2<- data.frame(x=c(1,2,3,4,5,6,7,8,9,10), y=c(1,2,3,4,5,0,0,0,0,10))
ggplot(df_plot2,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()

I dont know if theres just an easy way for dealing with this in the graph? Otherwise I need to add 0's in the revenue column for every week a sku wasnt bought by the customer. If that's the case, is there an efficient way of doing that? Thanks as always!

Body:
You can fill missing values for levels of a factor variable or continuous variable that are not present in the data set with tidyr::complete and tidyr::full_seq.

In your case, I think you want:

# Load required packages.
library(ggplot2)
library(tidyr)

# Create data frame with 0 values omitted.
df_plot<- data.frame(x=c(1,2,3,4,5,10), y=c(1,2,3,4,5,10))
ggplot(df_plot,aes(x,y))+
  geom_point()+
  geom_smooth()+
  geom_line()

# Fill gap in continuous variable with 0's and plot.
df_plot %>%
  complete(x = full_seq(x, 1), fill = list(y = 0)) %>%
  ggplot(., aes(x, y)) +
  geom_point() +
  geom_smooth() +
  geom_line()

Alternatively, you can do this with the statar package's fill_gap function:

df_plot %>%
statar::fill_gap(x, full = TRUE) %>%
  replace_na(list(y = 0)) %>%
  ggplot(., aes(x, y)) +
  geom_point() +
  geom_smooth() +
  geom_line()


问:
How to drop multiple columns from a pandas dataframe if it contains any alphabet (non numeric)?
I have pulled data from hive into python using pyhive. Now I have created a dataframe from the data imported. The dtype of all the columns in the dataframe is object. I wanted to know the best way to drop any column in the data frame that contains an alphabet(non numeric)?

df.select_dtypes(['number']) wouldnt work since all my columns are dtype=object.

答:
The following will convert numeric strings to number dtypes and select only the numeric dtypes from the DataFrame.</p>

```<code>#convert number columns to numeric
df=df.apply(pd.to_numeric, errors='ignore')
df=df.select_dtypes('number')
</code>```

Body:
The following will convert numeric strings to number dtypes and select only the numeric dtypes from the DataFrame.

#convert number columns to numeric
df=df.apply(pd.to_numeric, errors='ignore')
df=df.select_dtypes('number')


问:
SQL Timeout Errors
I'm getting a problem with only 1 of about 30 sites we run on a W2003 Web Server.

Probably for about 25% of the day, the website constantly returns : SQL Timeout Errors on  various connections to SQL (using ODBC)

I have checked and updated the ODBC drivers to the latest that I could find (3.5.x?) and I am also checking the SQL server to see if that has problems (another server running on the same network connected via Gb LAN)

The IIS log files return "[Microsoft][ODBC_SQL_Server_Driver]Timeout_expired"

I experienced the problem this morning, so tried to reboot the SQL server to see if it was a load related problem or something - but the site continued to generate these errors for about 20 minutes after the reboot (even though all our other sites were working at this point) - then it stopped timing out and is now working again.

I tried to extend the Timeout of SQL connections for the website to see if this changed something, but it hasn't seem to have done a thing.

This site has been running for about 3 years continually with no problems and we haven't changed anything on our servers for some time now - this started happening around Christmas time, but has got more and more regular since.

I have been through all the code to make sure that DB Connections are being open/closed correctly (Site is classic ASP), and ensured that it's not opening too many concurrent connections - but all to no avail and I'm starting to run out of ideas.... anyone?

My only thought is to change to OLEDB connection instead of an ODBC - but before I do that, I wanted to check that there wasn't something else I've missed which I could try first.

Thanks in Advance!

Carl.

答: If those things above did not work, I would check your page file (PF) usage under Task Manager and see where it is at. You can get timeout errors from lacking virtual memory. If it looks like it is near the top, consider increasing it higher. I got a lot of SQL timeout errors sporadically and in different parts of my application. It turned out it was a performance issue. I would recommend at least 4000mb of page file depending on the amount of ram you have on your server. </p>

OwnerDisplayName: Carl Crawley

ContentLicense: CC BY-SA 2.5

Title: SQL Timeout Errors


问:
Is there a problem in mixing @Transactional with "jpaApi.withTransaction"?
I was having some trouble making transactions work properly in my play application, and my code is structured in such a way that I cannot afford the time to do it "properly" as it shows in the Play Framework documentation.

Only using @Transactional was not enough because for some reason  it was not rolling back when I threw my own exceptions.

So this is the way I managed to make transactions work:

```<code>@Transactional
public Result myAction() {
    try {
        return ok(Json.toJson(myServiceClass.doStuff()));
    } catch (BusinessRuleException e) {
        return badRequest(Json.toJson("error"));
    }
}

...

public class MyServiceClass {
    public Bill doStuff() throws BusinessRuleException {
        return jpaApi.withTransaction(() -> {

               //...do a bunch of stuff here

        });
    }
}
</code>```

Is this fine? Can it cause problems later for some reason?

答: @Transactional and JPAApi.withTransaction under the hood creates new instances of entity managers. This entity managers serves as unit of work. In this situation you wind up with two running transactions that don't connected. So I guess it's better not mix this two approaches and choose one of them.

Body:
I was having some trouble making transactions work properly in my play application, and my code is structured in such a way that I cannot afford the time to do it "properly" as it shows in the Play Framework documentation.

Only using @Transactional was not enough because for some reason  it was not rolling back when I threw my own exceptions.

So this is the way I managed to make transactions work:

@Transactional
public Result myAction() {
    try {
        return ok(Json.toJson(myServiceClass.doStuff()));
    } catch (BusinessRuleException e) {
        return badRequest(Json.toJson("error"));
    }
}

...

public class MyServiceClass {
    public Bill doStuff() throws BusinessRuleException {
        return jpaApi.withTransaction(() -> {

               //...do a bunch of stuff here

        });
    }
}

Is this fine? Can it cause problems later for some reason?


问:
MonoTouch: proper way to handle ReceiveMemoryWarning
I have a MonoTouch app out in the wild that dies sometimes with mprotect errno 12 (out of memory), and it always seems to get at least one ReceiveMemoryWarning notification beforehand.

I'm wondering what the right way to respond to this is. There are two types of things that my app could free: OpenGL textures and managed memory.

My questions about this are:

OpenGL textures: Will deleting OpenGL textures help?

Managed memory: I can't free this directly, but I can get null out references to it. Is that enough?

GC.Collect: Should I call GC.Collect() at the end of my handler? Does GC.Collect do anything immediately, or does it schedule a collection for the future?

Anything else I can/should do in response to this?

答:
I ran into this a while back in my app using OpenGL. For me, it really was a memory leak.

[DllImport("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics")]
public static extern void CGDataProviderRelease(IntPtr provider);

and after you call
GL.TexImage2D.....

you need to call CGDataProviderRelease(data.Handle);

now that being said, you might want to look at this:

http://forums.monotouch.net/yaf_postst1541.aspx


问:
How to set a Heroku hosted Twitter bot to run periodically, shutting off the dyno between runs?
I would like to run my .jar file once every hour or so. Basically, turn the dyno on and let the program run, then turn it off. I am curious if this is possible with a scheduler, and if so, how to implement this method.

I've done Thread.sleep(millis) and just looped around and restarted the programs, but this keeps the dynos on, and you only get 550 free dyno hours which will be used up in less than a month by one bot that is enabled constantly.

Here is the procfile, not sure if it'd be useful.

```<code>worker: java -jar myapp.jar
</code>```

I assume the correct method is to install a scheduler, but the documentation on this is confusing and insufficient. What would be the simplest way to solve this problem? I have 4 bots I would like to host, and they shouldn't get anywhere near the monthly allowance as long as they're just cutting on every now and then.

答:
One thing I could try will be set up free CI/CD e.g, travis-ci, and set to periodical deploy, not pull based or commit based, and make travis-ci pipeline to deploy your app to Heroku periodically ( with out without entire build? ).

And probably you need to change your app to execute only once and then exit?

Another way might be, if you use free tier, if web app runs in free Dynos tier doesn't get any traffic in 30 minutes, it will sleep and those sleep time won't be count as your free time. So I guess you can set travis-ci or something else that runs in every 30+ minutes ( maybe 40 mins to make sure ) and hit your app, and then app runs just once. With this, you'll only use less than 12 hours a day, means you'll still be safe with those 550 free Dynos hours.

Body:
I would like to run my .jar file once every hour or so. Basically, turn the dyno on and let the program run, then turn it off. I am curious if this is possible with a scheduler, and if so, how to implement this method.

I've done Thread.sleep(millis) and just looped around and restarted the programs, but this keeps the dynos on, and you only get 550 free dyno hours which will be used up in less than a month by one bot that is enabled constantly.

Here is the procfile, not sure if it'd be useful.

worker: java -jar myapp.jar

I assume the correct method is to install a scheduler, but the documentation on this is confusing and insufficient. What would be the simplest way to solve this problem? I have 4 bots I would like to host, and they shouldn't get anywhere near the monthly allowance as long as they're just cutting on every now and then.