问:
How to display all articles with same height
I'm working on a website where i want to display the recommended videos from my youtube channel. I can load all the videos and display them but after 4-5 rows theres a problem. Some Videos are a few milimeters heigher and destroy the whole layout.

Those are the first two rows and how it should be

And then the 4 and the 5 row looks like this

The 3th video in the first row is few milimeteres heigher and this destroy the whole layout so how can i format all cells the same i ve tried adding display:table to the parent and display:table-cell to thec hild without success

Here is the HTML and the JS

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
    <link href="../css/youtube.css" type ="text/css" rel="stylesheet">
    <link href="../css/navigation.css" type ="text/css" rel="stylesheet">

</head>
<body>
<div id ="main">
<div class="menu">

    <div class="hori-menu">
    <ul>
      <ul>
          <li><a href="#home">Weiterschauen</a></li>
          <li><a href="userseries.html">Meine Serien</a></li>
          <li><a href="soon.html">Demnächst</a></li>
          <li><a href="suggestion.html">Vorschläge</a></li>
          <li><a class="active" href="youtube.html">YouTube</a></li>
          <li><a href="#about">Mitbewohner</a></li>
        </ul>
    </ul>
    </div>
    </div>

    <main id="container">
        <section id="video"></section>
        <div id="videos"></div>
    </main>

</body>

<script language="JavaScript">
    var key = '...';
    var videos = [];
    var totalResults = 0;

    $(document).ready(function(){
        getMyChannel();
    });

    function shuffle() {
        for (let i = videos.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [videos[i], videos[j]] = [videos[j], videos[i]];
        }

    }

    function getMyChannel(){
        var url = "https://www.googleapis.com/youtube/v3/activities";
        var options = {
            part: 'contentDetails',
            channelId: 'UCAe66hs74KDbpvK2x3ZrTXA',
            maxResults: 20,
            key: key
        }
        loadUser();

        function loadUser(){
            $.getJSON(url, options, function(data){
                loadUsersChannels(data);
            });
        }

        function loadUsersChannels(data){

            $.each(data.items, function (i, item) {
                var id = item.contentDetails.subscription.resourceId.channelId;
                getChannel(id);
            });
        }
    }

    function getChannel(id){
        var url = "https://www.googleapis.com/youtube/v3/channels";
        var options = {
            part: 'snippet,contentDetails',
            id: id,
            maxResults: 20,
            key: key

        }

        loadLists();

        function loadLists(){
            $.getJSON(url, options, function(data) {
                loadPlaylists(data);

            });

        }

        function loadPlaylists(data){
            $.each(data.items, function (i, item) {
                var id = item.contentDetails.relatedPlaylists.uploads;
                getPlaylist(id);
            });

        }
    }

    function getPlaylist(playlistId){

    var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';

    var options = {
        part: 'snippet',
        key: key,
        maxResults: 20,
        playlistId: playlistId
    }

    loadVids();

    function loadVids() {
        $.getJSON(URL, options, function (data) {
           // var id = data.items[0].snippet.resourceId.videoId;
           // mainVid(id);
            resultsLoop(data);
        });
    }

    function mainVid(id) {
        $('#video').html(`
            <iframe width="560" height="315" src="https://www.youtube.com/embed/${id}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
        `);
    }

    function resultsLoop(data) {

        totalResults = totalResults + data.pageInfo.resultsPerPage;

        $.each(data.items, function (i, item) {

            var thumb = item.snippet.thumbnails.medium.url;
            var title = item.snippet.title;
            var vid = item.snippet.resourceId.videoId;

            $('#videos').append(`
                <article class="item" data-key="${vid}">
                        <div class="details">
                        <img src="${thumb}" alt="" class="thumb">
                        <h4>${title}</h4>
                    </div>
                </article>
            `);
        });

    }

        // CLICK EVENT
    $('main').on('click', 'article', function () {
        var id = $(this).attr('data-key');
        mainVid(id);
    });

}

    </script>
  </body>
</html>
</code>```

And here is the css

```<code>@mixin font-base {
    padding: 0;
    margin: 0;
    line-height: 1.3;
    font-weight: 600;
}

h4 {
    @include font-base;
}

p {
    @include font-base;
    color: grey;
    font-size: 0.7rem;
}

.container {
    width: 100%;
    background-color: #fff;
    margin: 0 auto;
    display:table;
    border-spacing: 10px;
}

section {
    height:100%;
    margin-top: 4%;
    margin-bottom:2%;
    text-align:center;
    background-color:#eee;

}
iframe{
    width:100%;
    height:900px;
    background-color:#65626b;
    padding:8px 12px;
}
#videos{
    overflow:hidden;
}

article {
    margin:5px 5px;
    width:24%;
    float:left;
    background-color:#eee;
    border-radius:8px;

}
article div{
    border: 1px solid black;
    border-radius: 8px;
    padding: 8px 12px;

}
article:hover{
    background-color:#65626b;
    color:white;

}

.thumb {
    width: 100%;
    border-radius:8px;
}
</code>```

For more infos on code please ask. Thank you!

答: You can try using min-height or max-height CSS property on article divs.

Body:
I'm working on a website where i want to display the recommended videos from my youtube channel. I can load all the videos and display them but after 4-5 rows theres a problem. Some Videos are a few milimeters heigher and destroy the whole layout.

Those are the first two rows and how it should be

And then the 4 and the 5 row looks like this

The 3th video in the first row is few milimeteres heigher and this destroy the whole layout so how can i format all cells the same i ve tried adding display:table to the parent and display:table-cell to thec hild without success

Here is the HTML and the JS

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <link href="../css/youtube.css" type ="text/css" rel="stylesheet">
    <link href="../css/navigation.css" type ="text/css" rel="stylesheet">

Weiterschauen

Meine Serien

Demnächst

Vorschläge

YouTube

Mitbewohner

And here is the css

@mixin font-base {
    padding: 0;
    margin: 0;
    line-height: 1.3;
    font-weight: 600;
}

h4 {
    @include font-base;
}

p {
    @include font-base;
    color: grey;
    font-size: 0.7rem;
}

.container {
    width: 100%;
    background-color: #fff;
    margin: 0 auto;
    display:table;
    border-spacing: 10px;
}

section {
    height:100%;
    margin-top: 4%;
    margin-bottom:2%;
    text-align:center;
    background-color:#eee;

}
iframe{
    width:100%;
    height:900px;
    background-color:#65626b;
    padding:8px 12px;
}
#videos{
    overflow:hidden;
}

article {
    margin:5px 5px;
    width:24%;
    float:left;
    background-color:#eee;
    border-radius:8px;

}
article div{
    border: 1px solid black;
    border-radius: 8px;
    padding: 8px 12px;

}
article:hover{
    background-color:#65626b;
    color:white;

}

.thumb {
    width: 100%;
    border-radius:8px;
}

For more infos on code please ask. Thank you!


来源: stackexchange

问:
Syncing localStorage
I'm looking for a solution that allows a browser's localStorage to be less local, so that people can access their data on multiple devices. The traditional way is to run a database on a server and have people log in; but I'm trying to avoid doing that. I'd like the server side to be lightweight - perhaps even completely static if possible - and to not have the job of safely storing passwords, worrying about data protection etc.

Many browsers have a login of some sort -- Google Account, Firefox Account etc -- that ties a user's browsers together. So the ideal solution would be to store data in localStorage, but use that account to sync across devices. There are interfaces such as chrome.storage that seem to be available to packaged apps, but not to ordinary web pages.

Is something like this possible with present technologies?

答: you can use api that save all data ...api for per user after login load data from back-end after that save in local Storage </p>

ContentLicense: CC BY-SA 3.0

Title: Syncing localStorage

ContentLicense: CC BY-SA 4.0


问:
Filtering SQL rows based on values from other rows
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

```<code>user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464
</code>```

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

The result I want, where John Brown (22307) is excluded, is:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?

答:
I would just use not exists with a correlated subquery to ensure that no other record exists with the same user_id and a 'Death' status:

```<code>select a.*
from agentsTable a
where not exists (
    select 1
    from agentsTable a1
    where a1.user_id = a.user_id and a1.agent_status = 'Death'
)
</code>```

Body:
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

The result I want, where John Brown (22307) is excluded, is:

user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?

Body:
I would just use not exists with a correlated subquery to ensure that no other record exists with the same user_id and a 'Death' status:

select a.*
from agentsTable a
where not exists (
    select 1
    from agentsTable a1
    where a1.user_id = a.user_id and a1.agent_status = 'Death'
)


问:
How to change the size of blinking bar/line for specific UITextField?

i'm working on a project(Swift4,Xcode 9.2) which has a feature to get text input and the blinking bar/line should be of big size (it should be Square instead of bar/line), so i placed a UITextField for Text but i don't understand how to change the size of that blinking line/bar.

So, is it possible to change the size of line/bar? and if Yes then how to do it?
i know how to change the color of that line/bar but this is something different.

答:
There are some unnecessary lines of codes, so this is the revised:</p>

```<code>class CustomTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        var rect = super.caretRect(for: position)
        rect = CGRect(x: rect.origin.x, y: .zero, width: 15, height: 30)
        return rect
    }
}
</code>```

Body:
There are some unnecessary lines of codes, so this is the revised:

class CustomTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        var rect = super.caretRect(for: position)
        rect = CGRect(x: rect.origin.x, y: .zero, width: 15, height: 30)
        return rect
    }
}


问:
How to get date time from UTC date time fromat?
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

```<code>String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}
</code>```

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

答:
```<code>String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
</code>```

Body:
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"


问:
How to change page title with routing in Angular application?
Is there any npm module/ other way like React-Helmet that allows us to change page title as we route through our Angular application?

PS: I am using Angular 5.

答:
```<code>// Component.ts
</code>```
<pre class="lang-js prettyprint-override"><code>
    import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
    import { filter } from 'rxjs/operators';

    @Component({
      selector: 'app-component',
      templateUrl: './component.html',
      styleUrls: ['./component.css']
    })
    export class Component implements OnInit {

      constructor(private router: Router, private route: ActivatedRoute) { }

      path: string[] = [];
      pathTitle: string;

      ngOnInit() {
        this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
            this.path = event.url.substring(1).split('/');  //  URL => stackOverflow
            this.pathTitle = this.route.root.firstChild.snapshot.data.title; // data.title => stack Overflow
        });
      }

    // app-routing.module.ts
    const routes: Routes = [
      {
        path: 'stackOverflow',
        component: Component,
        data: {title: 'stack Overflow'}
       }
    ];
</code>```

Body:
// Component.ts

    import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
    import { filter } from 'rxjs/operators';

    @Component({
      selector: 'app-component',
      templateUrl: './component.html',
      styleUrls: ['./component.css']
    })
    export class Component implements OnInit {

      constructor(private router: Router, private route: ActivatedRoute) { }

      path: string[] = [];
      pathTitle: string;

      ngOnInit() {
        this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
            this.path = event.url.substring(1).split('/');  //  URL => stackOverflow
            this.pathTitle = this.route.root.firstChild.snapshot.data.title; // data.title => stack Overflow
        });
      }

    // app-routing.module.ts
    const routes: Routes = [
      {
        path: 'stackOverflow',
        component: Component,
        data: {title: 'stack Overflow'}
       }
    ];


问:
Keyboard is hidden on orientation change
My keyboard is hidden when the orientation of the android phone changes to landscape. What should I do in order to show my keyboard?</p>

答:
Add this on your code</p>

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
</code>```

Body:
Add this on your code

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);


问:
Getting wrong data from database even if I am fetching something different in laravel api
Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.

Here is my model code

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';

}
</code>```

Here is my Controller Code

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\user;

class GetController extends Controller
{
    public function databybusinessid($business _id){
    $users = new user();
    $users = user::find($business _id);
    return response()->json($users);
}
}
</code>```

Thank you so much

答:
You are using user::find($business _id)

find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.

```<code>class user extends Model
{
    protected $table = 'business';

    protected $primaryKey = 'business_id';
}
</code>```

If in doubt, you can also fetch database record by a specific column using where

```<code> $users = user::where('business_id', '=', $business _id)->get()
</code>```

Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent

Body:
Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.

Here is my model code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';

}

Here is my Controller Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\user;

class GetController extends Controller
{
    public function databybusinessid($business _id){
    $users = new user();
    $users = user::find($business _id);
    return response()->json($users);
}
}

Thank you so much

Body:
You are using user::find($business _id)

find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.

class user extends Model
{
    protected $table = 'business';

    protected $primaryKey = 'business_id';
}

If in doubt, you can also fetch database record by a specific column using where

 $users = user::where('business_id', '=', $business _id)->get()

Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent


问:
How to properly call methods with no input arguments
The Qt Documentation provides the method

```<code>bool QOpcUaNode::callMethod(const QString &methodNodeId, const QVector<QOpcUa::TypedVariant> &args = QVector<QOpcUa::TypedVariant>())
</code>```

for calling methods on the Opc Ua Server. Regarding this Method I have 2 Questions:

What exactly is methodNodeId ? I imagine it is the Id of the Node I want to call, but if this is the case, why would the function not be static instead ?

How to call methods with 0 input arguments? trying to call myNode->callMethod(methodNodeId) without specifiying further arguments still returns BadTooManyArguments, but there is really not other way I could see it being used.

答:
An OPC UA Call Service Request need to contain an Array of CallMethodRequest
A CallMethod Request is defined as following in the OPC UA Specification:

objectId (NodeId) - The NodeId shall be that of the Object or ObjectType on which the Method is invoked. -> I guess this is your QOpcUaNode

methodId (NodedId) - The NodeId of the Method to invoke.

inputArguments[] (BaseDataType) - List of input argument values.

You will have to check your Method definition and maybe your server. Your call of callMethod(methodId) without arguments is fine. Depending of the Method you are calling, this call might succeed or not.

Anyway your OPC UA Server might also have an issue sending Bad_TooManyArguments instead of Bad_ArgumentsMissing if it was waiting for some inputArguments you did not provide.

Body:
The Qt Documentation provides the method

bool QOpcUaNode::callMethod(const QString &methodNodeId, const QVector<QOpcUa::TypedVariant> &args = QVector<QOpcUa::TypedVariant>())

for calling methods on the Opc Ua Server. Regarding this Method I have 2 Questions:

What exactly is methodNodeId ? I imagine it is the Id of the Node I want to call, but if this is the case, why would the function not be static instead ?

How to call methods with 0 input arguments? trying to call myNode->callMethod(methodNodeId) without specifiying further arguments still returns BadTooManyArguments, but there is really not other way I could see it being used.


问:
How to retrieve item from another localStorage Domain?
I'm working on a JAVA web application which plays the role of a search engine. Its backend is developed with AngularJS. And I have a small PHP code which tries to send a data from an input text to the JAVA web app via an iframe. the data is stocked in a localStorage.

Here is below the PHP Code :

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Search</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 <form action="http://localhost:8050/searchEngine/#/search">
  <input type="text" name="word" id="wordToSearch">
    <input type="submit" value="Search"  onclick="redirect()">
 </form>

```
</div>
</div>
</p>

<p>Precisely, I'm trying to retrieve the "wordToSearch" item value stored within the localStorage </p>

<p>Here is below the code where i add my iFrame to my application :</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-html lang-html prettyprint-override"><code><iframe src='http://localhost:8040/test/index.php'></iframe></code>```

This is the result i get in the developer tools :

Developer Tools Result

Can anyone help me please ?

答: You can do it using cookie, set value to http://localhost:8050 and get value from http://localhost:8040. Visit https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie</p>

Body:
I'm working on a JAVA web application which plays the role of a search engine. Its backend is developed with AngularJS. And I have a small PHP code which tries to send a data from an input text to the JAVA web app via an iframe. the data is stocked in a localStorage.

Here is below the PHP Code :

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Search</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 <form action="http://localhost:8050/searchEngine/#/search">
  <input type="text" name="word" id="wordToSearch">
    <input type="submit" value="Search"  onclick="redirect()">
 </form>

Precisely, I'm trying to retrieve the "wordToSearch" item value stored within the localStorage

Here is below the code where i add my iFrame to my application :

This is the result i get in the developer tools :

Developer Tools Result

Can anyone help me please ?


问:
Conditional wrapper rendering in vue
I'm making a link/button component which either can have a button or an anchor wrapper, a  text and an optional icon. My template code below is currently rendering either an anchor or a button (with the exact same content) based on an if statement on the wrapper element, resulting in duplicate code.

```<code><template>
    <a v-if="link" v-bind:href="url" class="btn" :class="modifier" :id="id" role="button" :disabled="disabled">
        {{buttonText}}
        <svg class="icon" v-if="icon" :class="iconModifier">
            <use v-bind="{ 'xlink:href':'#sprite-' + icon }"></use>
        </svg>
    </a>
    <button v-else type="button" class="btn" :class="modifier" :id="id" :disabled="disabled">
        {{buttonText}}
        <svg class="icon" v-if="icon" :class="iconModifier">
            <use v-bind="{ 'xlink:href':'#sprite-' + icon }"></use>
        </svg>
    </button>
</template>
</code>```

Is there a more clean way for wrapping my buttonText and icon inside either an anchor or button?

答:
I've solved my issue by intensive Google-ing! Found this issue regarding Vue on Github which pointed me in the right direction.

Small piece of backstory

I'm using Vue in combination with Storybook to build a component library in which a button can either be a button or an anchor. All buttons look alike (apart from color) and can be used for submitting or linking. To keep my folder structure ordered, I would like a solution that generates a multiple buttons types (with or without link) from one single file.

Solution

Using computed properties I'm able to "calculate" the necessary tag, based on the url property of my component. When a url is passed, I know that my button has to link to another page. If there is no url property it should submit something or preform a custom click handler (not in the sample code below).

I've created the returnComponentTag computed property to avoid placing any complex or bulky logic (like my original solution) in my template. This returns either an a or a button tag based on the existence of the url property.

Next, as suggested by ajobi, using the :is attribute I'm able to define the component tag based on the result of my computed property. Below a stripped sample of my final (and working) solution:

```<code><template>
    <component :is="returnComponentTag" v-bind:href="url ? url : ''" class="btn" :class="modifier" :id="id">
        {{buttonText}}
    </component>
</template>

<script>
export default {
    name: "Button",
    props: {
        id: {
            type: Number
        },
        buttonText: {
            type: String,
            required: true,
            default: "Button"
        },
        modifier: {
            type: String,
            default: "btn-cta-01"
        },
        url: {
            type: String,
            default: ""
        }
    },
    computed: {
        returnComponentTag() {
            return this.url ? "a" : "button"
        }
    }
};
</script>
</code>```

Title: Conditional wrapper rendering in vue

Body:
I'm making a link/button component which either can have a button or an anchor wrapper, a  text and an optional icon. My template code below is currently rendering either an anchor or a button (with the exact same content) based on an if statement on the wrapper element, resulting in duplicate code.

<template>

        {{buttonText}}
        <svg class="icon" v-if="icon" :class="iconModifier">
            <use v-bind="{ 'xlink:href':'#sprite-' + icon }"></use>
        </svg>

    <button v-else type="button" class="btn" :class="modifier" :id="id" :disabled="disabled">
        {{buttonText}}
        <svg class="icon" v-if="icon" :class="iconModifier">
            <use v-bind="{ 'xlink:href':'#sprite-' + icon }"></use>
        </svg>
    </button>
</template>

Is there a more clean way for wrapping my buttonText and icon inside either an anchor or button?

Body:
I've solved my issue by intensive Google-ing! Found this issue regarding Vue on Github which pointed me in the right direction.

Small piece of backstory

I'm using Vue in combination with Storybook to build a component library in which a button can either be a button or an anchor. All buttons look alike (apart from color) and can be used for submitting or linking. To keep my folder structure ordered, I would like a solution that generates a multiple buttons types (with or without link) from one single file.

Solution

Using computed properties I'm able to "calculate" the necessary tag, based on the url property of my component. When a url is passed, I know that my button has to link to another page. If there is no url property it should submit something or preform a custom click handler (not in the sample code below).

I've created the returnComponentTag computed property to avoid placing any complex or bulky logic (like my original solution) in my template. This returns either an a or a button tag based on the existence of the url property.

Next, as suggested by ajobi, using the :is attribute I'm able to define the component tag based on the result of my computed property. Below a stripped sample of my final (and working) solution:

<template>
    <component :is="returnComponentTag" v-bind:href="url ? url : ''" class="btn" :class="modifier" :id="id">
        {{buttonText}}
    </component>
</template>

<script>
export default {
    name: "Button",
    props: {
        id: {
            type: Number
        },
        buttonText: {
            type: String,
            required: true,
            default: "Button"
        },
        modifier: {
            type: String,
            default: "btn-cta-01"
        },
        url: {
            type: String,
            default: ""
        }
    },
    computed: {
        returnComponentTag() {
            return this.url ? "a" : "button"
        }
    }
};
</script>


问:
How to parameterize pyodbc identifiers in queries safely?
I have written a small tool which migrates data from SQL Server to Postgres.

To make things work, I did it quick and dirty using string concats since I had a lot of other issues to solve and I did not want to bother with the SQL at the time. But now that everything is sorted out, I want to do things porperly in the SQL department.

The unsafe quick and dirty version :

```<code>import pyodbc
# this is the bad example DON'T do this
    def getDataFromTable(self,table):
        """
        Gets all data from the specified Table.
        table -- Table name as string
        """
        cursor = self.cursor
        SQL = f"""SELECT * FROM {table}""" ## DON'T do this
        cursor.execute(SQL)
        rows = cursor.fetchall()
        records = []
        for row in rows:
            records.append(list(row))
        return records
</code>```

This works perfectly fine, but is a SQL injection waiting to happen.

I want to build something like this (I have omitted the unchanged parts):

```<code>...
cursor = self.cursor
SQL = f"""SELECT * FROM ?""" # Use parameters insted of string concats
cursor.execute(SQL, table) # pass parameters to the execute method.
rows = cursor.fetchall()
...
</code>```

This looks nice an safe, but also does not work. Following error pops up :

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Die @P1-Tabellenvariable muss deklariert werden. (1087) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Anweisung(en) konnte(n) nicht vorbereitet werden. (8180)')

It's in German but roughly translates to: table variables must be declared, statement could not be prepared.

How can I pass a variable into the execute method to take the identifiers place safely?

答:
You can not have a variable for table name in SQL Server. You can generate a string in python and then execute it.

```<code>table_name = 'table1'
query = "Select * from %s" % table_name
</code>```

Or you can use Dynamic SQL.

Body:
I have written a small tool which migrates data from SQL Server to Postgres.

To make things work, I did it quick and dirty using string concats since I had a lot of other issues to solve and I did not want to bother with the SQL at the time. But now that everything is sorted out, I want to do things porperly in the SQL department.

The unsafe quick and dirty version :

import pyodbc
# this is the bad example DON'T do this
    def getDataFromTable(self,table):
        """
        Gets all data from the specified Table.
        table -- Table name as string
        """
        cursor = self.cursor
        SQL = f"""SELECT * FROM {table}""" ## DON'T do this
        cursor.execute(SQL)
        rows = cursor.fetchall()
        records = []
        for row in rows:
            records.append(list(row))
        return records

This works perfectly fine, but is a SQL injection waiting to happen.

I want to build something like this (I have omitted the unchanged parts):

...
cursor = self.cursor
SQL = f"""SELECT * FROM ?""" # Use parameters insted of string concats
cursor.execute(SQL, table) # pass parameters to the execute method.
rows = cursor.fetchall()
...

This looks nice an safe, but also does not work. Following error pops up :

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Die @P1-Tabellenvariable muss deklariert werden. (1087) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Anweisung(en) konnte(n) nicht vorbereitet werden. (8180)')

It's in German but roughly translates to: table variables must be declared, statement could not be prepared.

How can I pass a variable into the execute method to take the identifiers place safely?

Body:
You can not have a variable for table name in SQL Server. You can generate a string in python and then execute it.

table_name = 'table1'
query = "Select * from %s" % table_name

Or you can use Dynamic SQL.


问:
Java Rudimentary Hex Editor - Programming Assignment
I am coding a rudimentary hex editor for an assignment in school. I have it just about 90% done, however, I can't figure out how to assign a new byte value to an already existing byte value. Basically, I ask the user if he/she would like to modify a byte at the position they specify (earlier in the code). If they choose yes, then they should be prompted to enter a new HEX value to overwrite the one at the position. So far, I have this:

```<code>System.out.print("Would you like to edit the byte at this position?(y/n): ");
            String choice;
            choice = in.nextLine();
            if ("y".equals(choice)){
                System.out.print("Enter the new hex value: ");
                String hv = in.nextLine();
                int i = Integer.decode("0x" + hv);
</code>```

Here, I can't really figure out how to then put the value they enter into the corresponding position.

Here's the previous code that sets the position the user specifies:

```<code>        System.out.print("Enter byte positon to navigate to: ");
        long loc = in.nextLong(); in.nextLine();
        if (loc >= 0 && loc < fileList.size()) {
            ListIterator<Byte> lit = fileList.listIterator((loc - 5 >= 0)?(int)(loc-5):0);
            int start = lit.nextIndex();
            System.out.println("The surrounding 5 bytes (left and right) are: ");
            while (start <= loc+5 && start < fileList.size()){
                if (start == loc){
                   System.out.print(" ( ");
                }
            byte b = lit.next();
            System.out.print(((b >= 0 && b <= 15)?"0":" ") + Integer.toHexString((int)b & 0x00FF) + " ");
            if (start == loc)
                System.out.print(" ) ");
            System.out.print(" ");
            start++;

            }
</code>```

Any help at all is greatly appreciated. Thank you.

答:
If I understand correctly your fileList contains every byte of the open file. That is how you retrieve the selected bytes at least.

So maybe you can use the set() method to change a byte of the fileList (https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#set(E))

I think you need to go to the correct offset, call next() to retrieve it and then call set() to define it if I understand the docs correctly.

After you perfromed this operation the byte is probabbly only altered in memory and you would still need to write them to disk, if you want to preserve them.

Body:
I am coding a rudimentary hex editor for an assignment in school. I have it just about 90% done, however, I can't figure out how to assign a new byte value to an already existing byte value. Basically, I ask the user if he/she would like to modify a byte at the position they specify (earlier in the code). If they choose yes, then they should be prompted to enter a new HEX value to overwrite the one at the position. So far, I have this:

System.out.print("Would you like to edit the byte at this position?(y/n): ");
            String choice;
            choice = in.nextLine();
            if ("y".equals(choice)){
                System.out.print("Enter the new hex value: ");
                String hv = in.nextLine();
                int i = Integer.decode("0x" + hv);

Here, I can't really figure out how to then put the value they enter into the corresponding position.

Here's the previous code that sets the position the user specifies:

        System.out.print("Enter byte positon to navigate to: ");
        long loc = in.nextLong(); in.nextLine();
        if (loc >= 0 && loc < fileList.size()) {
            ListIterator<Byte> lit = fileList.listIterator((loc - 5 >= 0)?(int)(loc-5):0);
            int start = lit.nextIndex();
            System.out.println("The surrounding 5 bytes (left and right) are: ");
            while (start <= loc+5 && start < fileList.size()){
                if (start == loc){
                   System.out.print(" ( ");
                }
            byte b = lit.next();
            System.out.print(((b >= 0 && b <= 15)?"0":" ") + Integer.toHexString((int)b & 0x00FF) + " ");
            if (start == loc)
                System.out.print(" ) ");
            System.out.print(" ");
            start++;

            }

Any help at all is greatly appreciated. Thank you.


问:
row number increases by specific conditions in more fast way R
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

```<code>
df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}
</code>```

答:
You can try : </p>

```<code>library(dplyr)
df %>% mutate(rank  = cumsum(diff > 14 | ID != lag(ID, default = TRUE)))
</code>```

<p>Same logic using base R : </p>

```<code>df$rank <- with(df, cumsum(diff > 14 | c(TRUE, tail(ID, -1) != head(ID, -1))))
</code>```

Body:
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}

Body:
You can try :

library(dplyr)
df %>% mutate(rank  = cumsum(diff > 14 | ID != lag(ID, default = TRUE)))

Same logic using base R :

df$rank <- with(df, cumsum(diff > 14 | c(TRUE, tail(ID, -1) != head(ID, -1))))


问:
Google Cloud Data Fusion + CI/CD for Data Pipelines
I am just getting started with both, GCP & Google Cloud Data Fusion. Just viewed the intro video. I see that pipelines can be exported. I was wondering how we might promote a pipeline from say, Dev to Prod env? My guess is that after some testing, the exported file is copied to the Prod branch on Git, from where we need to invoke the APIs to deploy it? Also, what about connection details, how do we avoid hard-coding the source/destination configurations & credentials? </p>

答: Yes. You would have to export and re-import the pipeline.</p>


问:
Using pushViewController: animated:
I'm trying to use the pushViewController: animated: with a UIViewController. I have it housed in a UINavigationController with initWithRoot and it still doesn't work.

Here is my code? Am I doing something wrong?

```<code>CloudappSettingsViewController *cloud = [[CloudappSettingsViewController alloc] initWithNibName:nil bundle:nil];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cloud];
        [self pushViewController:nav animated:YES];
        [cloud release];
</code>```

It always crashes when it gets up to the [self pushViewController:nav animated:YES];

Any ideas?
Thanks

答:
is "self" a UINavigationController?

It seems you are trying to push the navigation controller, but that is backwards. You should present the navigation controller and push additional views to it.

So the UIView you are in should already be in the nav controller then you would push cloud into that.

Title: Using pushViewController: animated:

Body:
I'm trying to use the pushViewController: animated: with a UIViewController. I have it housed in a UINavigationController with initWithRoot and it still doesn't work.

Here is my code? Am I doing something wrong?

CloudappSettingsViewController *cloud = [[CloudappSettingsViewController alloc] initWithNibName:nil bundle:nil];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cloud];
        [self pushViewController:nav animated:YES];
        [cloud release];

It always crashes when it gets up to the [self pushViewController:nav animated:YES];

Any ideas?
Thanks


问:
MongoDB， How to associate array fields for statistics
Example JSON：

```<code>{
  "groups": [
    {
      "_id": 1,
      "name": "g1"
    },
    {
      "_id": 2,
      "name": "g2"
    }
  ],
  "items": [
    {
      "_id": 1,
      "name": "item1",
      "gid": 1
    },
    {
      "_id": 2,
      "name": "item2",
      "gid": 2
    }
  ]
}
</code>```

How to associate two arrays and count ？I tried to use aggregate, I didn't get the results I wanted.

Required Result:
Or can directly find all the items associated with it, perfect....

```<code>{"groups": [
{
  "_id": 1,
  "name": "g1",
  "count": 1,
  "items": [
    {
      "_id": 1,
      "name": "item1"
    }
  ]
},
{
  "_id": 2,
  "name": "g2",
  "count": 1,
  "items": [
    {
      "_id": 2,
      "name": "item2"
    }
  ]
}
]}
</code>```

答:
```<code>db.getCollection('collection').aggregate([
{$unwind:{
    path:"$groups",
    preserveNullAndEmptyArrays:true
}},
{$unwind:{
    path:"$items",
    preserveNullAndEmptyArrays:true
}},
{$redact: {$cond: [{
                    $eq: [
                           "$groups._id",
                           "$items.gid"
                         ]
                  },
                  "$$KEEP",
                  "$$PRUNE"
                ]
        }
},
{$project:{
    _id:1,
    groups_id:"$groups._id",
    group_name:"$groups.name",
    item_data:{
        _id:"$items._id",
        name:"$items.name",
        }
    }},
    {
        $group:{
            _id:"$groups_id",
            name:{$first:"$group_name"},
            count:{$sum:1},
            items:{$push:"$item_data"}
            }
    }
])
</code>```

Body:
Example JSON：

{
  "groups": [
    {
      "_id": 1,
      "name": "g1"
    },
    {
      "_id": 2,
      "name": "g2"
    }
  ],
  "items": [
    {
      "_id": 1,
      "name": "item1",
      "gid": 1
    },
    {
      "_id": 2,
      "name": "item2",
      "gid": 2
    }
  ]
}

How to associate two arrays and count ？I tried to use aggregate, I didn't get the results I wanted.

Required Result:
Or can directly find all the items associated with it, perfect....

{"groups": [
{
  "_id": 1,
  "name": "g1",
  "count": 1,
  "items": [
    {
      "_id": 1,
      "name": "item1"
    }
  ]
},
{
  "_id": 2,
  "name": "g2",
  "count": 1,
  "items": [
    {
      "_id": 2,
      "name": "item2"
    }
  ]
}
]}


问:
How to export all filtered records kartik-v/yii2-export in GridView?
I am using the extension kartik-v / yii2-export, (Apparently it is the only one there is to export). I have the following inconvenience:

I only exported the first page of the dataprovider.

I would like to filter the data in the grid, and export the filtered data, even if they have several pages. Is this possible?

答: I Solved this; by setting the property  'batchSize'  from the Export Widget, the same value the property 'pageSize' from DataProvider. It Works !</p>


问:
GDB cannot step over a function if the following lines don't include a decision or branch
I am having problems with debugging (stepping over) in C++ with GDB.
I have an in house developed RTOS which runs on a PowerPC e500mc target.

Software versions: GCC 4.9.2, gdb-server 5 ~(I am not sure about the exact version), GDB 7.9.1 (I also tried 8.3.1).

The source file is compiled with the -g and -O0 parameters.

The problem seems to be occurring in C++ after stepping over a function if the following lines don't include any jump, branch instruction for a certain amount, GDB lost track where to stop at function return and continue running.

I've tried the same code on an x86-64 target version. It runs as expected without any issue. The first, I checked was gdb-server's target porting part, and then logged the messaging between the host and the target. As you can see below, the problem seems to be at the GDB side since GDB itself decides where to put a breakpoint.

There is example code exploiting the error, and I also added the log file. The lines starting with "gdb:" are the messages from GDB to the target. I don't include the gdb-server's responses to avoid confusion.

Other lines are printed by the target. <..> are the comments added by me later. It tells the meaning of the code, data or address, and also what I did at that time. I also include the ELF file's related part to make it more understandable.

Here it what happens. At first I load my program to the target, with auto start disabled. The program is in memory and waiting for my command to run. Then I attach to the process for debugging. GDB takes over and starts communication. After some handshaking and queries, it catches the process. It wasn't running, so it catch at the very beginning, initialization code before the main function at 0x210106E8. So GDB knows that I want to stop at my code (main), puts a breakpoint at main's first instruction after the function's stack operations at 0x21010250.

Then programs runs on the target and catch a trap exception at a breakpoint. When the execution stops GDB removes the breakpoint (trap instruction) and puts back the original instruction.

Later I do a step over which is line int i=0. GDB sets on the trace mode and starts the execution.

The program catches the trace exception after running the first instruction. Since I am not in instruction stepping mode, GDB starts execution again until the c line ends, GDB catches the second trace exception and reaches the end of the c line sets of the trace mode.

Now we are at the function call line and stepping over again. GDB sets on the trace mode and start executing the program. The program calls the function and catches the trace exception. GDB sees it's not in the function (main) we are interested in since we are stepping over, and sets a breakpoint for function return point. The program starts executing and prints the message. The function returns and hits the breakpoint at 0x2101025C. So far so good.

It should have stopped here, since my initial command, which is stepping over function call, is completed, but continues.

Now as you can see on the log output, GDB starts queries about the code block, which it has done before, but not with a much greater number, looking for 52 instructions ahead (which are all the i++s). GDB removes the breakpoint and sets the trace mode on and executes the first instruction of the i++ command.

After the first instruction executed and the exception caught, again the 52 instruction queries. After all this, GDB should set on the trace mode and start executing. Instead of this, it puts a breakpoint before the current PC, at the address of the instruction it just executed. When trace mode is off and when the execution starts, the program executes to completion since the breakpoint will not be hit.

If I reduce the number of i++'s to the point, where in 52 instruction query GDB will see some jump or branch, everything works as expected.

And if the same code compiled as C, not C++, again everything works as expected.

As I mentioned earlier, same code running on a x86 target, everything works as expected.

Code:

```<code>#include <iostream>

using namespace std;

void printHello(void)
{
    cout << "Hello, World!" << endl;
}

int main()
{
    int i = 0;
    printHello();
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    return 0;
}
</code>```

Terminal output:

<attach to process>
gdb:qSupported:multiprocess+;qRelocInsn+
gdb:!
gdb:Hgp0.0
gdb:QNonStop:0
gdb:qTStatus
gdb:?
gdb:qXfer:osdata:read:processes:0,35b
gdb:qXfer:threads:read::0,35b
gdb:vAttach;10000
stopping 65537 @210106e8 <_posix_lib_process_start>
gdb:qC
gdb:Hgp10000.10001
gdb:g
gdb:qSymbol::
gdb:m21010250,4
gdb:m21010250,4
gdb:m21010250,4
gdb:m210151c8,4 <_ZSt9terminatev>
gdb:m2102e288,4 <_Unwind_DebugHook>
gdb:qXfer:threads:read::0,763
gdb:qXfer:osdata:read:processes:0,763
gdb:qXfer:threads:read::0,763
gdb:Z0,21010250,4
gdb:m21010250,4 <backup>
gdb:X21010250,0:
gdb:X21010250,4:}] <put breakpoint @ main>
gdb:vCont?
gdb:vCont;c:p10000.-1 <cont all, breakpoint ready>
starting 65537 @210106e8
trap callback
stopping 65537 @21010250 <stop @ breakpoint>
gdb:m21010250,4
gdb:m21010254,4
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21441fa0,4
gdb:g
gdb:qXfer:threads:read::0,763
gdb:X21010250,4:9 <remove breakpoint>
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
<stop @ int=0 line>

<step>
gdb:m2102e288,4 <backup>
gdb:X2102e288,4:}] <??put breakpoint>
gdb:m21010250,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010250
trace callback <instruction complete exception>
stopping 65537 @21010254
single step reset
gdb:m21010254,4
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:g
gdb:m21010254,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010254
trace callback <instruction complete exception>
stopping 65537 @21010258
single step reset <step done, new c line>
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:g
gdb:qXfer:threads:read::0,763
gdb:X2102e288,4:N <??remove breakpoint>
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
<stop @ printHello() line>

<step>
gdb:m2102e288,4
gdb:X2102e288,4:}] <??put breakpoint>
gdb:m21010258,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010258
trace callback
stopping 65537 @210101e8 <printHello>
single step reset
gdb:m210101e8,4
gdb:m210101ec,4
gdb:m210101f0,4
gdb:m210101f4,4
gdb:m210101f8,4
gdb:m210101fc,4
gdb:m21010200,4
gdb:m21010204,4
gdb:m21010208,4
gdb:m2101020c,4
gdb:m210101e8,4
gdb:g
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:m2101025c,4
gdb:m2101025c,4
gdb:X2101025c,4:}] <put breakpoint>
gdb:vCont;c:p10000.-1 <cont all, breakpoint ready>
starting 65537 @210101e8
Hello World
trap callback <stop @ breakpoint>
stopping 65537 @2101025c
gdb:m2101025c,4
gdb:m21010260,4
gdb:m21010264,4
gdb:m21010268,4
gdb:m2101026c,4
gdb:m21010270,4
gdb:m21010274,4
gdb:m21010278,4
gdb:m2101027c,4
gdb:m21010280,4
gdb:m21010284,4
gdb:m21010288,4
gdb:m2101028c,4
gdb:m21010290,4
gdb:m21010294,4
gdb:m21010298,4
gdb:m2101029c,4
gdb:m210102a0,4
gdb:m210102a4,4
gdb:m210102a8,4
gdb:m210102ac,4
gdb:m210102b0,4
gdb:m210102b4,4
gdb:m210102b8,4
gdb:m210102bc,4
gdb:m210102c0,4
gdb:m210102c4,4
gdb:m210102c8,4
gdb:m210102cc,4
gdb:m210102d0,4
gdb:m210102d4,4
gdb:m210102d8,4
gdb:m210102dc,4
gdb:m210102e0,4
gdb:m210102e4,4
gdb:m210102e8,4
gdb:m210102ec,4
gdb:m210102f0,4
gdb:m210102f4,4
gdb:m210102f8,4
gdb:m210102fc,4
gdb:m21010300,4
gdb:m21010304,4
gdb:m21010308,4
gdb:m2101030c,4
gdb:m21010310,4
gdb:m21010314,4
gdb:m21010318,4
gdb:m2101031c,4
gdb:m21010320,4
gdb:m21010324,4
gdb:m21010328,4
gdb:m21010258,4
gdb:g
gdb:X2101025c,4:? <remove breakpoint>
gdb:m2101025c,4
gdb:vCont;s:p10000.10001 <stop thread, trace ready><??c:-1 neden yok>
single step set
starting 65537 @2101025c
trace callback <instruction complete exception>
stopping 65537 @21010260
single step reset
gdb:m21010260,4
gdb:m21010264,4
gdb:m21010268,4
gdb:m2101026c,4
gdb:m21010270,4
gdb:m21010274,4
gdb:m21010278,4
gdb:m2101027c,4
gdb:m21010280,4
gdb:m21010284,4
gdb:m21010288,4
gdb:m2101028c,4
gdb:m21010290,4
gdb:m21010294,4
gdb:m21010298,4
gdb:m2101029c,4
gdb:m210102a0,4
gdb:m210102a4,4
gdb:m210102a8,4
gdb:m210102ac,4
gdb:m210102b0,4
gdb:m210102b4,4
gdb:m210102b8,4
gdb:m210102bc,4
gdb:m210102c0,4
gdb:m210102c4,4
gdb:m210102c8,4
gdb:m210102cc,4
gdb:m210102d0,4
gdb:m210102d4,4
gdb:m210102d8,4
gdb:m210102dc,4
gdb:m210102e0,4
gdb:m210102e4,4
gdb:m210102e8,4
gdb:m210102ec,4
gdb:m210102f0,4
gdb:m210102f4,4
gdb:m210102f8,4
gdb:m210102fc,4
gdb:m21010300,4
gdb:m21010304,4
gdb:m21010308,4
gdb:m2101030c,4
gdb:m21010310,4
gdb:m21010314,4
gdb:m21010318,4
gdb:m2101031c,4
gdb:m21010320,4
gdb:m21010324,4
gdb:m21010328,4
gdb:m2101032c,4
gdb:m2101025c,4
gdb:m21010258,4
gdb:g
gdb:m2101025c,4
gdb:X2101025c,4:}] <HATA put breakpoint>
gdb:vCont;c:p10000.-1 <cont all><HATA -1 gönderdiği için, trace yapmıyor>
starting 65537 @21010260
```
<h3>ELF file</h3>
<pre class="lang-none prettyprint-override"><code>void printHello(void)
{
210101e8:    94 21 ff f0     stwu    r1,-16(r1)
210101ec:    7c 08 02 a6     mflr    r0
210101f0:    90 01 00 14     stw     r0,20(r1)
210101f4:    93 e1 00 0c     stw     r31,12(r1)
210101f8:    7c 3f 0b 78     mr      r31,r1
     cout << "Hello World" << endl;
210101fc:    3d 20 21 04     lis     r9,8452
21010200:    38 69 01 78     addi    r3,r9,376
21010204:    3d 20 21 04     lis     r9,8452
21010208:    38 89 82 48     addi    r4,r9,-32184
2101020c:    48 02 1f a9     bl      210321b4
21010210:    7c 69 1b 78     mr      r9,r3
21010214:    7d 23 4b 78     mr      r3,r9
21010218:    3d 20 21 03     lis     r9,8451
2101021c:    38 89 26 ec     addi    r4,r9,9964
21010220:    48 02 25 45     bl      21032764
}
21010224:    39 7f 00 10     addi    r11,r31,16
21010228:    80 0b 00 04     lwz     r0,4(r11)
2101022c:    7c 08 03 a6     mtlr    r0
21010230:    83 eb ff fc     lwz     r31,-4(r11)
21010234:    7d 61 5b 78     mr      r1,r11
21010238:    4e 80 00 20     blr

2101023c <main>:

int main()
{
2101023c:    94 21 ff e0     stwu    r1,-32(r1)
21010240:    7c 08 02 a6     mflr    r0
21010244:    90 01 00 24     stw     r0,36(r1)
21010248:    93 e1 00 1c     stw     r31,28(r1)
2101024c:    7c 3f 0b 78     mr      r31,r1
    int i = 0;
21010250:    39 20 00 00     li      r9,0
21010254:    91 3f 00 08     stw     r9,8(r31)
    printHello();
21010258:    4b ff ff 91     bl      210101e8 <_Z10printHellov>
        i++;
2101025c:    81 3f 00 08     lwz     r9,8(r31)
21010260:    39 29 00 01     addi    r9,r9,1
21010264:    91 3f 00 08     stw     r9,8(r31)
        i++;
21010268:    81 3f 00 08     lwz     r9,8(r31)
2101026c:    39 29 00 01     addi    r9,r9,1
21010270:    91 3f 00 08     stw     r9,8(r31)
        i++;
21010274:    81 3f 00 08     lwz     r9,8(r31)
21010278:    39 29 00 01     addi    r9,r9,1
2101027c:    91 3f 00 08     stw     r9,8(r31)
</code>```

答:
The problem is solved. At least step over works fine now.

The error was caused by the rs6000_in_function_epilogue_frame_p() function.

As you can see, the function scans forward until the next BLR for 52 (seems familiar) instruction. And it scans backwards until adjustment to stack pointer. These causes it to put a breakpoint to be put on a previous code from the PC and execution cannot be stopped.

The function modified just to return 0.

I don’t have a deep understanding on the host side, and maybe you'll find a better solution.

I suspect there was a design change in previous versions in the step functionality, the Intel architecture code was updated, but PowerPC was forgotten.

Body:
I am having problems with debugging (stepping over) in C++ with GDB.
I have an in house developed RTOS which runs on a PowerPC e500mc target.

Software versions: GCC 4.9.2, gdb-server 5 ~(I am not sure about the exact version), GDB 7.9.1 (I also tried 8.3.1).

The source file is compiled with the -g and -O0 parameters.

The problem seems to be occurring in C++ after stepping over a function if the following lines don't include any jump, branch instruction for a certain amount, GDB lost track where to stop at function return and continue running.

I've tried the same code on an x86-64 target version. It runs as expected without any issue. The first, I checked was gdb-server's target porting part, and then logged the messaging between the host and the target. As you can see below, the problem seems to be at the GDB side since GDB itself decides where to put a breakpoint.

There is example code exploiting the error, and I also added the log file. The lines starting with "gdb:" are the messages from GDB to the target. I don't include the gdb-server's responses to avoid confusion.

Other lines are printed by the target. <..> are the comments added by me later. It tells the meaning of the code, data or address, and also what I did at that time. I also include the ELF file's related part to make it more understandable.

Here it what happens. At first I load my program to the target, with auto start disabled. The program is in memory and waiting for my command to run. Then I attach to the process for debugging. GDB takes over and starts communication. After some handshaking and queries, it catches the process. It wasn't running, so it catch at the very beginning, initialization code before the main function at 0x210106E8. So GDB knows that I want to stop at my code (main), puts a breakpoint at main's first instruction after the function's stack operations at 0x21010250.

Then programs runs on the target and catch a trap exception at a breakpoint. When the execution stops GDB removes the breakpoint (trap instruction) and puts back the original instruction.

Later I do a step over which is line int i=0. GDB sets on the trace mode and starts the execution.

The program catches the trace exception after running the first instruction. Since I am not in instruction stepping mode, GDB starts execution again until the c line ends, GDB catches the second trace exception and reaches the end of the c line sets of the trace mode.

Now we are at the function call line and stepping over again. GDB sets on the trace mode and start executing the program. The program calls the function and catches the trace exception. GDB sees it's not in the function (main) we are interested in since we are stepping over, and sets a breakpoint for function return point. The program starts executing and prints the message. The function returns and hits the breakpoint at 0x2101025C. So far so good.

It should have stopped here, since my initial command, which is stepping over function call, is completed, but continues.

Now as you can see on the log output, GDB starts queries about the code block, which it has done before, but not with a much greater number, looking for 52 instructions ahead (which are all the i++s). GDB removes the breakpoint and sets the trace mode on and executes the first instruction of the i++ command.

After the first instruction executed and the exception caught, again the 52 instruction queries. After all this, GDB should set on the trace mode and start executing. Instead of this, it puts a breakpoint before the current PC, at the address of the instruction it just executed. When trace mode is off and when the execution starts, the program executes to completion since the breakpoint will not be hit.

If I reduce the number of i++'s to the point, where in 52 instruction query GDB will see some jump or branch, everything works as expected.

And if the same code compiled as C, not C++, again everything works as expected.

As I mentioned earlier, same code running on a x86 target, everything works as expected.

Code:

#include <iostream>

using namespace std;

void printHello(void)
{
    cout << "Hello, World!" << endl;
}

int main()
{
    int i = 0;
    printHello();
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    i++;
    return 0;
}

Terminal output:

<attach to process>
gdb:qSupported:multiprocess+;qRelocInsn+
gdb:!
gdb:Hgp0.0
gdb:QNonStop:0
gdb:qTStatus
gdb:?
gdb:qXfer:osdata:read:processes:0,35b
gdb:qXfer:threads:read::0,35b
gdb:vAttach;10000
stopping 65537 @210106e8 <_posix_lib_process_start>
gdb:qC
gdb:Hgp10000.10001
gdb:g
gdb:qSymbol::
gdb:m21010250,4
gdb:m21010250,4
gdb:m21010250,4
gdb:m210151c8,4 <_ZSt9terminatev>
gdb:m2102e288,4 <_Unwind_DebugHook>
gdb:qXfer:threads:read::0,763
gdb:qXfer:osdata:read:processes:0,763
gdb:qXfer:threads:read::0,763
gdb:Z0,21010250,4
gdb:m21010250,4 <backup>
gdb:X21010250,0:
gdb:X21010250,4:}] <put breakpoint @ main>
gdb:vCont?
gdb:vCont;c:p10000.-1 <cont all, breakpoint ready>
starting 65537 @210106e8
trap callback
stopping 65537 @21010250 <stop @ breakpoint>
gdb:m21010250,4
gdb:m21010254,4
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21441fa0,4
gdb:g
gdb:qXfer:threads:read::0,763
gdb:X21010250,4:9 <remove breakpoint>
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
<stop @ int=0 line>

<step>
gdb:m2102e288,4 <backup>
gdb:X2102e288,4:}] <??put breakpoint>
gdb:m21010250,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010250
trace callback <instruction complete exception>
stopping 65537 @21010254
single step reset
gdb:m21010254,4
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:g
gdb:m21010254,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010254
trace callback <instruction complete exception>
stopping 65537 @21010258
single step reset <step done, new c line>
gdb:m21010258,4
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:g
gdb:qXfer:threads:read::0,763
gdb:X2102e288,4:N <??remove breakpoint>
gdb:qXfer:threads:read::0,763
gdb:qXfer:threads:read::0,763
<stop @ printHello() line>

<step>
gdb:m2102e288,4
gdb:X2102e288,4:}] <??put breakpoint>
gdb:m21010258,4
gdb:vCont;s:p10000.10001;c:p10000.-1 <stop thread, set trace>
single step set
starting 65537 @21010258
trace callback
stopping 65537 @210101e8 <printHello>
single step reset
gdb:m210101e8,4
gdb:m210101ec,4
gdb:m210101f0,4
gdb:m210101f4,4
gdb:m210101f8,4
gdb:m210101fc,4
gdb:m21010200,4
gdb:m21010204,4
gdb:m21010208,4
gdb:m2101020c,4
gdb:m210101e8,4
gdb:g
gdb:m2101023c,4
gdb:m2101023c,4
gdb:m21010240,4
gdb:m21010244,4
gdb:m21010248,4
gdb:m2101024c,4
gdb:m21010250,4
gdb:m21441fa0,4
gdb:m2101025c,4
gdb:m2101025c,4
gdb:X2101025c,4:}] <put breakpoint>
gdb:vCont;c:p10000.-1 <cont all, breakpoint ready>
starting 65537 @210101e8
Hello World
trap callback <stop @ breakpoint>
stopping 65537 @2101025c
gdb:m2101025c,4
gdb:m21010260,4
gdb:m21010264,4
gdb:m21010268,4
gdb:m2101026c,4
gdb:m21010270,4
gdb:m21010274,4
gdb:m21010278,4
gdb:m2101027c,4
gdb:m21010280,4
gdb:m21010284,4
gdb:m21010288,4
gdb:m2101028c,4
gdb:m21010290,4
gdb:m21010294,4
gdb:m21010298,4
gdb:m2101029c,4
gdb:m210102a0,4
gdb:m210102a4,4
gdb:m210102a8,4
gdb:m210102ac,4
gdb:m210102b0,4
gdb:m210102b4,4
gdb:m210102b8,4
gdb:m210102bc,4
gdb:m210102c0,4
gdb:m210102c4,4
gdb:m210102c8,4
gdb:m210102cc,4
gdb:m210102d0,4
gdb:m210102d4,4
gdb:m210102d8,4
gdb:m210102dc,4
gdb:m210102e0,4
gdb:m210102e4,4
gdb:m210102e8,4
gdb:m210102ec,4
gdb:m210102f0,4
gdb:m210102f4,4
gdb:m210102f8,4
gdb:m210102fc,4
gdb:m21010300,4
gdb:m21010304,4
gdb:m21010308,4
gdb:m2101030c,4
gdb:m21010310,4
gdb:m21010314,4
gdb:m21010318,4
gdb:m2101031c,4
gdb:m21010320,4
gdb:m21010324,4
gdb:m21010328,4
gdb:m21010258,4
gdb:g
gdb:X2101025c,4:? <remove breakpoint>
gdb:m2101025c,4
gdb:vCont;s:p10000.10001 <stop thread, trace ready><??c:-1 neden yok>
single step set
starting 65537 @2101025c
trace callback <instruction complete exception>
stopping 65537 @21010260
single step reset
gdb:m21010260,4
gdb:m21010264,4
gdb:m21010268,4
gdb:m2101026c,4
gdb:m21010270,4
gdb:m21010274,4
gdb:m21010278,4
gdb:m2101027c,4
gdb:m21010280,4
gdb:m21010284,4
gdb:m21010288,4
gdb:m2101028c,4
gdb:m21010290,4
gdb:m21010294,4
gdb:m21010298,4
gdb:m2101029c,4
gdb:m210102a0,4
gdb:m210102a4,4
gdb:m210102a8,4
gdb:m210102ac,4
gdb:m210102b0,4
gdb:m210102b4,4
gdb:m210102b8,4
gdb:m210102bc,4
gdb:m210102c0,4
gdb:m210102c4,4
gdb:m210102c8,4
gdb:m210102cc,4
gdb:m210102d0,4
gdb:m210102d4,4
gdb:m210102d8,4
gdb:m210102dc,4
gdb:m210102e0,4
gdb:m210102e4,4
gdb:m210102e8,4
gdb:m210102ec,4
gdb:m210102f0,4
gdb:m210102f4,4
gdb:m210102f8,4
gdb:m210102fc,4
gdb:m21010300,4
gdb:m21010304,4
gdb:m21010308,4
gdb:m2101030c,4
gdb:m21010310,4
gdb:m21010314,4
gdb:m21010318,4
gdb:m2101031c,4
gdb:m21010320,4
gdb:m21010324,4
gdb:m21010328,4
gdb:m2101032c,4
gdb:m2101025c,4
gdb:m21010258,4
gdb:g
gdb:m2101025c,4
gdb:X2101025c,4:}] <HATA put breakpoint>
gdb:vCont;c:p10000.-1 <cont all><HATA -1 gönderdiği için, trace yapmıyor>
starting 65537 @21010260

ELF file

void printHello(void)
{
210101e8:    94 21 ff f0     stwu    r1,-16(r1)
210101ec:    7c 08 02 a6     mflr    r0
210101f0:    90 01 00 14     stw     r0,20(r1)
210101f4:    93 e1 00 0c     stw     r31,12(r1)
210101f8:    7c 3f 0b 78     mr      r31,r1
     cout << "Hello World" << endl;
210101fc:    3d 20 21 04     lis     r9,8452
21010200:    38 69 01 78     addi    r3,r9,376
21010204:    3d 20 21 04     lis     r9,8452
21010208:    38 89 82 48     addi    r4,r9,-32184
2101020c:    48 02 1f a9     bl      210321b4
21010210:    7c 69 1b 78     mr      r9,r3
21010214:    7d 23 4b 78     mr      r3,r9
21010218:    3d 20 21 03     lis     r9,8451
2101021c:    38 89 26 ec     addi    r4,r9,9964
21010220:    48 02 25 45     bl      21032764
}
21010224:    39 7f 00 10     addi    r11,r31,16
21010228:    80 0b 00 04     lwz     r0,4(r11)
2101022c:    7c 08 03 a6     mtlr    r0
21010230:    83 eb ff fc     lwz     r31,-4(r11)
21010234:    7d 61 5b 78     mr      r1,r11
21010238:    4e 80 00 20     blr

2101023c :

int main()
{
2101023c:    94 21 ff e0     stwu    r1,-32(r1)
21010240:    7c 08 02 a6     mflr    r0
21010244:    90 01 00 24     stw     r0,36(r1)
21010248:    93 e1 00 1c     stw     r31,28(r1)
2101024c:    7c 3f 0b 78     mr      r31,r1
    int i = 0;
21010250:    39 20 00 00     li      r9,0
21010254:    91 3f 00 08     stw     r9,8(r31)
    printHello();
21010258:    4b ff ff 91     bl      210101e8 <_Z10printHellov>
        i++;
2101025c:    81 3f 00 08     lwz     r9,8(r31)
21010260:    39 29 00 01     addi    r9,r9,1
21010264:    91 3f 00 08     stw     r9,8(r31)
        i++;
21010268:    81 3f 00 08     lwz     r9,8(r31)
2101026c:    39 29 00 01     addi    r9,r9,1
21010270:    91 3f 00 08     stw     r9,8(r31)
        i++;
21010274:    81 3f 00 08     lwz     r9,8(r31)
21010278:    39 29 00 01     addi    r9,r9,1
2101027c:    91 3f 00 08     stw     r9,8(r31)


问:
Linking Fragments With Buttons
Can someone please help me?
i just want to add 2 Buttons in a activity and each button goes to a different fragment
for example:
Button 1 goes to Login_Fragment

Button 2 goes to SignUp_Fragment
those fragments have their own xml files
the code below is FirstPage and it's xml is first_page
so the below code will replace the first_page xml with the fragments xml files
how can i prevent that?

```<code>package com.example.logindesign;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

public class First_Page extends AppCompatActivity {
    Button createAccount, login;

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

        createAccount = findViewById(R.id.createAccount);
        createAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                SignUp_Fragment f2 = new SignUp_Fragment();
                fm.beginTransaction().replace(R.id.mParent, f2).commit();
            }
        });

        login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                Login_Fragment f2 = new Login_Fragment();
                fm.beginTransaction().add(R.id.mParent, f2).commit();
            }
        });
    }
}
</code>```

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Blue"
    android:id="@+id/mParent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/stay_connected_with_friends"
        android:textSize="28sp"
        android:textColor="@color/white"
        android:fontFamily="@font/nunito_bold"
        android:layout_marginTop="230dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="200dp"
        >

    </TextView>

    <Button
        android:id="@+id/createAccount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/sign_up"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="200dp"
        android:layout_marginBottom="172dp"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/login"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="175dp"
        android:layout_height="141dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="114dp"
        android:layout_marginBottom="136dp"
        android:contentDescription="@string/logo"
        app:srcCompat="@drawable/logo" />

</RelativeLayout>
</code>```

答:
use code like this,
 click on button A,

```<code> Fragment A = new FragmentA();
</code>```

click on button B,

```<code>Fragment B = new FragmentB();
</code>```

and make a function for both load Fragments,

```<code>public void loadFragment(Fragment f)
 {
    FragmentManager fm = getSupportFragmentManager();
    fm.beginTransaction().replace(R.id.main_contenier,f).commit();
 }
</code>```

Title: Linking Fragments With Buttons

Body:
Can someone please help me?
i just want to add 2 Buttons in a activity and each button goes to a different fragment
for example:
Button 1 goes to Login_Fragment

Button 2 goes to SignUp_Fragment
those fragments have their own xml files
the code below is FirstPage and it's xml is first_page
so the below code will replace the first_page xml with the fragments xml files
how can i prevent that?

package com.example.logindesign;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

public class First_Page extends AppCompatActivity {
    Button createAccount, login;

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

        createAccount = findViewById(R.id.createAccount);
        createAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                SignUp_Fragment f2 = new SignUp_Fragment();
                fm.beginTransaction().replace(R.id.mParent, f2).commit();
            }
        });

        login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                Login_Fragment f2 = new Login_Fragment();
                fm.beginTransaction().add(R.id.mParent, f2).commit();
            }
        });
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Blue"
    android:id="@+id/mParent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/stay_connected_with_friends"
        android:textSize="28sp"
        android:textColor="@color/white"
        android:fontFamily="@font/nunito_bold"
        android:layout_marginTop="230dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="200dp"
        >

    </TextView>

    <Button
        android:id="@+id/createAccount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/sign_up"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="200dp"
        android:layout_marginBottom="172dp"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/login"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="175dp"
        android:layout_height="141dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="114dp"
        android:layout_marginBottom="136dp"
        android:contentDescription="@string/logo"
        app:srcCompat="@drawable/logo" />

</RelativeLayout>

Body:
use code like this,
 click on button A,

 Fragment A = new FragmentA();

click on button B,

Fragment B = new FragmentB();

and make a function for both load Fragments,

public void loadFragment(Fragment f)
 {
    FragmentManager fm = getSupportFragmentManager();
    fm.beginTransaction().replace(R.id.main_contenier,f).commit();
 }


问:
Assigning version labels in model_config_file fails
I have versions 1 and 2 of a model and I'm trying to assign them labels, following the instructions at https://www.tensorflow.org/serving/serving_config#assigning_string_labels_to_model_versions_to_simplify_canary_and_rollback

I have exported the two versions in /path/to/model/1 and /path/to/model/2 respectively and I'm starting the server with the following command:

tensorflow_model_server --rest_api_port=8501 --model_config_file=models.config

The following models.config file works, and results in only serving version 1 (and if the specific message is omitted, version 2 is served as expected since it corresponds to the highest number):

```<code>model_config_list {
    config {
        name: 'm1'
        base_path: '/path/to/model/'
        model_platform: 'tensorflow'
        model_version_policy {
        specific {
            versions: 1
        }
    }
}
</code>```

I have verified that I can use the server to send requests to the model and perform inference as expected. However if I try to add version_labels by using this config file:

```<code>model_config_list {
    config {
        name: 'm1'
        base_path: '/path/to/model/'
        model_platform: 'tensorflow'
        model_version_policy {
        specific {
            versions: 1
        }
        version_labels {
            key: 'current'
            value: 1
        }
    }
}
</code>```

then launching the server fails with the following error:

Failed to start server. Error: Failed precondition: Request to assign label to version 1 of model m1, which is not currently available for inference.

I've also noticed that changing the value field to a non-existent version folder yields a similar result:

Failed to start server. Error: Failed precondition: Request to assign label to version 1234 of model m1, which is not currently available for inference.

I'm using:

```<code>TensorFlow ModelServer: 1.12.0-rc0+dev.sha.87470f0
TensorFlow Library: 1.12.0
</code>```

I couldn't find any SO questions on the topic of version_labels and the available tensorflow documentation seems incomplete and outdated (for instance it doesn't mention the need to pass model_platform: 'tensorflow' in the config file).

Any help would be much appreciated!

答:
More recently, it is possible to assign labels to models that are not yet loaded provided the --allow_version_labels_for_unavailable_models=true flag is specified (in the same place you specify your --model_config_file=... variable. (In my case, I do this in a docker-compose.yaml file.)

For more information, see the official documentation, which at the time of writinng says,

If you would like to assign a label to a version that is not yet loaded (for ex. by supplying both the model version and the label at startup time) then you must set the --allow_version_labels_for_unavailable_models flag to true, which allows new labels to be assigned to model versions that are not loaded yet.

Body:
I have versions 1 and 2 of a model and I'm trying to assign them labels, following the instructions at https://www.tensorflow.org/serving/serving_config#assigning_string_labels_to_model_versions_to_simplify_canary_and_rollback

I have exported the two versions in /path/to/model/1 and /path/to/model/2 respectively and I'm starting the server with the following command:

tensorflow_model_server --rest_api_port=8501 --model_config_file=models.config

The following models.config file works, and results in only serving version 1 (and if the specific message is omitted, version 2 is served as expected since it corresponds to the highest number):

model_config_list {
    config {
        name: 'm1'
        base_path: '/path/to/model/'
        model_platform: 'tensorflow'
        model_version_policy {
        specific {
            versions: 1
        }
    }
}

I have verified that I can use the server to send requests to the model and perform inference as expected. However if I try to add version_labels by using this config file:

model_config_list {
    config {
        name: 'm1'
        base_path: '/path/to/model/'
        model_platform: 'tensorflow'
        model_version_policy {
        specific {
            versions: 1
        }
        version_labels {
            key: 'current'
            value: 1
        }
    }
}

then launching the server fails with the following error:

Failed to start server. Error: Failed precondition: Request to assign label to version 1 of model m1, which is not currently available for inference.

I've also noticed that changing the value field to a non-existent version folder yields a similar result:

Failed to start server. Error: Failed precondition: Request to assign label to version 1234 of model m1, which is not currently available for inference.

I'm using:

TensorFlow ModelServer: 1.12.0-rc0+dev.sha.87470f0
TensorFlow Library: 1.12.0

I couldn't find any SO questions on the topic of version_labels and the available tensorflow documentation seems incomplete and outdated (for instance it doesn't mention the need to pass model_platform: 'tensorflow' in the config file).

Any help would be much appreciated!


问:
Date Format from Date in String to Date

Possible Duplicate:

String to Date in Different Format in Java

Hi,

I m receiving date as String data type in MM/dd/yyyy format and need to convert in data Datatype in format yyyy-MM-dd to store in DB.

答:
You can use SimpleDateFormat:</p>

```<code>SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat destinationFormat = new SimpleDateFormat("yyyy-MM-dd");

String result = sourceFormat.format(destinationFormat.parse(input));
</code>```

Title: Date Format from Date in String to Date

Body:
You can use SimpleDateFormat:

SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat destinationFormat = new SimpleDateFormat("yyyy-MM-dd");

String result = sourceFormat.format(destinationFormat.parse(input));


问:
Rename: FileNotFoundError: [WinError 2] - working with rasters
In my code in Python I keep getting the error

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Z_Cawc_000_005_estimated_value.tfw' -> 'awc_000_005_estimated_value.tfw'

So,
'Z_Cawc_000_005_estimated_value.tfw' is the name of the first raster on a folder with 800 rasters.

All I want is to get rid off the initial "Z_C" characters of the 800 raster files in a folder.

My code is

```<code>    import os
    path = os.getcwd()
    filenames =
    os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
    for filename in filenames:
        os.rename(filename, filename.replace("Z_C",""))
</code>```

I`ve also try the following code:

```<code>    from os import rename, listdir

    badprefix = "Z_C"
    fnames = listdir('I:\\PhD_2019\\Spatial_Datasets\\Baroon_Pocket_Dam_Catchment\\Raster\\Soil_Zonal_Stats')

    for fname in fnames:
        if fname.startswith(badprefix):
            rename(fname, fname.replace(badprefix, '', 1))
</code>```

and the following code as well:

```<code>    import os
    path =  os.getcwd()
    filenames = os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats' )

    for filename in filenames:
        os.rename(filename, filename.replace("Z_C", ""))
</code>```

But both of them resulted in the same error!
Can anyone let me know what is wrong with my code, please?

答:
You need to specify the full path to the file, otherwise python would look in your working directory and won't find the file. the fix is:</p>

```<code>folder = r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats'
filenames =
    os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
    for filename in filenames:
        os.rename(os.path.join(folder, filename), os.path.join(folder, filename.replace("Z_C","")))
</code>```

Body:
In my code in Python I keep getting the error

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Z_Cawc_000_005_estimated_value.tfw' -> 'awc_000_005_estimated_value.tfw'

So,
'Z_Cawc_000_005_estimated_value.tfw' is the name of the first raster on a folder with 800 rasters.

All I want is to get rid off the initial "Z_C" characters of the 800 raster files in a folder.

My code is

    import os
    path = os.getcwd()
    filenames =
    os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
    for filename in filenames:
        os.rename(filename, filename.replace("Z_C",""))

I`ve also try the following code:

    from os import rename, listdir

    badprefix = "Z_C"
    fnames = listdir('I:\\PhD_2019\\Spatial_Datasets\\Baroon_Pocket_Dam_Catchment\\Raster\\Soil_Zonal_Stats')

    for fname in fnames:
        if fname.startswith(badprefix):
            rename(fname, fname.replace(badprefix, '', 1))

and the following code as well:

    import os
    path =  os.getcwd()
    filenames = os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats' )

    for filename in filenames:
        os.rename(filename, filename.replace("Z_C", ""))

But both of them resulted in the same error!
Can anyone let me know what is wrong with my code, please?

Body:
You need to specify the full path to the file, otherwise python would look in your working directory and won't find the file. the fix is:

folder = r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats'
filenames =
    os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
    for filename in filenames:
        os.rename(os.path.join(folder, filename), os.path.join(folder, filename.replace("Z_C","")))