问:
Angular - Mat Paginator : Multiple Tables in a component
I am stuck on an issue for a while now, searched for solution but, unfortunately, nothing is working.

I am rendering 5 tables on the screen. The table data is fetched using a GET call. The tables are getting rendered without an issue but I am unable to implement pagination on them. The pagination controls work fine but the table data is not updated. I can see the total elements in the array and i can move around with the direction key, change the page size but it has no effect on table. The table is stuck on the five records.

Here is my .ts file

```<code>  @ViewChild(MatPaginator) paginatorLegal: MatPaginator;
  @ViewChild(MatPaginator) paginatorGSTN: MatPaginator;
  @ViewChild(MatPaginator) paginatorPHYS: MatPaginator;
  @ViewChild(MatPaginator) paginatorLink: MatPaginator;
  // @ViewChild(MatPaginator, {read: true}) paginatorLink: MatPaginator;
  @ViewChild(MatPaginator) paginatorAlias: MatPaginator;

  ORGANIZATION_LINK //I removed it from Datasource object to see if it will somehow fix the issue.

  DATASOURCES = {
    LEGAL_ADDRESS: <any>[],
    TELECOM_ADDRESS: <any>[],
    GSTN_ADDRESS: <any>[],
    PHYSICAL_ADDRESS: <any>[],
    ORGANIZATION_ALIAS: <any>[]
  }

  ngOnInit() {
    // this.organizationData.push(this.data['dataKey'])
    this.cust_service.organizationToViewOrg.subscribe(data => {
      this.organizationData = data
      this.legalAddressTableCreation(data[0].legalAddress)
      this.fetchTABLES();
    })
}

  fetchORGLINK() {
    this.cust_service.getOrgLink(this.organizationData[0]['orgNumber'], resp => {
      if (resp['data']['allOrganizationLinkList'].length > 0) {
        this.ORGANIZATION_LINK = new MatTableDataSource(resp['data']['allOrganizationLinkList'])
        // this.ORGANIZATION_LINK.paginatorLink = this.paginatorLink
        setTimeout(() => this.ORGANIZATION_LINK.paginator = this.paginatorLink);

      }
      else {
        this.orgLinkNull = true;
      }
    },
      err => {
        this.orgLinkNull = true;
      }
    );
  }

  fetchORGALIAS() {
    this.cust_service.getOrgAliasFn(this.organizationData[0]['orgNumber'], resp => {
      if (resp['data']['allOrganizationAliasList'].length > 0) {
        this.DATASOURCES.ORGANIZATION_ALIAS = new MatTableDataSource(resp['data']['allOrganizationAliasList'])
        setTimeout(() => { this.DATASOURCES.ORGANIZATION_ALIAS.paginator = this.paginatorAlias });
      }
      else {
        this.orgAliasNull = true;
      }
    },
      err => {
        this.orgAliasNull = true;
      })
  }

  fetchTABLES() {
    this.fetchGSTN(); // same implementation as fetch org link or fetch alias
    this.fetchPHYSICAL(); //same implementation as fetch org link or fetch alias
    this.fetchORGLINK();
    this.fetchORGALIAS();
  }
</code>```

the HTML looks like

```<code>  <div class="card">
    <div class="card-header">
        <b>Legal Address</b>
    </div>

    <div class="card-body">

      <div class="table" *ngIf="!GSTN_null">
        <div class="searchPagination">
          <mat-paginator #paginatorLegal [length]="this.DATASOURCES.LEGAL_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
        </div>

        <mat-table [dataSource]="this.DATASOURCES.LEGAL_ADDRESS" class="mat-table_">

          //data
        </mat-table>
      </div>

      <div class="noRecords" *ngIf='GSTN_null'>
        <b>No Records Found....</b>
      </div>

    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <b>GSTN Address</b>
    </div>

    <div class="card-body">

      <div class="table" *ngIf="!GSTN_null">
        <div class="searchPagination">
          <mat-paginator #paginatorGSTN [length]="this.DATASOURCES.GSTN_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
        </div>

        <mat-table [dataSource]="this.DATASOURCES.GSTN_ADDRESS" class="mat-table_">

          //data
        </mat-table>
      </div>

      <div class="noRecords" *ngIf='GSTN_null'>
        <b>No Records Found....</b>
      </div>

    </div>
  </div>

  <div class="card">
    <div class="card-header">
        <b>Physical Address</b>
    </div>

    <div class="card-body">

      <div class="table" *ngIf="!physicalNull">

        <div class="searchPagination">
          <mat-paginator #paginatorPHYS [length]="this.DATASOURCES.PHYSICAL_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
        </div>

        <mat-table [dataSource]="this.DATASOURCES.PHYSICAL_ADDRESS" class="mat-table_">

          //data
        </mat-table>
      </div>

      <div class="noRecords" *ngIf='physicalNull'>
        <b>No Records Found....</b>
      </div>

    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <b>Organization Link</b>
    </div>

    <div class="card-body">

      <div class="table" *ngIf="!orgLinkNull">

        <div class="searchPagination">
          <mat-paginator #paginatorLink [length]="this.ORGANIZATION_LINK?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
        </div>

        <mat-table [dataSource]="this.ORGANIZATION_LINK" class="mat-table_">
    //data
        </mat-table>
      </div>

      <div class="noRecords" *ngIf='orgLinkNull'>
        <b>No Records Found....</b>
      </div>

    </div>
  </div>

  <div class="card">
    <div class="card-header"><b>Organization Alias</b></div>

    <div class="card-body">

      <div class="table" *ngIf="!orgAliasNull">

        <div class="searchPagination">
          <mat-paginator #paginatorAlias [length]="this.DATASOURCES.ORGANIZATION_ALIAS?.filteredData?.length"
            [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
        </div>

        <mat-table [dataSource]="this.DATASOURCES.ORGANIZATION_ALIAS" class="mat-table_">
//data
        </mat-table>
      </div>

      <div class="noRecords" *ngIf='orgAliasNull'>
        <b>No Records Found....</b>
      </div>

    </div>
  </div>
</code>```

Is there something that I am missing (Been working for 12 hours straight), a typo or something? Or is there another way to tackle this issue and making the pagination work on the tables.

答:
First tell your component the alias of the matPaginator which you are going to bind in the HTML.

For Example in your HTML it should be like this:

 <mat-paginator #paginatorLegal="matPaginator"
 [length]="this.DATASOURCES.LEGAL_ADDRESS?.filteredData?.length" [pageSize]="5"
 [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
```
<pre class="lang-html prettyprint-override"><code> <mat-paginator #paginatorGSTN="matPaginator"
 [length]="this.DATASOURCES.GSTN_ADDRESS?.filteredData?.length" [pageSize]="5"
 [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>
</code>```

And then bind to them in your .ts component using ViewChild alias property

 @ViewChild('paginatorLegal') paginatorLegal: MatPaginator;
 @ViewChild('paginatorGSTN') paginatorGSTN: MatPaginator;
```

and then finally when you get the data you should bind the paginators where the respective MatTableDataSource which you already did in the subscribe code.

Body:
I am stuck on an issue for a while now, searched for solution but, unfortunately, nothing is working.

I am rendering 5 tables on the screen. The table data is fetched using a GET call. The tables are getting rendered without an issue but I am unable to implement pagination on them. The pagination controls work fine but the table data is not updated. I can see the total elements in the array and i can move around with the direction key, change the page size but it has no effect on table. The table is stuck on the five records.

Here is my .ts file

  @ViewChild(MatPaginator) paginatorLegal: MatPaginator;
  @ViewChild(MatPaginator) paginatorGSTN: MatPaginator;
  @ViewChild(MatPaginator) paginatorPHYS: MatPaginator;
  @ViewChild(MatPaginator) paginatorLink: MatPaginator;
  // @ViewChild(MatPaginator, {read: true}) paginatorLink: MatPaginator;
  @ViewChild(MatPaginator) paginatorAlias: MatPaginator;

  ORGANIZATION_LINK //I removed it from Datasource object to see if it will somehow fix the issue.

  DATASOURCES = {
    LEGAL_ADDRESS: <any>[],
    TELECOM_ADDRESS: <any>[],
    GSTN_ADDRESS: <any>[],
    PHYSICAL_ADDRESS: <any>[],
    ORGANIZATION_ALIAS: <any>[]
  }

  ngOnInit() {
    // this.organizationData.push(this.data['dataKey'])
    this.cust_service.organizationToViewOrg.subscribe(data => {
      this.organizationData = data
      this.legalAddressTableCreation(data[0].legalAddress)
      this.fetchTABLES();
    })
}

  fetchORGLINK() {
    this.cust_service.getOrgLink(this.organizationData[0]['orgNumber'], resp => {
      if (resp['data']['allOrganizationLinkList'].length > 0) {
        this.ORGANIZATION_LINK = new MatTableDataSource(resp['data']['allOrganizationLinkList'])
        // this.ORGANIZATION_LINK.paginatorLink = this.paginatorLink
        setTimeout(() => this.ORGANIZATION_LINK.paginator = this.paginatorLink);

      }
      else {
        this.orgLinkNull = true;
      }
    },
      err => {
        this.orgLinkNull = true;
      }
    );
  }

  fetchORGALIAS() {
    this.cust_service.getOrgAliasFn(this.organizationData[0]['orgNumber'], resp => {
      if (resp['data']['allOrganizationAliasList'].length > 0) {
        this.DATASOURCES.ORGANIZATION_ALIAS = new MatTableDataSource(resp['data']['allOrganizationAliasList'])
        setTimeout(() => { this.DATASOURCES.ORGANIZATION_ALIAS.paginator = this.paginatorAlias });
      }
      else {
        this.orgAliasNull = true;
      }
    },
      err => {
        this.orgAliasNull = true;
      })
  }

  fetchTABLES() {
    this.fetchGSTN(); // same implementation as fetch org link or fetch alias
    this.fetchPHYSICAL(); //same implementation as fetch org link or fetch alias
    this.fetchORGLINK();
    this.fetchORGALIAS();
  }

the HTML looks like

        Legal Address

          <mat-paginator #paginatorLegal [length]="this.DATASOURCES.LEGAL_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

        <mat-table [dataSource]="this.DATASOURCES.LEGAL_ADDRESS" class="mat-table_">

          //data
        </mat-table>

        No Records Found....

      GSTN Address

          <mat-paginator #paginatorGSTN [length]="this.DATASOURCES.GSTN_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

        <mat-table [dataSource]="this.DATASOURCES.GSTN_ADDRESS" class="mat-table_">

          //data
        </mat-table>

        No Records Found....

        Physical Address

          <mat-paginator #paginatorPHYS [length]="this.DATASOURCES.PHYSICAL_ADDRESS?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

        <mat-table [dataSource]="this.DATASOURCES.PHYSICAL_ADDRESS" class="mat-table_">

          //data
        </mat-table>

        No Records Found....

      Organization Link

          <mat-paginator #paginatorLink [length]="this.ORGANIZATION_LINK?.filteredData?.length" [pageSize]="5"
            [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

        <mat-table [dataSource]="this.ORGANIZATION_LINK" class="mat-table_">
    //data
        </mat-table>

        No Records Found....

Organization Alias

          <mat-paginator #paginatorAlias [length]="this.DATASOURCES.ORGANIZATION_ALIAS?.filteredData?.length"
            [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

        <mat-table [dataSource]="this.DATASOURCES.ORGANIZATION_ALIAS" class="mat-table_">
//data
        </mat-table>

        No Records Found....

Is there something that I am missing (Been working for 12 hours straight), a typo or something? Or is there another way to tackle this issue and making the pagination work on the tables.

Body:
First tell your component the alias of the matPaginator which you are going to bind in the HTML.

For Example in your HTML it should be like this:

 <mat-paginator #paginatorLegal="matPaginator"
 [length]="this.DATASOURCES.LEGAL_ADDRESS?.filteredData?.length" [pageSize]="5"
 [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

 <mat-paginator #paginatorGSTN="matPaginator"
 [length]="this.DATASOURCES.GSTN_ADDRESS?.filteredData?.length" [pageSize]="5"
 [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page"></mat-paginator>

And then bind to them in your .ts component using ViewChild alias property

 @ViewChild('paginatorLegal') paginatorLegal: MatPaginator;
 @ViewChild('paginatorGSTN') paginatorGSTN: MatPaginator;

and then finally when you get the data you should bind the paginators where the respective MatTableDataSource which you already did in the subscribe code.


来源: stackexchange

问:
How to change a git submodule to point to a subfolder?
Skimming through the SubModule tutorial, I created a submodule out of the boto project. Then, I discovered that I actually need only a subset of this project - specifically, the boto folder.

I would like to change my submodule to point to this folder. When I look in .gitmodules, I see

```<code>[submodule "backup/src/boto"]
    path = backup/src/boto
    url = https://github.com/boto/boto.git
</code>```

What URL should I use instead of https://github.com/boto/boto.git? After I change the URL, should I delete the boto folder locally and re-pull?

答:
All the answers here are pretty dated. You could use the newer git sparse-checkout command docs here, further examples in this article to grab pieces of a repo. This is effective if you only want a directory or two from a larger git project.

TLDR:

git sparse-checkout init --cone
git sparse-checkout set <dir1> <dir2> ...
git checkout main
```

ContentLicense: CC BY-SA 2.5

Body:
Skimming through the SubModule tutorial, I created a submodule out of the boto project. Then, I discovered that I actually need only a subset of this project - specifically, the boto folder.

I would like to change my submodule to point to this folder. When I look in .gitmodules, I see

[submodule "backup/src/boto"]
    path = backup/src/boto
    url = https://github.com/boto/boto.git

What URL should I use instead of https://github.com/boto/boto.git? After I change the URL, should I delete the boto folder locally and re-pull?

ContentLicense: CC BY-SA 4.0


问:
Menu dropdown in html, css and js from mobile and desktop
i refer to this thread: JS using onclick event on li to display block

From desktop is ok but how do i do the same thing but that from the mobile you can touch the "disappearing" menu and make sure that it remains visible until the next touch?

I'm currently using this code here:

function dropdown() {
  document.getElementById("Menuitems").style.display = "block";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown ul {
  display: block;
  transition-duration: 1s;
}

#dropdown ul li {
  display: block;
  background-color: #212121;
  color: #ffffff;
}

#dropdown ul li ul {
  display: none;
}

#dropdown ul li:hover>ul {
  /*this is what the onclick event should do*/
  display: block;
}</code>```

Menu

item 1

item 2

item 3

```

答:
I just added an active class onclick .. the active class toggles on every click. and just add the same hover effect to active class

function dropdown() {
  document.getElementById("Menuitems").classList.toggle("active");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown ul {
  display: block;
  transition-duration: 1s;
}

#dropdown ul li {
  display: block;
  background-color: #212121;
  color: #ffffff;
}

#dropdown ul li ul {
  display: none;
}

#dropdown ul li:hover>ul,
#dropdown ul li>ul.active{
  /*this is what the onclick event should do*/
  display: block;
}</code>```

Menu

item 1

item 2

item 3

```

Body:
i refer to this thread: JS using onclick event on li to display block

From desktop is ok but how do i do the same thing but that from the mobile you can touch the "disappearing" menu and make sure that it remains visible until the next touch?

I'm currently using this code here:

function dropdown() {
  document.getElementById("Menuitems").style.display = "block";
}

#dropdown ul {
  display: block;
  transition-duration: 1s;
}

#dropdown ul li {
  display: block;
  background-color: #212121;
  color: #ffffff;
}

#dropdown ul li ul {
  display: none;
}

#dropdown ul li:hover>ul {
  /*this is what the onclick event should do*/
  display: block;
}

Menu

item 1

item 2

item 3

Body:
I just added an active class onclick .. the active class toggles on every click. and just add the same hover effect to active class

function dropdown() {
  document.getElementById("Menuitems").classList.toggle("active");
}

#dropdown ul {
  display: block;
  transition-duration: 1s;
}

#dropdown ul li {
  display: block;
  background-color: #212121;
  color: #ffffff;
}

#dropdown ul li ul {
  display: none;
}

#dropdown ul li:hover>ul,
#dropdown ul li>ul.active{
  /*this is what the onclick event should do*/
  display: block;
}

<div id="dropdown">
  <ul>
    <li onclick="dropdown()"><a>Menu</a>
      <ul id="Menuitems">
        <li><a href="">item 1</a> </li>
        <li><a href="">item 2</a> </li>
        <li><a href="">item 3</a> </li>
      </ul>
    </li>
  </ul>
</div>


问:
GET() missing 1 required positional argument : how do i format a GET request to include parameters?
I have a webapp with the following code, which is supposed to serve up any .html file I have stored in the htmls/ directory, provided the two parameters urlhash and predictiontag are correct.

```<code>import web

urls = (
    '/htmlview/(.*)', 'htmlview'
)

class htmlview:
    def GET(self, urlhash, predictiontag):
        cache_dir = os.path.join("htmls\\", urlhash)
        htmlpath = os.path.join(cache_dir, predictiontag + ".html")
        with open(htmlpath, "r", encoding="utf-8") as f:
            data = f.read()
        return data

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
</code>```

I don't know how to format the GET request from a browser window in order to actually access these files. I tried http://localhost:8080/htmlview/a?urlhash=6355865449554195623&predictiontag=Primary but it gave me the error:

```<code><class 'TypeError'> at /htmlview/a
GET() missing 1 required positional argument: 'predictiontag'
</code>```

For reference, here is the other post I was following: How to serve file in webpy?

答:
Use urls regular expression to match url path.

Use web.input() to access query string.

For your example url: http://localhost:8080/htmlview/a?urlhash=6355865449554195623&predictiontag=Primary

```<code>url = ( '/htmlview/(.*)', 'htmlview', )
</code>```

Will pass only 'a' as the first parameter to htmlview.GET(). The remainder is obtainable within htmlview.GET() using web.input():

```<code>class htmlview:
    def GET(self, path):
        urlhash = web.input().urlhash
        predictiontag = web.input().predictiontag

</code>```

Body:
I have a webapp with the following code, which is supposed to serve up any .html file I have stored in the htmls/ directory, provided the two parameters urlhash and predictiontag are correct.

import web

urls = (
    '/htmlview/(.*)', 'htmlview'
)

class htmlview:
    def GET(self, urlhash, predictiontag):
        cache_dir = os.path.join("htmls\\", urlhash)
        htmlpath = os.path.join(cache_dir, predictiontag + ".html")
        with open(htmlpath, "r", encoding="utf-8") as f:
            data = f.read()
        return data

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

I don't know how to format the GET request from a browser window in order to actually access these files. I tried http://localhost:8080/htmlview/a?urlhash=6355865449554195623&predictiontag=Primary but it gave me the error:

<class 'TypeError'> at /htmlview/a
GET() missing 1 required positional argument: 'predictiontag'

For reference, here is the other post I was following: How to serve file in webpy?

Body:
Use urls regular expression to match url path.

Use web.input() to access query string.

For your example url: http://localhost:8080/htmlview/a?urlhash=6355865449554195623&predictiontag=Primary

url = ( '/htmlview/(.*)', 'htmlview', )

Will pass only 'a' as the first parameter to htmlview.GET(). The remainder is obtainable within htmlview.GET() using web.input():

class htmlview:
    def GET(self, path):
        urlhash = web.input().urlhash
        predictiontag = web.input().predictiontag


问:
random image on load
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

```<code>$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('<img src="images/logo/' + Rlogo[rand] + '">').appendTo('#logo');
  });
</code>```

in my html i have;

```<code><img src="images/logo/BIMP_oranje.jpg" id="logo" align="right" alt='align="right"'>
</code>```

the image doesn;t change on refresh.

please help

答:
Try replacing this line:

```<code>$('<img src="images/logo/' + Rlogo[rand] + '">').appendTo('#logo');
</code>```

with this:

```<code>$('#logo').attr("src","images/logo/" + Rlogo[rand]);
</code>```

Essentially what this means is "get the DOM element with id="logo" and change the "src" element to "images/logo/" + Rlogo[rand].

ContentLicense: CC BY-SA 3.0

Title: random image on load

Body:
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('').appendTo('#logo');
  });

in my html i have;

the image doesn;t change on refresh.

please help

Body:
Try replacing this line:

$('<img src="images/logo/' + Rlogo[rand] + '">').appendTo('#logo');

with this:

$('#logo').attr("src","images/logo/" + Rlogo[rand]);

Essentially what this means is "get the DOM element with id="logo" and change the "src" element to "images/logo/" + Rlogo[rand].


问:
stop IntelliJ IDEA to switch java language level every time the pom is reloaded (or change the default project language level)
Using IntelliJ 12, I have a java project and I use maven with a pom.xml.
My project is using java8, but it seems the default project language level has been set to 6 while importing the project.

I can change the language level to 8.0 (F4 -> Modules -> Language level) however every time I edit my pom.xml the project level is switched back to "use project language level", and I have to edit this settings again and again.

Is there something I need to add to the pom.xml to set the default language level to 8.0?

答:
Problem: Expected Java version: 11 but Stuck at version: 8

I tried almost all the answers, still I was stuck with language_level 8 and nowhere in my project or in the Intellij IDE I found any trace that could relate to Java version 8.

Then I explored the pom.xml of the parent with no success but in the pom.xml of the grand-parent, I found that the release version is 8.

Solution:
Adding the following 3 lines in the properties made the difference.

```<code><properties>
  <maven.compiler.source>11</maven.compiler.source>
  <maven.compiler.target>11</maven.compiler.target>
  <maven.compiler.release>11</maven.compiler.release>
</properties>
</code>```

Body:
Problem: Expected Java version: 11 but Stuck at version: 8

I tried almost all the answers, still I was stuck with language_level 8 and nowhere in my project or in the Intellij IDE I found any trace that could relate to Java version 8.

Then I explored the pom.xml of the parent with no success but in the pom.xml of the grand-parent, I found that the release version is 8.

Solution:
Adding the following 3 lines in the properties made the difference.

<properties>
  <maven.compiler.source>11</maven.compiler.source>
  <maven.compiler.target>11</maven.compiler.target>
  <maven.compiler.release>11</maven.compiler.release>
</properties>


问:
How can I remove duplicate rows from a data frame when the data is the same, but in a different order in R?
I have the following data frame:

df <- data.frame(node1=c("a","b", "c","d"), node2=c("b","a","f","g"),value=c(2,2,5,7))

I want to remove rows where node1 and node2 contain the same letters (Regardless of order) and same value so the resulting df should look like:

df <- data.frame(node1=c("a","c","d"), node2=c("b","f","g"), value=c(2,5,7))

Please help, thank you.

答:
This uses an environment to keep track of already seen node1, node2 and value combinations:

library(dplyr)
library(purrr)

df |> filter({
    M <- new.env()

    key <- purrr::map2(node1, node2, c) |>
        purrr::map(sort) |>
        purrr::map(~ paste(.x,collapse = "\t"))

    purrr::map2_lgl(key, value, ~{
        if (is.null(M[[.x]])) {
            M[[.x]] <<- list()
        }
        res <- ! .y %in% M[[.x]]
        M[[.x]] <<- union(M[[.x]], .y)
        res
    })
})

# A tibble: 3 x 3
  node1 node2 value
  <chr> <chr> <dbl>
1 a     b         2
2 c     f         5
3 d     g         7
```


问:
How do I use subscript and superscript in Swift?
I want my UILabel to display text in following manner 6.022*1023. What functions does Swift have for subscript and superscript?

答:
I wrote a fun little algorithm for this as an extension on Int that doesn't require any messy attributed strings.

Usage:

```<code>let superscriptString = 8675309.superscriptString
</code>```

Implementation:

```<code>extension Int {

    var superscriptString: String {

        var input: Int = self
        var result: String = ""

        while input > 0 {
            let lastDigit = input % 10
            input /= 10
            guard let superscript = lastDigit.superscript else { continue }
            result = superscript + result
        }

        return result
    }

    private var superscript: String? {
        switch self {
        case 0:
            return "\u{2070}"
        case 1:
            return "\u{00B9}"
        case 2:
            return "\u{00B2}"
        case 3:
            return "\u{00B3}"
        case 4:
            return "\u{2074}"
        case 5:
            return "\u{2075}"
        case 6:
            return "\u{2076}"
        case 7:
            return "\u{2077}"
        case 8:
            return "\u{2078}"
        case 9:
            return "\u{2079}"
        default:
            return nil
        }
    }

}
</code>```

Body:
I wrote a fun little algorithm for this as an extension on Int that doesn't require any messy attributed strings.

Usage:

let superscriptString = 8675309.superscriptString

Implementation:

extension Int {

    var superscriptString: String {

        var input: Int = self
        var result: String = ""

        while input > 0 {
            let lastDigit = input % 10
            input /= 10
            guard let superscript = lastDigit.superscript else { continue }
            result = superscript + result
        }

        return result
    }

    private var superscript: String? {
        switch self {
        case 0:
            return "\u{2070}"
        case 1:
            return "\u{00B9}"
        case 2:
            return "\u{00B2}"
        case 3:
            return "\u{00B3}"
        case 4:
            return "\u{2074}"
        case 5:
            return "\u{2075}"
        case 6:
            return "\u{2076}"
        case 7:
            return "\u{2077}"
        case 8:
            return "\u{2078}"
        case 9:
            return "\u{2079}"
        default:
            return nil
        }
    }

}


问:
Flickity How to make the carousel resize based on image size?
I'm trying to achieve something similar to the graphic below.

Blue = Carousel Slides (As Images)

Green = Carousel Frame/Viewport/Container

Red = Visible Page (1440)

I have 5 images, all with the same resolution of (1024x576), and I want them to maintain their ratio while scaling up/down based on screen size.

I've spent several hours on this now and I've been unable to achieve what I want.

I DO NOT want to use some fixed height like is shown in a majority of the demos on their website, since it becomes problematic when scaling down to smaller devices.

The reason I post this question is because any time I try and use anything OTHER than a fixed height, the entire carousel collapses, even with adaptiveHeight: true, and/or setGallerySize: false.

I'm also using tailwind if that helps at all.

Any help is appreciated.

答:
.carousel-cell {
  min-height: 100%;
  width: 100%;
}

.carousel-cell img {
  width: 100%;
}
```

Using min-height instead of height on the .carousel-cell style seems to help avoid interfering with Flickity's internal calculations.

Demo:
https://codepen.io/chrisfritz/pen/RwjVvLV

Body:
.carousel-cell {
  min-height: 100%;
  width: 100%;
}

.carousel-cell img {
  width: 100%;
}

Using min-height instead of height on the .carousel-cell style seems to help avoid interfering with Flickity's internal calculations.

Demo:
https://codepen.io/chrisfritz/pen/RwjVvLV


问:
Is there another way to get value directly in drf serializer?
Let's assume we have two model

```<code>Listing

class ListingStatus(models.Model):
    FULL = 0
    AVALIABLE = 1

    STATUS_CATEGORY = (
        (FULL, _("Full")),
        (AVALIABLE, _("AVAIL")),
    )

    listing = models.OneToOneField(Listing, on_delete=models.CASCADE)
    status = models.SmallIntegerField(choices=STATUS_CATEGORY, default=AVALIABLE)

    def __str__(self):
        return str(self.status)
</code>```

In serializer code

```<code>class ListingStatusSerializer(ReadOnlyModelSerializer):
    class Meta:
        model = ListingStatus
        fields = ["status"]

class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus.status")
</code>```

It doesn't work.
I get empty serializer

```<code>class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus")
</code>```

This works but I need to get status value like instance.status.status. it's inefficient

```<code>class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus")

    def get_status(self, instance):
        return instance.listingstatus.status
</code>```

I can achieve what I want with above code , but I want to make sure it's best solution?

答:
use the get_field_display approach.

```<code>class ListingSerializer(ReadOnlyModelSerializer):
    status = serializers.CharField(source="get_status_display")
</code>```

Body:
Let's assume we have two model

Listing

class ListingStatus(models.Model):
    FULL = 0
    AVALIABLE = 1

    STATUS_CATEGORY = (
        (FULL, _("Full")),
        (AVALIABLE, _("AVAIL")),
    )

    listing = models.OneToOneField(Listing, on_delete=models.CASCADE)
    status = models.SmallIntegerField(choices=STATUS_CATEGORY, default=AVALIABLE)

    def __str__(self):
        return str(self.status)

In serializer code

class ListingStatusSerializer(ReadOnlyModelSerializer):
    class Meta:
        model = ListingStatus
        fields = ["status"]

class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus.status")

It doesn't work.
I get empty serializer

class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus")

This works but I need to get status value like instance.status.status. it's inefficient

class ListingSerializer(ReadOnlyModelSerializer):
    status = ListingStatusSerializer(source="listingstatus")

    def get_status(self, instance):
        return instance.listingstatus.status

I can achieve what I want with above code , but I want to make sure it's best solution?

Body:
use the get_field_display approach.

class ListingSerializer(ReadOnlyModelSerializer):
    status = serializers.CharField(source="get_status_display")


问:
Nginx mirror not forwarding to mirror link
I currently have this nginx setup:

```<code>events {
    worker_connections  4096;
}

http {
    log_format upstreamlog '[$time_local] Forwarding $request from $remote_addr to: ($upstream_addr $request_uri $request) - Statuscode: $upstream_status Response time: $upstream_response_time';
    log_format upstreamlogmirror '[$time_local] Forwarding mirror $request from $remote_addr to: ($upstream_addr $request_uri $request): Statuscode: $upstream_status Response time: $upstream_response_time';

    server {
        listen        0.0.0.0:80;
        listen        0.0.0.0:443;

        location / {
            access_log  /dev/stdout upstreamlog;
            mirror /mirror;
            proxy_pass https://first.service.com/api/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /mirror {
            internal;
            proxy_pass http://127.0.0.1:55555/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    server {
        listen 127.0.0.1:55555;
        location / {
            access_log  /dev/stdout upstreamlogmirror;
            proxy_pass https://second.service.com/;
        }
    }
}
</code>```

However, I am facing some difficulties with this.

It seems like the mirrored server is indeed receiving a request (I see it in the logs), but when requesting e.g. https://localhost/myroute, it will properly forward to https://first.service.com/api/myroute, but the second service is only sent to https://second.service.com/ without having the route appended.

I also tried to do the whole thing with this setup:

```<code>        location / {
            access_log  /dev/stdout upstreamlog;
            mirror /mirror;
            proxy_pass https://first.service.com/api/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /mirror {
            internal;
            access_log  /dev/stdout upstreamlogmirror;
            proxy_pass http://second.service.com/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
</code>```

This works just fine, but in this case I am not getting any logs at all.

Where am I going wrong here?

答:
You have to add the $request_uri to the proxy_pass to send the full URI to the second, mirrored backend. Just tested in my lab:

```<code>server {
  listen 9001;
  log_subrequest on;
  access_log /var/log/nginx/mirror.log upstream_time;
  location / {
    mirror /mirror;
    proxy_pass http://127.0.0.1:9002/;
  }

  location = /mirror {
    proxy_pass http://127.0.0.1:8000$request_uri;
 }
}

server {listen 9002; return 200 "Server 1\n";}
</code>```

Make sure adding the internal directive to the mirror location.

As responses from the mirror will be ignored I am using an Python http.server to fake my backend and see the trace the incoming requests.

python3 -m http.server 8000

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [05/Feb/2022 22:00:45] code 404, message File not found
127.0.0.1 - - [05/Feb/2022 22:00:45] "GET /test/something HTTP/1.0" 404 -
```
<p>The NGINX logs after submitting a simple curl
<code>curl 127.0.0.1:9001/test/something</code></p>
<pre class="lang-sh prettyprint-override"><code>127.0.0.1 - - [05/Feb/2022:22:08:46 -0500] "GET /test/something HTTP/1.1" 404 156 "-" "curl/7.29.0" upa="127.0.0.1:8000/test/something" rt=0.003 uct="0.000" uht="0.003" urt="0.003"
127.0.0.1 - - [05/Feb/2022:22:08:46 -0500] "GET /test/something HTTP/1.1" 200 9 "-" "curl/7.29.0" upa="127.0.0.1:9002/test/something" rt=0.003 uct="0.000" uht="0.001" urt="0.001"
</code>```

To have the correct URI in your log file, make sure you are adding $request_uri to your logformat. The $uri variable will change to /mirror.

Read more https://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri

Body:
I currently have this nginx setup:

events {
    worker_connections  4096;
}

http {
    log_format upstreamlog '[$time_local] Forwarding $request from $remote_addr to: ($upstream_addr $request_uri $request) - Statuscode: $upstream_status Response time: $upstream_response_time';
    log_format upstreamlogmirror '[$time_local] Forwarding mirror $request from $remote_addr to: ($upstream_addr $request_uri $request): Statuscode: $upstream_status Response time: $upstream_response_time';

    server {
        listen        0.0.0.0:80;
        listen        0.0.0.0:443;

        location / {
            access_log  /dev/stdout upstreamlog;
            mirror /mirror;
            proxy_pass https://first.service.com/api/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /mirror {
            internal;
            proxy_pass http://127.0.0.1:55555/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    server {
        listen 127.0.0.1:55555;
        location / {
            access_log  /dev/stdout upstreamlogmirror;
            proxy_pass https://second.service.com/;
        }
    }
}

However, I am facing some difficulties with this.

It seems like the mirrored server is indeed receiving a request (I see it in the logs), but when requesting e.g. https://localhost/myroute, it will properly forward to https://first.service.com/api/myroute, but the second service is only sent to https://second.service.com/ without having the route appended.

I also tried to do the whole thing with this setup:

        location / {
            access_log  /dev/stdout upstreamlog;
            mirror /mirror;
            proxy_pass https://first.service.com/api/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /mirror {
            internal;
            access_log  /dev/stdout upstreamlogmirror;
            proxy_pass http://second.service.com/;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

This works just fine, but in this case I am not getting any logs at all.

Where am I going wrong here?

Body:
You have to add the $request_uri to the proxy_pass to send the full URI to the second, mirrored backend. Just tested in my lab:

server {
  listen 9001;
  log_subrequest on;
  access_log /var/log/nginx/mirror.log upstream_time;
  location / {
    mirror /mirror;
    proxy_pass http://127.0.0.1:9002/;
  }

  location = /mirror {
    proxy_pass http://127.0.0.1:8000$request_uri;
 }
}

server {listen 9002; return 200 "Server 1\n";}

Make sure adding the internal directive to the mirror location.

As responses from the mirror will be ignored I am using an Python http.server to fake my backend and see the trace the incoming requests.

python3 -m http.server 8000

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [05/Feb/2022 22:00:45] code 404, message File not found
127.0.0.1 - - [05/Feb/2022 22:00:45] "GET /test/something HTTP/1.0" 404 -

The NGINX logs after submitting a simple curl
curl 127.0.0.1:9001/test/something

127.0.0.1 - - [05/Feb/2022:22:08:46 -0500] "GET /test/something HTTP/1.1" 404 156 "-" "curl/7.29.0" upa="127.0.0.1:8000/test/something" rt=0.003 uct="0.000" uht="0.003" urt="0.003"
127.0.0.1 - - [05/Feb/2022:22:08:46 -0500] "GET /test/something HTTP/1.1" 200 9 "-" "curl/7.29.0" upa="127.0.0.1:9002/test/something" rt=0.003 uct="0.000" uht="0.001" urt="0.001"

To have the correct URI in your log file, make sure you are adding $request_uri to your logformat. The $uri variable will change to /mirror.

Read more https://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri


问:
print outnum to the standard output stream sample input 5,10,6,8 sample output 4
Consider an array of non-zero positive integers inarr. Identify and print a number outnum based on the below logic:

· Across each of the possible ways in which integers in inarr can be sequentially arranged, identify the maximum absolute difference of adjacent values

o The last and the first integers are adjacent

· Print outnum, the minimum value across the maximum differences identified above

Input:

The first line represents the array inarr with its elements separated by ‘,’(comma)

Read the inputs from the standard input stream

Output:

Print outnum to the standard output stream

Sample Input    Sample Output   Explanation

5,10,6,8    4

For the given inarr, the maximum absolute difference of adjacent values for all the possible ways in which integers can be arranged is as below:

5,10,6,8:

5 - 10 =5  àabsolute maximum difference

10 - 6 = 4

6 - 8 =2

8 - 5 =3

Similarly, for other possible ways:

5,10,8,6 - absolute max diff = 5

5,6,8,10 - absolute max diff = 5

5,6,10,8 - absolute max diff = 4

5,8,6,10 - absolute max diff = 5

5,8,10,6 - absolute max diff = 4

10,5,6,8 - absolute max diff = 5

10,5,8,6 - absolute max diff = 5

10,6,5,8 - absolute max diff = 4

10,6,8,5 - absolute max diff = 5

10,8,6,5 - absolute max diff = 5

10,8,5,6 - absolute max diff = 4

6,5,10,8 - absolute max diff = 5

6,5,8,10 - absolute max diff = 4

6,8,5,10 - absolute max diff = 5

6,8,10,5 - absolute max diff = 5

6,10,5,8 - absolute max diff = 5

6,10,8,5 - absolute max diff = 4

8,5,6,10 - absolute max diff = 4

8,5,10,6 - absolute max diff = 5

8,6,5,10 - absolute max diff = 5

8,6,10,5 - absolute max diff = 5

8,10,5,6 - absolute max diff = 5

8,10,6,5 - absolute max diff = 4

The minimum value across the maximum differences is 4

答:
The following code should solve the problem.

maxAbsDiff() returns the maximum absolute difference of adjacent numbers for an array.

minMaxAbsDiff() iterates over all permutations of an array and returns the smallest maximum absolute difference.

```<code>import itertools

def maxAbsDiff(arr):
    max = 0
    for i in range(len(arr)-1):
        diff = abs(arr[i+1] - arr[i])
        if diff > max:
            max = diff
    diff = abs(arr[len(arr)-1] - arr[0])
    if diff > max:
        max = diff
    return max

def minMaxAbsDiff(arr):
    min = -1
    permutations = list(itertools.permutations(arr))
    for i in range(len(permutations)):
        diff = maxAbsDiff(permutations[i])
        if (min < 0) or (diff < min):
            min = diff
    return min

def input_intArr():
    str_in = input()
    str_arr = [x.strip() for x in str_in.split(",")]
    arr = []
    for i in range(len(str_arr)):
        arr.append(int(str_arr[i]))
    return arr

print(minMaxAbsDiff(input_intArr()))
</code>```

Body:
The following code should solve the problem.

maxAbsDiff() returns the maximum absolute difference of adjacent numbers for an array.

minMaxAbsDiff() iterates over all permutations of an array and returns the smallest maximum absolute difference.

import itertools

def maxAbsDiff(arr):
    max = 0
    for i in range(len(arr)-1):
        diff = abs(arr[i+1] - arr[i])
        if diff > max:
            max = diff
    diff = abs(arr[len(arr)-1] - arr[0])
    if diff > max:
        max = diff
    return max

def minMaxAbsDiff(arr):
    min = -1
    permutations = list(itertools.permutations(arr))
    for i in range(len(permutations)):
        diff = maxAbsDiff(permutations[i])
        if (min < 0) or (diff < min):
            min = diff
    return min

def input_intArr():
    str_in = input()
    str_arr = [x.strip() for x in str_in.split(",")]
    arr = []
    for i in range(len(str_arr)):
        arr.append(int(str_arr[i]))
    return arr

print(minMaxAbsDiff(input_intArr()))


问:
Foobar Test Case Failing on my solution on decrypting input
every lowercase letter [a..z] is replaced with the corresponding one in [z..a], while every other character (including uppercase letters and punctuation) is left untouched.  That is, 'a' becomes 'z', 'b' becomes 'y', 'c' becomes 'x', etc.  For instance, the word ""vmxibkgrlm"", when decoded, would become ""encryption"".

Write a function called solution(s) which takes in a string and returns the deciphered string so you can show the commander proof that these minions are talking about ""Lance & Janice"" instead of doing their jobs.

```<code>def solution(x):
    alph = "abcdefghijklmnopqrstuvwxyz"
    decryptDic = {}
    alph_len = (len(alph) -1)
    response =""
    for i in alph:
        decryptDic[i] = alph[alph_len]
        alph_len = alph_len-1
    for char in  x:
        if char == char.upper():
            response = f"{response}{char}"
        elif char not in decryptDic:
            response = response.join(char)
        else:
            response = f"{response}{(decryptDic.get(char))}"

    return response
</code>```

It is just saying test case failed

Test cases

Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.

-- Python cases --

Input:
solution.solution("wrw blf hvv ozhg mrtsg'h vkrhlwv?")

Output:
did you see last night's episode?

答:
Now that you have found your problem, I thought it may be worth giving you a slightly more pythonic version of your code:

```<code>def solution(x):
    alph = "abcdefghijklmnopqrstuvwxyz"
    response = ""

    decryptDic = {c : c_prime for c, c_prime in zip(alph, alph[::-1])}

    for char in  x:
        if char == char.upper() or char not in decryptDic:
            response += char
        else:
            response += (decryptDic.get(char))

    return response
</code>```

Explanation:

{c : c_prime for c, c_prime in zip(alph, alph[::-1])} is a dict comprehension where you can replace your loop with one line which is more readable. alph[::-1] reverses your string and zip "zips" together two iterables element wise.

The logic has only two options (add character to string or add translated character to string) so you can combine two of your statements into one. I think you could probably drop the if char == char.upper() too as your alph doesn't include any upper case letter too if you want.

x += s is a more compact way of writing x = x + s and is backward compatible with Python 2.7. f-strings are preferred when you need to insert variables into strings.

Body:
every lowercase letter [a..z] is replaced with the corresponding one in [z..a], while every other character (including uppercase letters and punctuation) is left untouched.  That is, 'a' becomes 'z', 'b' becomes 'y', 'c' becomes 'x', etc.  For instance, the word ""vmxibkgrlm"", when decoded, would become ""encryption"".

Write a function called solution(s) which takes in a string and returns the deciphered string so you can show the commander proof that these minions are talking about ""Lance & Janice"" instead of doing their jobs.

def solution(x):
    alph = "abcdefghijklmnopqrstuvwxyz"
    decryptDic = {}
    alph_len = (len(alph) -1)
    response =""
    for i in alph:
        decryptDic[i] = alph[alph_len]
        alph_len = alph_len-1
    for char in  x:
        if char == char.upper():
            response = f"{response}{char}"
        elif char not in decryptDic:
            response = response.join(char)
        else:
            response = f"{response}{(decryptDic.get(char))}"

    return response

It is just saying test case failed

Test cases

Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.

-- Python cases --

Input:
solution.solution("wrw blf hvv ozhg mrtsg'h vkrhlwv?")

Output:
did you see last night's episode?

Body:
Now that you have found your problem, I thought it may be worth giving you a slightly more pythonic version of your code:

def solution(x):
    alph = "abcdefghijklmnopqrstuvwxyz"
    response = ""

    decryptDic = {c : c_prime for c, c_prime in zip(alph, alph[::-1])}

    for char in  x:
        if char == char.upper() or char not in decryptDic:
            response += char
        else:
            response += (decryptDic.get(char))

    return response

Explanation:

{c : c_prime for c, c_prime in zip(alph, alph[::-1])} is a dict comprehension where you can replace your loop with one line which is more readable. alph[::-1] reverses your string and zip "zips" together two iterables element wise.

The logic has only two options (add character to string or add translated character to string) so you can combine two of your statements into one. I think you could probably drop the if char == char.upper() too as your alph doesn't include any upper case letter too if you want.

x += s is a more compact way of writing x = x + s and is backward compatible with Python 2.7. f-strings are preferred when you need to insert variables into strings.


问:
C++ DLL Not Receiving Passed Variables
I am trying to write a C++ DLL that will receive two long values, sum them, and then return the result. I'm doing this testing as a way to attempt to fix a 20+ year old C++ DLL that needs some fine-tuning to be 64-bit compliant and my skills in C++ are rusty at best. So I'm starting simple with basic math and I can't seem to get it to work. I'm calling the DLL from VBA but I don't think it's my VBA that's the issue.

C++ Header File

```<code>#pragma once

#define DLL_EXPORT _declspec (dllexport)

class __declspec(dllexport) CalculationApi
{
public:
    long Addition(long* value1, long* value2);
};
</code>```

C++ CPP File

```<code>#include "pch.h"
#include "Calculation.h"
#include "windows.h"
#include "string"
#include<iostream>

using namespace std;

long DLL_EXPORT __stdcall CalculationApi::Addition(long* value1, long* value2)
{
    long return_result;
    string MsgBoxMessage;

    string Integer1_Type = typeid(*value1).name();

    string test_integer_text = std::to_string(*value1);

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Value1 Data Type is: " + Integer1_Type;
    MessageBox(NULL, MsgBoxMessage.c_str(), "Data Type of Value1", MB_OK);

    MsgBoxMessage = "Value2 is: " + to_string(*value2);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value2", MB_OK);

    return_result = *value1 + *value2;

    *value1 = 50;

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Result is: " + to_string(return_result);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Math Results", MB_OK);

    return return_result;

}
</code>```

And just in case I messed up the VBA here's how I call the DLL

```<code>Private Declare PtrSafe Function Addition Lib "C:\Users\micha\source\repos\CalculationDll\x64\Debug\CalculationDll.dll" (value1 As LongPtr, value2 As LongPtr) As LongPtr

Function DLL_Testing()
    Dim value1 As LongPtr
    Dim value2 As LongPtr
    Dim Results As LongPtr

    value1 = 10
    value2 = 20

    Results = Addition(integer1, integer2)

    test = 0

End Function
</code>```

The first messagebox in the C++ comes up blank... I'm sure I'm just not doing something right there but meh doesn't matter much. The second messagebox returns either 0 or some really funky number.  The VBA will return the result "583141696^" which of course is not 10+20.  Also the value1 doesn't get updated to 50, I'm pretty sure I'm not passing the pointer correctly as I've seen value2 update when I changed the value of value1 in the DLL.

This all seems REALLY basic yet it doesn't work. Thoughts?

答:
Well the suggestion to convert this to C instead of C++ paid off (after finding a dumb error of my own). Changes I made...

Class gone

Converted to C

I couldn't get the "static" suggestion to work but the code in C works fine without it. Not sure what's up there but I'm going to go with it.

Title: C++ DLL Not Receiving Passed Variables

Body:
I am trying to write a C++ DLL that will receive two long values, sum them, and then return the result. I'm doing this testing as a way to attempt to fix a 20+ year old C++ DLL that needs some fine-tuning to be 64-bit compliant and my skills in C++ are rusty at best. So I'm starting simple with basic math and I can't seem to get it to work. I'm calling the DLL from VBA but I don't think it's my VBA that's the issue.

C++ Header File

#pragma once

#define DLL_EXPORT _declspec (dllexport)

class __declspec(dllexport) CalculationApi
{
public:
    long Addition(long* value1, long* value2);
};

C++ CPP File

#include "pch.h"
#include "Calculation.h"
#include "windows.h"
#include "string"
#include<iostream>

using namespace std;

long DLL_EXPORT __stdcall CalculationApi::Addition(long* value1, long* value2)
{
    long return_result;
    string MsgBoxMessage;

    string Integer1_Type = typeid(*value1).name();

    string test_integer_text = std::to_string(*value1);

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Value1 Data Type is: " + Integer1_Type;
    MessageBox(NULL, MsgBoxMessage.c_str(), "Data Type of Value1", MB_OK);

    MsgBoxMessage = "Value2 is: " + to_string(*value2);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value2", MB_OK);

    return_result = *value1 + *value2;

    *value1 = 50;

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Result is: " + to_string(return_result);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Math Results", MB_OK);

    return return_result;

}

And just in case I messed up the VBA here's how I call the DLL

Private Declare PtrSafe Function Addition Lib "C:\Users\micha\source\repos\CalculationDll\x64\Debug\CalculationDll.dll" (value1 As LongPtr, value2 As LongPtr) As LongPtr

Function DLL_Testing()
    Dim value1 As LongPtr
    Dim value2 As LongPtr
    Dim Results As LongPtr

    value1 = 10
    value2 = 20

    Results = Addition(integer1, integer2)

    test = 0

End Function

The first messagebox in the C++ comes up blank... I'm sure I'm just not doing something right there but meh doesn't matter much. The second messagebox returns either 0 or some really funky number.  The VBA will return the result "583141696^" which of course is not 10+20.  Also the value1 doesn't get updated to 50, I'm pretty sure I'm not passing the pointer correctly as I've seen value2 update when I changed the value of value1 in the DLL.

This all seems REALLY basic yet it doesn't work. Thoughts?


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
"I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to"

In that case you meant Dict *const dict, not const Dict *dict. You've declared the struct as const, not the pointer to it.

"Why do I also need to have const for currPtr"

Because otherwise you could use currPtr to modify the dictionary struct itself, which is supposed to be const in this function.

"The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr"

Same reason: it's not an error if the const is in the place you put it. It would be if the const were in the other place for currPtr.

otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too

No - when the main program calls get, it passes a pointer value into the routine, and this becomes the value of dict in the get function. But get has its own pointer variable, separate from the one in the main program. Even if they just so happen to both be called "dict", changing one pointer won't change the other.

Both variables point to the same struct, so if you use the variable to modify any of the fields in the struct, then of course the results will affect both bits of code. Usually, a function called "get" would be a read-only operation, so you're right to make the parameter const Dict *. But I think the reason this is right, is slightly different from what you think. It's to protect the contents of the dictionary from change, not to protect your record of the address of it.

However, const-safety is slightly awkward for linked lists like this one. Even when you have a const Dict, its "next" field still doesn't point to const. So although you can't modify the first node, the const-system won't protect you from modifying other nodes in the list. C++ addresses this with function overloading, so you can have a "getnext" function which returns a const output if the input is const, but a non-const output if the input is non-const. You could achieve a similar thing in C with a "getnext" and "getnext_c", the latter having a const parameter and return. But most people don't bother, including standard library functions like strchr, which in C takes const char* but returns non-const char*. strchr can therefore be accidentally used in C to convert a const string into a non-const one, without any warning. Or deliberately, in which case it's a bit like laundering money through a "legit" business ;-)

the del() function does not require me to add a const before currPtr and prevPtr?

I confess I'm stumped on that. I would expect the same warning as in "get" - are you sure it isn't there? But the parameter to del shouldn't be const anyway, because you're potentially modifying the fields.

OwnerDisplayName: Nazgulled

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?


问:
sybase format results to 4 decimal places
In sybase, how do you format the result from a select statement for a numeric field, to have no commas and 4 decimal digits.

For Example:

344,500.39495     =    344500.3949

492,930,948.39    = 492930948.3900

答:
You can convert and format a number or a float to string with the str() function.
The second parameter is the total length of the number, including the decimal point, and the third parameter is the length after decimal point.

```<code>str(yourDecimalNumber, 20, 4)
</code>```

Body:
You can convert and format a number or a float to string with the str() function.
The second parameter is the total length of the number, including the decimal point, and the third parameter is the length after decimal point.

str(yourDecimalNumber, 20, 4)


问:
C# How to instantiate new object with Dependency Injection
I have a class that is using Logger:

```<code>internal class Class1
{
    private readonly ILogger<Class1> _logger;
    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }
    internal void Method1()
    {
        //some code
    }
}
</code>```

When I try using it, the compiler correctly tells me that there is no constructor that matches this signature:

```<code>Class1 cl1 = new Class1();
</code>```

I want to use default constructor.  If I understand this correctly, Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class.  How do I do that??  Thank you for your help.

答:
you have to DI  to the program code if you are using net 6 (or startup if you don't use program)

```<code>.....

builder.Services.AddScoped(typeof(Class1));

var app = builder.Build();
....

</code>```

if youi try to use this way

```<code>Class1 cl1 = new Class1();
</code>```

you will have to have parameterless construtor

```<code>internal Class1()
{
        _logger = ... tons of code to create a logger instance
}
</code>```

or may be (I don't know where are you creating the instance  of class)

```<code>var logger= .. tons of code to create a logger instance
var cl1 = new Class1(logger);
</code>```

Body:
I have a class that is using Logger:

internal class Class1
{
    private readonly ILogger<Class1> _logger;
    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }
    internal void Method1()
    {
        //some code
    }
}

When I try using it, the compiler correctly tells me that there is no constructor that matches this signature:

Class1 cl1 = new Class1();

I want to use default constructor.  If I understand this correctly, Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class.  How do I do that??  Thank you for your help.

Body:
you have to DI  to the program code if you are using net 6 (or startup if you don't use program)

.....

builder.Services.AddScoped(typeof(Class1));

var app = builder.Build();
....

if youi try to use this way

Class1 cl1 = new Class1();

you will have to have parameterless construtor

internal Class1()
{
        _logger = ... tons of code to create a logger instance
}

or may be (I don't know where are you creating the instance  of class)

var logger= .. tons of code to create a logger instance
var cl1 = new Class1(logger);


问:
Arbitrary length integer in Ada
I am currently teaching myself Ada and though I could begin by tackling some of the more conventional problems to get started.

More specifically I try to calculate the factorial n!, whereas n>100. My implementation so far is:

```<code>with Ada.Text_IO;
with Ada.Integer_Text_IO;

use Ada.Text_IO;

procedure Factorial is
    -- define a type covering the range beginning at 1 up to which faculty is to
    -- be computed.
    subtype Argument is Long_Long_Integer range 1..100;

    -- define a type that is large enough to hold the result
    subtype Result is Long_Long_Integer range 1..Long_Long_Integer'Last;
    package Result_IO is new Ada.Text_IO.Integer_IO(Result); use Result_IO;

    -- variable holding the faculty calculated.
    fac : Result := 1;

begin
    -- loop over whole range of ARGUMENT and calculate n!
    for n in ARGUMENT loop
        fac := (fac * n);
    end loop;
end;
</code>```

The problem is obviously that even Long_Long_Integer is may too small for this and throws a CONTRAINT_ERROR exception for n>20.

Is there a package that implements arbitrary-sized integers?

Thanks!

PS: I did opt against recursion because I wanted to explore loops in this exercise. But otherwise please comment on all aspects of the code (style, best-practices, error..)

答:
In the upcoming version of Ada 202X, support for arbitrary integer handling using GNAT is included in the library package Numerics.Big_Numbers.Big_Integers.

More information in the ARM:

http://www.ada-auth.org/standards/2xrm/html/RM-A-5-6.html

Title: Arbitrary length integer in Ada

Body:
I am currently teaching myself Ada and though I could begin by tackling some of the more conventional problems to get started.

More specifically I try to calculate the factorial n!, whereas n>100. My implementation so far is:

with Ada.Text_IO;
with Ada.Integer_Text_IO;

use Ada.Text_IO;

procedure Factorial is
    -- define a type covering the range beginning at 1 up to which faculty is to
    -- be computed.
    subtype Argument is Long_Long_Integer range 1..100;

    -- define a type that is large enough to hold the result
    subtype Result is Long_Long_Integer range 1..Long_Long_Integer'Last;
    package Result_IO is new Ada.Text_IO.Integer_IO(Result); use Result_IO;

    -- variable holding the faculty calculated.
    fac : Result := 1;

begin
    -- loop over whole range of ARGUMENT and calculate n!
    for n in ARGUMENT loop
        fac := (fac * n);
    end loop;
end;

The problem is obviously that even Long_Long_Integer is may too small for this and throws a CONTRAINT_ERROR exception for n>20.

Is there a package that implements arbitrary-sized integers?

Thanks!

PS: I did opt against recursion because I wanted to explore loops in this exercise. But otherwise please comment on all aspects of the code (style, best-practices, error..)


问:
aws cloudformation wordpress updates
I have a wordpress app that I need to install to aws with a cloudformation template, I initially created it using some sample template from AWS cloudformation, but when AWS rebuilds the system some changes are lost,

in particular I need to set the httpd.conf file so that:

```<code><Directory "/var/www">
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
</code>```

and everytime aws rebuilds (they do it a few times a week) I lose this.

also I need to add a few environment variables to the elasticbeanstalk instance so that other changes will be picked up as well.

I currently have a few env variables like:

RDS_DB_NAME, RDS_HOSTNAME, RDS_PASSWORD, RDS_PORT, RDS_USERNAME

I'm not sure where they are configured in the cloudformation template, I think I remember adding them manually to the elasticbean instance configuration. I now need to add a bunch to these, like:

```<code>AUTH_KEY
SECURE_AUTH_KEY
LOGGED_IN_KEY
NONCE_KEY
AUTH_SALT
SECURE_AUTH_SALT
LOGGED_IN_SALT
NONCE_SALT
</code>```

I'm not sure how to get around to do that.

I also need to configure the cloudformation so that my wordpress has also an SSL certificate (which I have available as arn) and is accessible via https.

I think if I add it to the autoscaling configuration, then updating the stack will just recreate the autoscaling resource and reinstall the vanilla version of wordpress,

I have wordpress in an application on elasticbean stalk, I'm not sure in this case how to make it install the latest version, instead of the vanilla one.

here's my entire cloudformation yaml template: https://justpaste.it/481a7

答: For me it was easier to create only the instance in an auto scaling group with CloudFormation and deploy the wordpress itself via CodeDeploy for example from a git repository or just folder/zip file. Then you can have there also the httpd.conf an you copy it to its location when CodeDeploy runs. Does not solve media content, but there is a wordpress plugin which stores media in s3. Or you can back it up on regular bases and sync up with the CodeDeploy script. Or EFS. There are many options.  Doing it only via instance UserData is tricky and hard to debug.</p>

Title: aws cloudformation wordpress updates

Body:
I have a wordpress app that I need to install to aws with a cloudformation template, I initially created it using some sample template from AWS cloudformation, but when AWS rebuilds the system some changes are lost,

in particular I need to set the httpd.conf file so that:

<Directory "/var/www">
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

and everytime aws rebuilds (they do it a few times a week) I lose this.

also I need to add a few environment variables to the elasticbeanstalk instance so that other changes will be picked up as well.

I currently have a few env variables like:

RDS_DB_NAME, RDS_HOSTNAME, RDS_PASSWORD, RDS_PORT, RDS_USERNAME

I'm not sure where they are configured in the cloudformation template, I think I remember adding them manually to the elasticbean instance configuration. I now need to add a bunch to these, like:

AUTH_KEY
SECURE_AUTH_KEY
LOGGED_IN_KEY
NONCE_KEY
AUTH_SALT
SECURE_AUTH_SALT
LOGGED_IN_SALT
NONCE_SALT

I'm not sure how to get around to do that.

I also need to configure the cloudformation so that my wordpress has also an SSL certificate (which I have available as arn) and is accessible via https.

I think if I add it to the autoscaling configuration, then updating the stack will just recreate the autoscaling resource and reinstall the vanilla version of wordpress,

I have wordpress in an application on elasticbean stalk, I'm not sure in this case how to make it install the latest version, instead of the vanilla one.

here's my entire cloudformation yaml template: https://justpaste.it/481a7


问:
Code can't reverse the string. It prins empty
```<code>#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}
</code>```

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

```<code>Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;
</code>```

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

```<code>f[i] = x[y-(1+i)];
f[y] = '\0';
</code>```

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

答:
Try this out

Simply loop through the string the user provide and start taking the character from the last index value minus one(-1) to the first index value and append it to the variable f

For Example

```<code>
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "digite algo\n";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = y-1; i>=0; i--){

    f+= x.at(i);

    }

    cout << f << endl;
    return 0;

}

</code>```

Body:
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

f[i] = x[y-(1+i)];
f[y] = '\0';

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

Body:
Try this out

Simply loop through the string the user provide and start taking the character from the last index value minus one(-1) to the first index value and append it to the variable f

For Example

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "digite algo\n";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = y-1; i>=0; i--){

    f+= x.at(i);

    }

    cout << f << endl;
    return 0;

}


问:
Inconsistent print with value from for statement (python)
So I’ve created a very basic program that rolls a dice a given number of times, and then displays who wins the game.
I’ve tried to print the results as they go along with the roll #.

The problem I’m having is the output seems weirdly, an indecipherably (at least to my eyes) inconsistent (ie: sometimes it will show the roll #, sometimes it won’t.

Besides how much cleaner I could make this code, what am I doing that’s producing inconsistent roll # printing?

Code as follows:

```<code>import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    ones = 0
    twos = 0
    threes = 0
    fours = 0
    fives = 0
    sixes = 0
    tries = 1

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        if ran_num == 1:
            print(f"Roll {tries}: One for the ones")
            ones += 1
        elif ran_num == 2:
            print("Roll {tries}: Two Two look at my shoe")
            twos += 1
        elif ran_num == 3:
            print("Roll {tries}: THREE!! I'm free'")
            threes += 1
        elif ran_num == 4:
            print("Roll {tries}: F0ar equals m0ar")
            fours += 1
        elif ran_num == 5:
            print("Roll {tries}: Five five don't step in a bee hive'")
            fives += 1
        elif ran_num == 6:
            print("Roll {tries}: Super Sixes - Yeharrrr!")
            sixes += 1
    rolls += 1
    tries += 1
    print(f"Final scores are: \n1: {ones}\n2: {twos}\n3: {threes}\n4: {fours}\n5: {fives}\n6: {sixes}")

HighRolla()’’’
</code>```

答:
The problem is that you don't use f-Strings correctly. If you want your variables to be replaced inside curly brackets you need to put an "f" in front of your string.

You could also use a dictionary or an array to make your code clearer and more readable, like so:

```<code>import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    roll_counts = [0] * 6 # Creates an array of 6 zeroes
    roll_messages = [
        "One for the ones",
        "Two Two look at my shoe",
        "THREE!! I'm free'",
        "F0ar equals m0ar",
        "Five five don't step in a bee hive'",
        "Super Sixes - Yeharrrr!"
    ]

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        roll_counts[ran_num-1] += 1
        print(f"Roll {roll}: {roll_messages[ran_num-1]}")

    print(f"Final scores are:")
    print("\n".join([f"{idx+1}: {roll_count}" for idx, roll_count in enumerate(roll_counts)]))

HighRolla()
</code>```

Body:
So I’ve created a very basic program that rolls a dice a given number of times, and then displays who wins the game.
I’ve tried to print the results as they go along with the roll #.

The problem I’m having is the output seems weirdly, an indecipherably (at least to my eyes) inconsistent (ie: sometimes it will show the roll #, sometimes it won’t.

Besides how much cleaner I could make this code, what am I doing that’s producing inconsistent roll # printing?

Code as follows:

import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    ones = 0
    twos = 0
    threes = 0
    fours = 0
    fives = 0
    sixes = 0
    tries = 1

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        if ran_num == 1:
            print(f"Roll {tries}: One for the ones")
            ones += 1
        elif ran_num == 2:
            print("Roll {tries}: Two Two look at my shoe")
            twos += 1
        elif ran_num == 3:
            print("Roll {tries}: THREE!! I'm free'")
            threes += 1
        elif ran_num == 4:
            print("Roll {tries}: F0ar equals m0ar")
            fours += 1
        elif ran_num == 5:
            print("Roll {tries}: Five five don't step in a bee hive'")
            fives += 1
        elif ran_num == 6:
            print("Roll {tries}: Super Sixes - Yeharrrr!")
            sixes += 1
    rolls += 1
    tries += 1
    print(f"Final scores are: \n1: {ones}\n2: {twos}\n3: {threes}\n4: {fours}\n5: {fives}\n6: {sixes}")

HighRolla()’’’

Body:
The problem is that you don't use f-Strings correctly. If you want your variables to be replaced inside curly brackets you need to put an "f" in front of your string.

You could also use a dictionary or an array to make your code clearer and more readable, like so:

import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    roll_counts = [0] * 6 # Creates an array of 6 zeroes
    roll_messages = [
        "One for the ones",
        "Two Two look at my shoe",
        "THREE!! I'm free'",
        "F0ar equals m0ar",
        "Five five don't step in a bee hive'",
        "Super Sixes - Yeharrrr!"
    ]

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        roll_counts[ran_num-1] += 1
        print(f"Roll {roll}: {roll_messages[ran_num-1]}")

    print(f"Final scores are:")
    print("\n".join([f"{idx+1}: {roll_count}" for idx, roll_count in enumerate(roll_counts)]))

HighRolla()


问:
marginRight property of imageview not working
I have an image view whose background is a xml shape  drawable i.e. a rectangle shape drawable.My app's orientation   is fixed to landscape view.

The imageview is in relative layout.

I  am trying to move it to  the right of the screen by setting the appropriate value of layout_marginRight but this does not work .The imageView always stays in its's original position.

I have tried the following other options also but none helped.

The other options which I tried are:

Creating a new relative layout params and  setting the right margin

Creating new margin layout params and setting the position

Trying padding option

Setting the imageview to  right position relative to another imageview...

Using display metrics to get width of screen and accordingly setting the margin....

I am stuck since a week setting the position of this imageview...

I was thinking the best approach is to  set this imageview in between two imageview as I am not able to move it by setting margin but that does not work either...

Here is the current xml of my imageview in main.xml:-

```<code><ImageView
            android:id="@+id/rect1"
            android:background="@drawable/rect"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginRight="70dp"
            android:scaleType="fitCenter"/>
</code>```

答: I don't see why adding a margin to the right of the image would help move the image to the right, it just extends the right side bounds of the imageview by the margin. As long as the imageview isn't actually on the right side of the parentview, it would be allowed to grow without changing position. I suggest using layout_alignParentRight="true" on the imageview if you want it on the right of your relativelayout, and then you can use the marginRight to control how far off the right side you want it.

Body:
I have an image view whose background is a xml shape  drawable i.e. a rectangle shape drawable.My app's orientation   is fixed to landscape view.

The imageview is in relative layout.

I  am trying to move it to  the right of the screen by setting the appropriate value of layout_marginRight but this does not work .The imageView always stays in its's original position.

I have tried the following other options also but none helped.

The other options which I tried are:

Creating a new relative layout params and  setting the right margin

Creating new margin layout params and setting the position

Trying padding option

Setting the imageview to  right position relative to another imageview...

Using display metrics to get width of screen and accordingly setting the margin....

I am stuck since a week setting the position of this imageview...

I was thinking the best approach is to  set this imageview in between two imageview as I am not able to move it by setting margin but that does not work either...

Here is the current xml of my imageview in main.xml:-

<ImageView
            android:id="@+id/rect1"
            android:background="@drawable/rect"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginRight="70dp"
            android:scaleType="fitCenter"/>


问:
Changing text size of go Treemap for text inside sectors
I have been looking to increase to the size of the text contained in a graph object Treemap, but with no success. I tried inserting HTML line breaks in the actual text but that didn't work. Maybe I am missing a simple solution. The docs have textinfo, textposition but not text size. Here is what it currently looks like: I just want the text to be readable.

enter image description here

Thank for you help!

EDIT: Here is my current code:

```<code>fig = go.Figure(go.Treemap(
ids=df_treemap['id'].tolist(),
labels=df_treemap['labels'].tolist(),
parents=df_treemap['parent'].tolist(),
values=df_treemap['value'].tolist(),
branchvalues='total',
hovertemplate='<b>%{label}',
insidetextfont=dict(size=11),
textfont=dict(size=30),
marker=dict(
    colors=df_treemap['color'],
    colorscale='RdBu',
    cmid=1,
    showscale=True),
name='',
text=summaries,
</code>```

I have tried cutting the text up with the following, but that does help:
short_summaries = [textwrap.fill(df['Summary'].tolist()[0],10) if
isinstance(df, pd.DataFrame) else 'N.A' for df in x]

答:
Extracted from the official docs:

textfont – Sets the font used for textinfo.

And it has a size property.

Body:
I have been looking to increase to the size of the text contained in a graph object Treemap, but with no success. I tried inserting HTML line breaks in the actual text but that didn't work. Maybe I am missing a simple solution. The docs have textinfo, textposition but not text size. Here is what it currently looks like: I just want the text to be readable.

enter image description here

Thank for you help!

EDIT: Here is my current code:

fig = go.Figure(go.Treemap(
ids=df_treemap['id'].tolist(),
labels=df_treemap['labels'].tolist(),
parents=df_treemap['parent'].tolist(),
values=df_treemap['value'].tolist(),
branchvalues='total',
hovertemplate='%{label}',
insidetextfont=dict(size=11),
textfont=dict(size=30),
marker=dict(
    colors=df_treemap['color'],
    colorscale='RdBu',
    cmid=1,
    showscale=True),
name='',
text=summaries,

I have tried cutting the text up with the following, but that does help:
short_summaries = [textwrap.fill(df['Summary'].tolist()[0],10) if
isinstance(df, pd.DataFrame) else 'N.A' for df in x]


问:
Difficulty using boost::regex_match to get separate matches for "NASIONAL" and "12" from string "NASIONAL12"
This works fine in all online regex testers but fails to produce any matches in boost::regex_match, which I unfortunately must use as is because it is being used in a system that expects this format for more complicated parsings of street names.

```<code>std::string rformat = "(([a-zA-Z]*)|([0-9]*))?";
std::string source = "NASIONAL12";
const boost::regex piecesRegex(rformat);
boost::smatch      piecesMatch;
if (boost::regex_match(source, piecesMatch, piecesRegex))
{
   for (auto match : piecesMatch) {
       std::cerr << "MATCH:" << match << std::endl;
   }
}
</code>```

What I need is for the first "piecesMatch" to return "NASIONAL" and the second "piecesMatch" to return "12"

答:
Thanks to everyone's help I found the right regex string:</p>
```<code>([a-zA-Z]*)?([0-9]*)?
</code>```

Body:
This works fine in all online regex testers but fails to produce any matches in boost::regex_match, which I unfortunately must use as is because it is being used in a system that expects this format for more complicated parsings of street names.

std::string rformat = "(([a-zA-Z]*)|([0-9]*))?";
std::string source = "NASIONAL12";
const boost::regex piecesRegex(rformat);
boost::smatch      piecesMatch;
if (boost::regex_match(source, piecesMatch, piecesRegex))
{
   for (auto match : piecesMatch) {
       std::cerr << "MATCH:" << match << std::endl;
   }
}

What I need is for the first "piecesMatch" to return "NASIONAL" and the second "piecesMatch" to return "12"

Body:
Thanks to everyone's help I found the right regex string:

([a-zA-Z]*)?([0-9]*)?


问:
Cannot find table elements to scrape pricing using BeautifulSoup
I'm trying to scrape all the pricing tables in the GCP site (https://cloud.google.com/compute/vm-instance-pricing) for every region. I have tried a combination of BeautifulSoup and Selenium but finding the  tags always comes up blank. Have read similar questions but solutions end up with the same result. There must be something obvious I'm missing but can't put my finger on it. Appreciate any help.</p>
```<code>import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd

url = 'https://cloud.google.com/compute/vm-instance-pricing'
driver=webdriver.Chrome(executable_path='C:/Users/pinzonpi/Downloads/chromedriver_win32/chromedriver.exe')
driver.get(url)

soup = BeautifulSoup(driver.page_source, 'lxml')
tables = soup.find_all('table')
</code>```

答:
Each table on that page is inside a separate iframe.

Browsers load the iframe content in a separate request. You'll have to do the same.

First you will have to get all the iframes list and then to scrape tables inside each iframe.

Something like this:

iframes = soup.find_all('iframe')
for iframe in iframes:
    response = urllib2.urlopen(iframe.attrs['src'])
    iframe_soup = BeautifulSoup(response)
    table = soup.find('table')
    #continue scraping this table content
```

Body:
I'm trying to scrape all the pricing tables in the GCP site (https://cloud.google.com/compute/vm-instance-pricing) for every region. I have tried a combination of BeautifulSoup and Selenium but finding the  tags always comes up blank. Have read similar questions but solutions end up with the same result. There must be something obvious I'm missing but can't put my finger on it. Appreciate any help.

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd

url = 'https://cloud.google.com/compute/vm-instance-pricing'
driver=webdriver.Chrome(executable_path='C:/Users/pinzonpi/Downloads/chromedriver_win32/chromedriver.exe')
driver.get(url)

soup = BeautifulSoup(driver.page_source, 'lxml')
tables = soup.find_all('table')


问:
Convert Integers to Dollar Format in Oracle Database
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

```<code>SELECT value AS "Valuation" FROM estimates;
</code>```

Result:

Instead, I would like to show:

```<code>$115,508
$38,150
$92,832
$116,222
</code>```

How can I convert the integers into dollar $ format?

答:
Use the TO_CHAR function:

```<code>TO_CHAR(SOME_NUMBER, '$999,999,999,999,999')
</code>```

db<>fiddle here

Body:
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

SELECT value AS "Valuation" FROM estimates;

Result:

Instead, I would like to show:

$115,508
$38,150
$92,832
$116,222

How can I convert the integers into dollar $ format?

Body:
Use the TO_CHAR function:

TO_CHAR(SOME_NUMBER, '$999,999,999,999,999')

db<>fiddle here


问:
How to fix Android ADB push error: Directory not empty
I am trying to put a .so file in /system/lib folder of emulator by using
$ adb push /home/username/Development/newdroid/filename.so /system/lib

but it gives me
error: failed to copy '/home/sudhir/Development/newdroid/libnfc_ndef.so' to '/system/lib/libnfc_ndef.so': Directory not empty

How do I fix this error?

答:
try this command

mount -o rw,remount /dev/block/mtdblock3 /system