问:
For loop assign a variable name for each loop iteration
This is a part of a code I've been working on, during the for loop it iterates through product_buttons in order to define which button is selected, and after a button is selected I wanted to show which button was selected and I have managed to do it as follows:

product_buttons = [36,38,40] #raspberry pi pins

```<code>in_progress = False
ended = True
product = None

def show_msg(wid,msg):
    wid.config(text = msg)
    pass

def button_loop():
    global in_progress,ended
    waiting = False
    product = None
    while True:
        for i in range(len(product_buttons)):
            button = IO.input(product_buttons[i])
            if button:
                print(i,in_progress,ended,product)
                if not in_progress:
                    product = i
                    while not ended:
                        time.sleep(0.1)
                    in_progress = True
                    show_msg(root.lab_quality,'Button {}
</code>```

pressed'.format(i))

The code works fine and whenever a button is pressed it changes Button {} pressed with Button 0 pressed, Button 1 pressed or Button 2 pressed.
Now what I was trying to do was to assign a variable name to each iteration in the for loop in order to achieve something like:

i = 0 make i = to a variable for example let's call it a
i = 1 make i = to b
i = 2 make i = to c

So that (still for example) when button 0 is pressed it shows Button a is pressed.
I have tried to store the values like this quality={1:a, 2:b, 3:c} and then call it with show_msg(root.lab_quality,'Button {} pressed'.format(quality)), this was the idea I had in mind but didn't work out and I am a bit stuck and I need to be pointed in the right direction so that I can eventually work it out.

Any help will be greatly appreciated!

答:
You need to define quality as a dictionary like this: quality={'1':'a', '2':'b', '3':'c'}. Then, you can call show_msg function:

```<code>show_msg(root.lab_quality,'Button {} pressed'.format(quality[str(i)]))
</code>```

This way you use the value of i variable as the key to read its name from the quality dictionary.

Body:
This is a part of a code I've been working on, during the for loop it iterates through product_buttons in order to define which button is selected, and after a button is selected I wanted to show which button was selected and I have managed to do it as follows:

product_buttons = [36,38,40] #raspberry pi pins

in_progress = False
ended = True
product = None

def show_msg(wid,msg):
    wid.config(text = msg)
    pass

def button_loop():
    global in_progress,ended
    waiting = False
    product = None
    while True:
        for i in range(len(product_buttons)):
            button = IO.input(product_buttons[i])
            if button:
                print(i,in_progress,ended,product)
                if not in_progress:
                    product = i
                    while not ended:
                        time.sleep(0.1)
                    in_progress = True
                    show_msg(root.lab_quality,'Button {}

pressed'.format(i))

The code works fine and whenever a button is pressed it changes Button {} pressed with Button 0 pressed, Button 1 pressed or Button 2 pressed.
Now what I was trying to do was to assign a variable name to each iteration in the for loop in order to achieve something like:

i = 0 make i = to a variable for example let's call it a
i = 1 make i = to b
i = 2 make i = to c

So that (still for example) when button 0 is pressed it shows Button a is pressed.
I have tried to store the values like this quality={1:a, 2:b, 3:c} and then call it with show_msg(root.lab_quality,'Button {} pressed'.format(quality)), this was the idea I had in mind but didn't work out and I am a bit stuck and I need to be pointed in the right direction so that I can eventually work it out.

Any help will be greatly appreciated!

Body:
You need to define quality as a dictionary like this: quality={'1':'a', '2':'b', '3':'c'}. Then, you can call show_msg function:

show_msg(root.lab_quality,'Button {} pressed'.format(quality[str(i)]))

This way you use the value of i variable as the key to read its name from the quality dictionary.


来源: stackexchange

问:
TypeError: Cannot read property 'db' of null
I am having issue connecting to mongodb atlas, getting the error below

```<code>let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db

let connectionString = 'mongodb+srv://olumide:xxxxxxxx@cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
    db = client.db()
    app.listen(3000)
})

app.use(express.urlencoded({extended: false}))

app.post('/create-item', function(req,res){
   db.collection('item').insertOne({text: req.body.item}, function(){
    res.send("thanks for submitting the form")
   })

})
</code>```

Error message

答:
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:

```<code>const {MongoClient} = require('mongodb')

const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')

async function start(){
  await client.connect()
  console.log("Connected")
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
}

  start()
</code>```

and while calling it from another file:

```<code>const productCollection = require('./db').collection("product");
</code>```

This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.

ContentLicense: CC BY-SA 4.0

Body:
I am having issue connecting to mongodb atlas, getting the error below

let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db

let connectionString = 'mongodb+srv://olumide:xxxxxxxx@cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
    db = client.db()
    app.listen(3000)
})

app.use(express.urlencoded({extended: false}))

app.post('/create-item', function(req,res){
   db.collection('item').insertOne({text: req.body.item}, function(){
    res.send("thanks for submitting the form")
   })

})

Error message

Body:
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:

const {MongoClient} = require('mongodb')

const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')

async function start(){
  await client.connect()
  console.log("Connected")
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
}

  start()

and while calling it from another file:

const productCollection = require('./db').collection("product");

This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.


问:
Pass Single Instance of Model to Multiple View Models in same Module for different views
I am working on a project using PRISM where I have left navigation implemented as Tree View and any click event happens raise event using event aggergation to Enrolment Module which has multiple view model for multiple views (like Wizard Applicaiton where you can go through many views to collect data). I want to have a common or shared or singleton model which can be passed across this view models and save at the end.... users can click on any link any navigation at any time and it should save data in to this singleton model expsosed through different view model. Do you have any samples which are doing something like this... or can you type up a quick one on how to do it? OR it is not possible to do it at all. I am following all patterns from Brian Lagunas's Pluralsight Video for PRISM so try to use that way....</p>

答:
I don't know, is it prism way, or something another, when I build something like wizard, first of all I create instance of all data which wizard collect.

```<code>public WizardData wd = new WizardData();
</code>```

Then, every page of wizard are initialized by this wd instance, i.e.

```<code>public FirstWizardPage(WizardData wd)
{
    this.wizardData = wd;
}
</code>```

So, this way allow you to have button Finish on every page, for example. You can initialize your ViewModel with wd, or its properties.

This way is not the best. Its hust one of the possible way.

Another - is to create singleton and use it without reference passing from page-to-page.

ContentLicense: CC BY-SA 3.0

Body:
I don't know, is it prism way, or something another, when I build something like wizard, first of all I create instance of all data which wizard collect.

public WizardData wd = new WizardData();

Then, every page of wizard are initialized by this wd instance, i.e.

public FirstWizardPage(WizardData wd)
{
    this.wizardData = wd;
}

So, this way allow you to have button Finish on every page, for example. You can initialize your ViewModel with wd, or its properties.

This way is not the best. Its hust one of the possible way.

Another - is to create singleton and use it without reference passing from page-to-page.


问:
How are two different appservices identified
How are two appservices in the same appservice plan uniquely identified though I understand they have different urls but it is explained that at the backend this urls are converted into IP addresses however the appservices have the same Outbound IP addresses</p>

答:
Yes the inbound and outbound IP addresses has little to do with the selection of app services running on ASP's, the outbound IP can even be totally different than the ASP addresses if you are using a NAT GateWay or other services.

If you want a more specific answer please ask a more specific question as in what problem are you trying to resolve?


问:
Why auto delete index policy doesn't work in elasticsearch?
I created a index policy in Kibana to delete index order than 7 days. Below is the configuration:

And I have indexes who are using this policy but none of them get deleted. Below is one of the index setting configuration. It has already specified the policy to use: metrics-log-retention. Is there anything I missed?

{
  "aws-logs-2022-02-01" : {
    "settings" : {
      "index" : {
        "lifecycle" : {
          "name" : "metrics-log-retention"
        },
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "aws-logs-2022-02-01",
        "creation_date" : "1643673636747",
        "priority" : "100",
        "number_of_replicas" : "1",
        "uuid" : "lLmO753nRpuw6bauKIJI2Q",
        "version" : {
          "created" : "7150299"
        }
      }
    }
  }
}

```
<p>Below is the hot phase. I have disabled all options under hot as shown in below screenshot. but it still doesn't work.</p>
<p><img src="https://i.stack.imgur.com/vqIfM.png" alt="enter image description here" /></p>
<p>Below is the raw data for the index policy:</p>
<pre class="lang-json prettyprint-override"><code>{
  "metrics-log-retention" : {
    "version" : 4,
    "modified_date" : "2022-02-10T22:24:14.492Z",
    "policy" : {
      "phases" : {
        "hot" : {
          "min_age" : "0ms",
          "actions" : {
            "rollover" : {
              "max_size" : "50gb",
              "max_primary_shard_size" : "50gb",
              "max_age" : "1d"
            }
          }
        },
        "delete" : {
          "min_age" : "6d",
          "actions" : {
            "delete" : {
              "delete_searchable_snapshot" : true
            }
          }
        }
      }
    },
    "in_use_by" : {
      "indices" : [
        "aws-logs-2022-02-01",
        "aws-logs-2022-02-04",
        "aws-logs-2022-02-05",
        "aws-logs-2022-02-02",
        "aws-logs-2022-02-03",
        "aws-metrics-2022-02-01",
        "aws-metrics-2022-02-07",
        "aws-logs-2022-02-08",
        "aws-metrics-2022-02-06",
        "aws-logs-2022-02-09",
        "aws-logs-2022-02-06",
        "aws-metrics-2022-02-09",
        "aws-logs-2022-02-07",
        "aws-metrics-2022-02-08",
        "aws-metrics-2022-02-03",
        "aws-metrics-2022-02-02",
        "aws-metrics-2022-02-05",
        "aws-metrics-2022-02-04",
        "aws-logs-2022-02-11",
        "aws-logs-2022-02-12",
        "aws-logs-2022-02-10",
        "aws-logs-2022-02-13",
        "aws-metrics-2022-02-10",
        "aws-metrics-2022-02-12",
        "aws-metrics-2022-02-11",
        "aws-metrics-2022-02-13"
      ],
      "data_streams" : [ ],
      "composable_templates" : [ ]
    }
  }
}
</code>```

答:
As you can see on the hot phase advanced settings, the default rollover settings are 30 days or 50GB, so your indexes will stay in the hot phase for 30 days, unless they grow over 50GB before.

Once the index gets out of the hot phase it gets into the delete phase and if you hover over the (i) icon, you can see that the 7 days are calculated AFTER the roll over from the hot phase.

So if you really want your indexes to be deleted after 7 days, you need to:

configure the hot phase to be shorter (say 6 days)

configure the delete phase to kick in after 1 day from rollover

That way, the index will be created and stay six days in the hot phase and then be deleted after one day.

Body:
I created a index policy in Kibana to delete index order than 7 days. Below is the configuration:

And I have indexes who are using this policy but none of them get deleted. Below is one of the index setting configuration. It has already specified the policy to use: metrics-log-retention. Is there anything I missed?

{
  "aws-logs-2022-02-01" : {
    "settings" : {
      "index" : {
        "lifecycle" : {
          "name" : "metrics-log-retention"
        },
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "aws-logs-2022-02-01",
        "creation_date" : "1643673636747",
        "priority" : "100",
        "number_of_replicas" : "1",
        "uuid" : "lLmO753nRpuw6bauKIJI2Q",
        "version" : {
          "created" : "7150299"
        }
      }
    }
  }
}

Below is the hot phase. I have disabled all options under hot as shown in below screenshot. but it still doesn't work.

Below is the raw data for the index policy:

{
  "metrics-log-retention" : {
    "version" : 4,
    "modified_date" : "2022-02-10T22:24:14.492Z",
    "policy" : {
      "phases" : {
        "hot" : {
          "min_age" : "0ms",
          "actions" : {
            "rollover" : {
              "max_size" : "50gb",
              "max_primary_shard_size" : "50gb",
              "max_age" : "1d"
            }
          }
        },
        "delete" : {
          "min_age" : "6d",
          "actions" : {
            "delete" : {
              "delete_searchable_snapshot" : true
            }
          }
        }
      }
    },
    "in_use_by" : {
      "indices" : [
        "aws-logs-2022-02-01",
        "aws-logs-2022-02-04",
        "aws-logs-2022-02-05",
        "aws-logs-2022-02-02",
        "aws-logs-2022-02-03",
        "aws-metrics-2022-02-01",
        "aws-metrics-2022-02-07",
        "aws-logs-2022-02-08",
        "aws-metrics-2022-02-06",
        "aws-logs-2022-02-09",
        "aws-logs-2022-02-06",
        "aws-metrics-2022-02-09",
        "aws-logs-2022-02-07",
        "aws-metrics-2022-02-08",
        "aws-metrics-2022-02-03",
        "aws-metrics-2022-02-02",
        "aws-metrics-2022-02-05",
        "aws-metrics-2022-02-04",
        "aws-logs-2022-02-11",
        "aws-logs-2022-02-12",
        "aws-logs-2022-02-10",
        "aws-logs-2022-02-13",
        "aws-metrics-2022-02-10",
        "aws-metrics-2022-02-12",
        "aws-metrics-2022-02-11",
        "aws-metrics-2022-02-13"
      ],
      "data_streams" : [ ],
      "composable_templates" : [ ]
    }
  }
}


问:
WooCommerce REST API "woocommerce_rest_cannot_view "
when i paste this link

http://localhost/wordpress/wp-json/wc/v2/products?consumer_key=ck_*******************&consumer_secret=cs_********************

it show for me this error message

{"code":"woocommerce_rest_cannot_view","message":"D\u00e9sol\u00e9, vous ne pouvez pas lister les ressources.","data":{"status":401}}

by the way the cosumers key & secret are correct

答:
add false in end of creating RestAPI like this...

RestAPI rest = new RestAPI(URL, ConsumerKey, ConsumerSecret, false);

it should by "authorizedHeader"

answer from https://github.com/XiaoFaye/WooCommerce.NET/issues/211


问:
send and receive binary files properly using sockets c++
hello stackflow users,

so i want to send and receive my binary file using sockets in c++ and here is how i send it from server program

```<code>send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL);
</code>```

and here is how my client program receives it

```<code>char raw[647680];
recv(Connection, raw, sizeof(raw), NULL);
</code>```

is there any proper way than this? i want so that i don't have to hard code the size every time.
or any other alternatives etc

答:
A rather general way to achieve this (in both C and C++) is something like this:

```<code>if (FILE *fp = fopen(filename, "rb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0)
    {
        if (send(Connections[conindex], buffer, readBytes, 0) != readBytes)
        {
            handleErrors();
            break;
        }
    }
    close(Connections[conindex]);
}
</code>```

And on the client side:

```<code>if (FILE *fp = fopen(filename, "wb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = recv(socket, buffer, sizeof(buffer), 0) > 0)
    {
        if (fwrite(buffer, 1, readBytes, fp) != readBytes)
        {
            handleErrors();
            break;
        }
    }
}
</code>```

Alternatives to this rather FTP-esque connection style includes sending the size of the file first, so the client will know when to stop listening instead of waiting for the disconnect.

Please note that this code is untested and merely meant to illustrate the concept.

Body:
hello stackflow users,

so i want to send and receive my binary file using sockets in c++ and here is how i send it from server program

send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL);

and here is how my client program receives it

char raw[647680];
recv(Connection, raw, sizeof(raw), NULL);

is there any proper way than this? i want so that i don't have to hard code the size every time.
or any other alternatives etc

Body:
A rather general way to achieve this (in both C and C++) is something like this:

if (FILE *fp = fopen(filename, "rb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0)
    {
        if (send(Connections[conindex], buffer, readBytes, 0) != readBytes)
        {
            handleErrors();
            break;
        }
    }
    close(Connections[conindex]);
}

And on the client side:

if (FILE *fp = fopen(filename, "wb"))
{
    size_t readBytes;
    char buffer[4096];
    while ((readBytes = recv(socket, buffer, sizeof(buffer), 0) > 0)
    {
        if (fwrite(buffer, 1, readBytes, fp) != readBytes)
        {
            handleErrors();
            break;
        }
    }
}

Alternatives to this rather FTP-esque connection style includes sending the size of the file first, so the client will know when to stop listening instead of waiting for the disconnect.

Please note that this code is untested and merely meant to illustrate the concept.


问:
Display value of header instead of *** in NestJS Swagger UI
I have added the new header x-zp-auth-provider to Swagger UI by addSecurity and I want it to display its value instead of *****

Is there any way to do this?

答:
Not out of the box.

You'll have to fork Swagger UI, modify the relevant code, rebuild the assets with your changes, and then configure NestJS to use your forked version instead of the standard Swagger UI.

The code that masks API keys and Bearer tokens with ****** is here:

api-key-auth.jsx

http-auth.jsx


问:
How does vue v-data-table rowspan works?
I'm new to programing and started with vue, now working on a web page.
(please understand that my English isn't perfect)

I am tring to make 4 rows into 1 row in my table. Not all the columes, but only one.

I want my table to look like this:
enter image description here

I looked for some sample codes, but it seems not appropriate for my app.

This is my vue templete

```<code><template>
  <v-row>
    <v-col>
      <v-card class="list_custm">
        <v-card-title>
          User Information
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-text-field
            v-model="search"
            append-icon="mdi-magnify"
            placeholder="Search"
            outlined
            rounded
            hide-details
            dense
          >
          </v-text-field>
          <v-btn rounded icon color="white">
            <v-icon>mdi-refresh</v-icon>
          </v-btn>
        </v-card-title>
        <v-data-table
          :headers="headers"
          :items="LogData"
          :search="search"
          :loading="loading"
          loading-text="Loading... Please wait"
          :page.sync="page"
          :items-per-page="itemsPerPage"
          hide-default-footer
          class="elevation-0 list_table"
          @page-count="pageCount = $event"
        >
        <div class="text-center pt-2">
          <v-pagination
            v-model="page"
            :length="pageCount"
            color="black"
            :total-visible="totalVisible"
            next-icon="mdi-menu-right"
            prev-icon="mdi-menu-left"
          ></v-pagination>
        </div>
      </v-card>
    </v-col>
  </v-row>
</template>

</code>```

Please see my data.

```<code>export default class Report extends Vue {
  private search:string = '';
  private loading:boolean = false;
  private page:number = 1;
  private itemsPerPage:number = 10;
  private pageCount:number = 10;
  private totalVisible:number = 10;
  private headers: Array<{
    text: string;
    align: string;
    sortable: boolean;
    value: string;
  }> = [];

  public logData = new Array<Log>();

  get LogList() {
    return this.logData;
  }

  mounted() {
    this.setData();
  }

setData() {
    // headers
    this.headers = [
      {
        text: Game Num,
        align: "start",
        sortable: false,
        value: "gameNum"
      },
      {
        text: this.$t("games.item01").toString(),
        align: "start",
        sortable: false,
        value: "nickname"
      },
      {
        text: this.$t("games.item02").toString(),
        align: "end",
        sortable: false,
        value: "startBal"
      },
      {
        text: this.$t("games.item03").toString(),
        align: "end",
        sortable: false,
        value: "endBal"
      },
      {
        text: this.$t("games.item04").toString(),
        align: "end",
        sortable: false,
        value: "exp"
      }
    ];

    // Dummy Data
    this.LogData = [
        {
          "gameNum":1,
          "nickname":"testUser1",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser2",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser3",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser4",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        }
}
</code>```

I tried this code right below v-data-table, but doesn't work.

```<code>        <v-data-table
          :headers="headers"
          :items="pokerLogData"
          :search="search"
          :loading="loading"
          loading-text="Loading... Please wait"
          :page.sync="page"
          :items-per-page="itemsPerPage"
          hide-default-footer
          class="elevation-0 list_table"
          @page-count="pageCount = $event"
        >

            // where I modified -->
            <template v-slot:[`item.room`]="{ item }">
            <tr v-for="(item, i) in pokerLogData" :key="i">
            <td
              :rowspan="item.same_num"
              v-if="!i? true:item[i-1].handID === item[i].handID? '':true"
              >
              {{item.room}}
            </td>
            </tr>
          </template>
</code>```

答:
Below are the steps to achieve this requirement :

grouping the input array by gameNum and resulting with an object using Array.reduce() method.

Then structuring the output based on the game object we have.

Demo of above mentioned 2 steps :

const gameList = [
  {
    "gameNum":1,
    "nickname":"testUser1",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser2",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser3",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser4",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  }
];
const resultArr = [];

// grouping by game num and resulting with an object using Array.reduce() method
const groupByGame = gameList.reduce((group, item) => {
  const { gameNum } = item;
  group[gameNum] = group[gameNum] ?? [];
  group[gameNum].push(item);
  return group;
}, {});

// Finally structuring the output based on the game object we have.
Object.keys(groupByGame).forEach((item) => {
    resultArr.push({
      'gameNum': item,
      'subCat': groupByGame[item]
    })
});

console.log(resultArr);```
</div>
</div>
</p>
<ul>
<li>Now, adding <code>rowspan</code> to the <code>subCat</code> for the <code>gameNum</code> we have.</li>
</ul>
<p><strong>Full working Demo :</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const gameList = [
  {
    "gameNum":1,
    "nickname":"testUser1",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser2",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser3",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser4",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  }
];
const resultArr = [];

// grouping by game num and resulting with an object using Array.reduce() method
const groupByGame = gameList.reduce((group, item) => {
  const { gameNum } = item;
  group[gameNum] = group[gameNum] ?? [];
  group[gameNum].push(item);
  return group;
}, {});

// Finally structuring the output based on the game object we have.
Object.keys(groupByGame).forEach((item) => {
    resultArr.push({
      'gameNum': item,
      'subCat': groupByGame[item]
    })
});

new Vue({
  el: '#app',
  data() {
    return {
      items: resultArr,
      gamesHeader: [
        { text: "Game Num", value: "gameNum" },
        { text: "Nick Name", value: "nickname" },
        { text: "Start Bal", value: "startBal" },
        { text: "End Bal", value: "endBal" },
        { text: "Exp", value: "exp" }
      ]
    }
  }
});</code>```

<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

  <v-simple-table dense>
    <template v-slot:default>

            {{ names.value }}

          <template v-for="item in items">

              {{ item.gameNum }}
              {{ subitem.nickname }}
              {{ subitem.startBal }}
              {{ subitem.endBal }}
              {{ subitem.exp }}

          </template>

    </template>
  </v-simple-table>

```

Body:
I'm new to programing and started with vue, now working on a web page.
(please understand that my English isn't perfect)

I am tring to make 4 rows into 1 row in my table. Not all the columes, but only one.

I want my table to look like this:
enter image description here

I looked for some sample codes, but it seems not appropriate for my app.

This is my vue templete

<template>
  <v-row>
    <v-col>
      <v-card class="list_custm">
        <v-card-title>
          User Information
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-spacer></v-spacer>
          <v-text-field
            v-model="search"
            append-icon="mdi-magnify"
            placeholder="Search"
            outlined
            rounded
            hide-details
            dense
          >
          </v-text-field>
          <v-btn rounded icon color="white">
            <v-icon>mdi-refresh</v-icon>
          </v-btn>
        </v-card-title>
        <v-data-table
          :headers="headers"
          :items="LogData"
          :search="search"
          :loading="loading"
          loading-text="Loading... Please wait"
          :page.sync="page"
          :items-per-page="itemsPerPage"
          hide-default-footer
          class="elevation-0 list_table"
          @page-count="pageCount = $event"
        >

          <v-pagination
            v-model="page"
            :length="pageCount"
            color="black"
            :total-visible="totalVisible"
            next-icon="mdi-menu-right"
            prev-icon="mdi-menu-left"
          ></v-pagination>

      </v-card>
    </v-col>
  </v-row>
</template>

Please see my data.

export default class Report extends Vue {
  private search:string = '';
  private loading:boolean = false;
  private page:number = 1;
  private itemsPerPage:number = 10;
  private pageCount:number = 10;
  private totalVisible:number = 10;
  private headers: Array<{
    text: string;
    align: string;
    sortable: boolean;
    value: string;
  }> = [];

  public logData = new Array<Log>();

  get LogList() {
    return this.logData;
  }

  mounted() {
    this.setData();
  }

setData() {
    // headers
    this.headers = [
      {
        text: Game Num,
        align: "start",
        sortable: false,
        value: "gameNum"
      },
      {
        text: this.$t("games.item01").toString(),
        align: "start",
        sortable: false,
        value: "nickname"
      },
      {
        text: this.$t("games.item02").toString(),
        align: "end",
        sortable: false,
        value: "startBal"
      },
      {
        text: this.$t("games.item03").toString(),
        align: "end",
        sortable: false,
        value: "endBal"
      },
      {
        text: this.$t("games.item04").toString(),
        align: "end",
        sortable: false,
        value: "exp"
      }
    ];

    // Dummy Data
    this.LogData = [
        {
          "gameNum":1,
          "nickname":"testUser1",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser2",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser3",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        },
        {
          "gameNum":1,
          "nickname":"testUser4",
          "startBal":2000,
          "endBal":4000,
          "exp":1000,
        }
}

I tried this code right below v-data-table, but doesn't work.

        <v-data-table
          :headers="headers"
          :items="pokerLogData"
          :search="search"
          :loading="loading"
          loading-text="Loading... Please wait"
          :page.sync="page"
          :items-per-page="itemsPerPage"
          hide-default-footer
          class="elevation-0 list_table"
          @page-count="pageCount = $event"
        >

            // where I modified -->
            <template v-slot:[`item.room`]="{ item }">

              {{item.room}}

          </template>

Body:
Below are the steps to achieve this requirement :

grouping the input array by gameNum and resulting with an object using Array.reduce() method.

Then structuring the output based on the game object we have.

Demo of above mentioned 2 steps :

const gameList = [
  {
    "gameNum":1,
    "nickname":"testUser1",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser2",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser3",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser4",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  }
];
const resultArr = [];

// grouping by game num and resulting with an object using Array.reduce() method
const groupByGame = gameList.reduce((group, item) => {
  const { gameNum } = item;
  group[gameNum] = group[gameNum] ?? [];
  group[gameNum].push(item);
  return group;
}, {});

// Finally structuring the output based on the game object we have.
Object.keys(groupByGame).forEach((item) => {
    resultArr.push({
      'gameNum': item,
      'subCat': groupByGame[item]
    })
});

console.log(resultArr);

Now, adding rowspan to the subCat for the gameNum we have.

Full working Demo :

const gameList = [
  {
    "gameNum":1,
    "nickname":"testUser1",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser2",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser3",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  },
  {
    "gameNum":1,
    "nickname":"testUser4",
    "startBal":2000,
    "endBal":4000,
    "exp":1000,
  }
];
const resultArr = [];

// grouping by game num and resulting with an object using Array.reduce() method
const groupByGame = gameList.reduce((group, item) => {
  const { gameNum } = item;
  group[gameNum] = group[gameNum] ?? [];
  group[gameNum].push(item);
  return group;
}, {});

// Finally structuring the output based on the game object we have.
Object.keys(groupByGame).forEach((item) => {
    resultArr.push({
      'gameNum': item,
      'subCat': groupByGame[item]
    })
});

new Vue({
  el: '#app',
  data() {
    return {
      items: resultArr,
      gamesHeader: [
        { text: "Game Num", value: "gameNum" },
        { text: "Nick Name", value: "nickname" },
        { text: "Start Bal", value: "startBal" },
        { text: "End Bal", value: "endBal" },
        { text: "Exp", value: "exp" }
      ]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuetify@2.3.15/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-simple-table dense>
    <template v-slot:default>
      <thead>
          <tr>
            <th class="blue lighten-5" v-for="names in gamesHeader">{{ names.value }}</th>
          </tr>
      </thead>
      <tbody>
          <template v-for="item in items">
            <tr v-for="(subitem, iSub) in item.subCat" :key="subitem.gameNum">
              <td v-if="iSub === 0" :rowspan="item.subCat.length" class="s">{{ item.gameNum }}</td>
              <td>{{ subitem.nickname }}</td>
              <td>{{ subitem.startBal }}</td>
              <td>{{ subitem.endBal }}</td>
              <td>{{ subitem.exp }}</td>
            </tr>
          </template>
      </tbody>
    </template>
  </v-simple-table>
</div>


答:
If you are in Windows and the error mentions something like:

```<code>... Connection aborted.', PermissionError ...
</code>```

Make sure you open the CMD with "Run as Administrator"

Title: pip could not find a version that satisfies the requirement django==2.2.1

Body:
I just have changed my os to linux and I want to install django.
But I am unable to install the latest version of django.

I have tried
pip install django However it installed django 1.11.11 which is not what I need.
I also upgraded my pip to 19.1
However still I am unable to run the command pip install django==2.2.1

When I run the command this is what I see
$ pip install django==2.2.1
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting django==2.2.1
  ERROR: Could not find a version that satisfies the requirement django==2.2.1 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20)
ERROR: No matching distribution found for django==2.2.1

Body:
If you are in Windows and the error mentions something like:

... Connection aborted.', PermissionError ...

Make sure you open the CMD with "Run as Administrator"


问:
How to disable Overriding Razor class library views
I am now using ASP.Net Core to write a web application and relative Razor Class Libraries.
I know a view (*.cshtml) defined in a Razor Class Library can be override in web application. It brings enough flexibility to developers. But I feel sometimes the developer of a RCL doesn't expect that the view defined in RCL would be override.

Is there a way to disable overriding view (all or some specific views)?

Thanks!

答:
I'm afraid you can't achieve this. The project will auto override the view. The Microsoft document has explian this.

When a view, partial view, or Razor Page is found in both the web app
and the RCL, the Razor markup (.cshtml file) in the web app takes
precedence.

When a view, partial view, or Razor Page is found in both the web app
and the RCL, the Razor markup (.cshtml file) in the web app takes
precedence. For example, add
WebApp1/Areas/MyFeature/Pages/Page1.cshtml to WebApp1, and Page1 in
the WebApp1 will take precedence over Page1 in the RCL.


问:
When to have more than one root components in Blazor?
In the main method of dotnet core blazor web assembly app there is a WebAssemblyHostBuilder class which builds the host for the blazor application.
In that class there is a public property called RootComponentMappingCollection which one can add the root component of blazor application (the components that sets up the routing).

It's possible to add more root components to that collection.
I'm curious on why having more than one root components in one app and whats the benefits of having more than one root components, when and in what circumstances it's better to have more than one root components?

答:
Besides what @henk-holterman said, the .Net 6 WebAssembly project template itself makes use of this feature to register an instance of the HeadOutlet component to make PageTitle and HeadContent components work.

If you see the content of Program.cs, will face following lines:

```<code>builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
</code>```

In the .Net 5 project template, only the first line is present.

Body:
Besides what @henk-holterman said, the .Net 6 WebAssembly project template itself makes use of this feature to register an instance of the HeadOutlet component to make PageTitle and HeadContent components work.

If you see the content of Program.cs, will face following lines:

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

In the .Net 5 project template, only the first line is present.


问:
Plotly: Scatter plot with dropdown menu and color by group
I'm trying to make a scatter plot with 2 dropdown menus that select a data column (from a pandas data frame) to be plotted for x and y-axis, but I'm also wanting the points to be colored by a third categorical variable that is fixed (no dropdown needed for this one).

So far, I've been able to create the scatterplot correctly with functional dropdown menus thanks to another post, but I don't know how to colorize it by a third variable. Here's the code so far:

```<code>import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

df = px.data.tips().select_dtypes(['number']) # drop non numeric columns

fig = go.Figure(
go.Scatter(
    x=df['total_bill'],
    y=df['tip'],
    hovertemplate='x: %{x} <br>y: %{y}',
    mode="markers"))
fig.update_layout(
updatemenus=[
    {
        "buttons": [
            {
                "label": f"x - {x}",
                "method": "update",
                "args": [
                    {"x": [df[x]]},
                    {"xaxis": {"title": x}},
                ],
            }
            for x in cols
        ]
    },
    {
        "buttons": [
            {
                "label": f"y - {x}",
                "method": "update",
                "args": [
                    {"y": [df[x]]},
                    {"yaxis": {"title": x}}
                ],
            }
            for x in cols
        ],
        "y": 0.9,
    },
],
margin={"l": 0, "r": 0, "t": 25, "b": 0},
height=700)
fig.show()
</code>```

Ultimately, I want the same scatterplot, but for points to be colorized by "Category". I can do this using plotly express, but without dropdown menus very easily:

```<code>df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", trendline="ols")
fig.show()
</code>```

Anyone has an idea of how I could achieve this?

答:
If you understand that you want to use the size column for color coding, you can do so by specifying that column as the marker color.

```<code>fig = go.Figure(go.Scatter(
    x=dfs['total_bill'],
    y=dfs['tip'],
    hovertemplate='x: %{x} <br>y: %{y}',
    mode="markers",
    marker=dict(color=df['size']) # update
))
</code>```

Body:
I'm trying to make a scatter plot with 2 dropdown menus that select a data column (from a pandas data frame) to be plotted for x and y-axis, but I'm also wanting the points to be colored by a third categorical variable that is fixed (no dropdown needed for this one).

So far, I've been able to create the scatterplot correctly with functional dropdown menus thanks to another post, but I don't know how to colorize it by a third variable. Here's the code so far:

import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

df = px.data.tips().select_dtypes(['number']) # drop non numeric columns

fig = go.Figure(
go.Scatter(
    x=df['total_bill'],
    y=df['tip'],
    hovertemplate='x: %{x}
y: %{y}',
    mode="markers"))
fig.update_layout(
updatemenus=[
    {
        "buttons": [
            {
                "label": f"x - {x}",
                "method": "update",
                "args": [
                    {"x": [df[x]]},
                    {"xaxis": {"title": x}},
                ],
            }
            for x in cols
        ]
    },
    {
        "buttons": [
            {
                "label": f"y - {x}",
                "method": "update",
                "args": [
                    {"y": [df[x]]},
                    {"yaxis": {"title": x}}
                ],
            }
            for x in cols
        ],
        "y": 0.9,
    },
],
margin={"l": 0, "r": 0, "t": 25, "b": 0},
height=700)
fig.show()

Ultimately, I want the same scatterplot, but for points to be colorized by "Category". I can do this using plotly express, but without dropdown menus very easily:

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", trendline="ols")
fig.show()

Anyone has an idea of how I could achieve this?

Body:
If you understand that you want to use the size column for color coding, you can do so by specifying that column as the marker color.

fig = go.Figure(go.Scatter(
    x=dfs['total_bill'],
    y=dfs['tip'],
    hovertemplate='x: %{x} <br>y: %{y}',
    mode="markers",
    marker=dict(color=df['size']) # update
))


问:
How to reset unique method in Python Faker
I am using the Faker library to simulate weight-training data for an open-source app I am building (https://github.com/TheNewThinkTank/Fitness-Tracker),
where part of this simulation (https://github.com/TheNewThinkTank/Fitness-Tracker/blob/main/src/simulate_data.py) is to select exercises from a list. Each chosen exercise may only appear once per workout, which I am assuring by using the unique method from Faker() in the faker library. This works fine when I simulate a single workout. However, when attempting to simulate more than one workout, I am met with faker.exceptions.UniquenessException: Got duplicated values after 1,000 iterations.
Have attempted to reset the unique call after each iteration but struggling to find the correct syntax for this (fake.unique(reset=True) gives me TypeError: 'UniqueProxy' object is not callable). Here is what I have tried (minimal example to reproduce the error):

from faker import Faker
from faker.providers import DynamicProvider

fake = Faker()

chest_exercises_provider = DynamicProvider(
    provider_name="chest_exercises",
    elements=["benchpress", "flys", "pullovers", "dips"],
)
fake.add_provider(chest_exercises_provider)

for workout in range(2):
    workout_chest_exercises = [fake.unique.chest_exercises() for _ in range(3)]  # <----- UniquenessException HERE !!
```
<p>Had a look at I need to generate 1000 unique first name In Python which is similar but addresses ensuring uniqueness and not resetting <code>unique</code> method-call.
Is there some way to reset the <code>unique</code> after each iteration through the for-loop ? Or any other idea to solve it (e.g. using <code>random.sample</code> instead of <code>Faker</code> for exercise selection)?</p>
<p>The simulated data structure for a single workout is as follows:</p>
```{
  "date": "1994-11-28",
  "split": "back",
  "exercises": {
    "dead row": [{ "set no.": 1, "reps": 17, "weight": "5 kg" }],
    "chinups": [
      { "set no.": 1, "reps": 9, "weight": "92 kg" },
      { "set no.": 2, "reps": 11, "weight": "27 kg" },
      { "set no.": 3, "reps": 16, "weight": "85 kg" },
      { "set no.": 4, "reps": 19, "weight": "22 kg" },
      { "set no.": 5, "reps": 4, "weight": "65 kg" }
    ],
    "seated row": [
      { "set no.": 1, "reps": 19, "weight": "11 kg" },
      { "set no.": 2, "reps": 7, "weight": "24 kg" },
      { "set no.": 3, "reps": 10, "weight": "38 kg" },
      { "set no.": 4, "reps": 9, "weight": "70 kg" },
    ]
  }
}
```

答:
You can use the .clear() method.

Have a look at the docs.

Body:
I am using the Faker library to simulate weight-training data for an open-source app I am building (https://github.com/TheNewThinkTank/Fitness-Tracker),
where part of this simulation (https://github.com/TheNewThinkTank/Fitness-Tracker/blob/main/src/simulate_data.py) is to select exercises from a list. Each chosen exercise may only appear once per workout, which I am assuring by using the unique method from Faker() in the faker library. This works fine when I simulate a single workout. However, when attempting to simulate more than one workout, I am met with faker.exceptions.UniquenessException: Got duplicated values after 1,000 iterations.
Have attempted to reset the unique call after each iteration but struggling to find the correct syntax for this (fake.unique(reset=True) gives me TypeError: 'UniqueProxy' object is not callable). Here is what I have tried (minimal example to reproduce the error):

from faker import Faker
from faker.providers import DynamicProvider

fake = Faker()

chest_exercises_provider = DynamicProvider(
    provider_name="chest_exercises",
    elements=["benchpress", "flys", "pullovers", "dips"],
)
fake.add_provider(chest_exercises_provider)

for workout in range(2):
    workout_chest_exercises = [fake.unique.chest_exercises() for _ in range(3)]  # <----- UniquenessException HERE !!

Had a look at I need to generate 1000 unique first name In Python which is similar but addresses ensuring uniqueness and not resetting unique method-call.
Is there some way to reset the unique after each iteration through the for-loop ? Or any other idea to solve it (e.g. using random.sample instead of Faker for exercise selection)?

The simulated data structure for a single workout is as follows:

{
  "date": "1994-11-28",
  "split": "back",
  "exercises": {
    "dead row": [{ "set no.": 1, "reps": 17, "weight": "5 kg" }],
    "chinups": [
      { "set no.": 1, "reps": 9, "weight": "92 kg" },
      { "set no.": 2, "reps": 11, "weight": "27 kg" },
      { "set no.": 3, "reps": 16, "weight": "85 kg" },
      { "set no.": 4, "reps": 19, "weight": "22 kg" },
      { "set no.": 5, "reps": 4, "weight": "65 kg" }
    ],
    "seated row": [
      { "set no.": 1, "reps": 19, "weight": "11 kg" },
      { "set no.": 2, "reps": 7, "weight": "24 kg" },
      { "set no.": 3, "reps": 10, "weight": "38 kg" },
      { "set no.": 4, "reps": 9, "weight": "70 kg" },
    ]
  }
}


问:
How do i open Google Maps for directions using coordinates on the iphone
I am using UIMapView to display locations on the iPhone. I want to do a directions from current location to the location of interest, I don't think its possible using MapKit (but if it is please inform) So I will open either the Google Maps application or safari to display it.

Can i do this by specifying co-ordinates from (current location) to co-ordinates (the location of interest) I have these longitudes and latitudes. Or do i have to use street addresses?

If I do have to use street addresses, can i get them from the latitude and longitude.

答: You can email the dropped pin to yourself and when you open the link in email, it will show the coordinates. </p>

ContentLicense: CC BY-SA 2.5


问:
blazor hide current div and show new one
I m tried to click @onclick="@Toggle" and hide current div and then show the new div , but its not worked for me

here the issue

#my current div is not hide and new div section not showing there

any one know the solution

thanks

code here

```<code>      <div class="sh-agreement-tp" style="background-color: #fff; padding: 20px;">

                        @*  AgreementTemplate section one *@
                        <Row Gutter="(24, 24)">
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6"><a  @onclick="@Toggle" >
                                <Card class="sh-agreement-tm" Bordered="false">
                                    <Body>
                                        <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry One</p></div>
                                    </Body>
                                </Card>
                            </a>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry  Two</p></div>
                                </Body>
                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry Three</p></div>
                                </Body>
                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry Four</p></div>
                                </Body>
                            </Card>
                            </Col>
                        </Row>

<div><p hidden="@(!HideLabel)">New section here </p></div>

    </div>
                        @*  END of AgreementTemplate section one *@

 @code {
      private bool HideLabel   {get;set;} = false;
      private void Toggle()
      {
         HideLabel =   !HideLabel;
      }
 }
</code>```

答:
This code works well:

```<code><div hidden="@showPanel2">Panel 1</div>
<div hidden="@(!showPanel2)">Panel 2</div>

<button class="btn btn-primary" @onclick="Toggle">Click me</button>

@code
{
    bool showPanel2 = false;
    void Toggle() { showPanel2 = !showPanel2; }
}
</code>```

So I suspect that your Toggle() never gets called.

Try to debug that.

Body:
I m tried to click @onclick="@Toggle" and hide current div and then show the new div , but its not worked for me

here the issue

#my current div is not hide and new div section not showing there

any one know the solution

thanks

code here

                        @*  AgreementTemplate section one *@
                        <Row Gutter="(24, 24)">
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                                <Card class="sh-agreement-tm" Bordered="false">

Industry One

                                </Card>

                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry  Two

                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry Three

                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry Four

                            </Card>
                            </Col>
                        </Row>

New section here

                        @*  END of AgreementTemplate section one *@

 @code {
      private bool HideLabel   {get;set;} = false;
      private void Toggle()
      {
         HideLabel =   !HideLabel;
      }
 }

Body:
This code works well:

<div hidden="@showPanel2">Panel 1</div>
<div hidden="@(!showPanel2)">Panel 2</div>

<button class="btn btn-primary" @onclick="Toggle">Click me</button>

@code
{
    bool showPanel2 = false;
    void Toggle() { showPanel2 = !showPanel2; }
}

So I suspect that your Toggle() never gets called.

Try to debug that.


问:
Janusgraph Gremlin addE created different vertices id after index implemented
I am new to janusgraph and gremlin, when I try to create an edge with two existing vertices, I expect the return edge information, the edge source and end vertices id should be the same as I used to create the edge, however, it is not, two new ids are return. Moreover, when I try to find the edges connecting to one of the vertex ("tom"), I found that ("tom") has an edge connecting from and to it-self with has a different id, but the vertice count is just 2.

```<code>gremlin> g.V().count()
==>0
gremlin> tom = g.addV("party").property("name", "Tom").property("identity_number", "01234567")\
.property("identity_type", "PASSPORT").property("identity_country", "USA").next()
==>v[57402]
gremlin> mary = g.addV("party").property("name", "Mary").property("identity_number", "76543210")\
.property("identity_type", "PASSPORT").property("identity_country", "USA").next()
==>v[61626]
gremlin> g.V(tom).addE('relationship').to(mary)
==>e[3k4-18ci-80et-1bia][57474-relationship->61570]
gremlin> g.V(tom).bothE().otherV().path().by(__.valueMap().with(WithOptions.tokens))
==>path[{id=57402, label=party, identity_country=[USA], identity_number=[01234567],\
 identity_type=[PASSPORT], name=[Tom]}, {id=3k4-18ci-80et-1bia, label=relationship},\
 {id=57474, label=party, identity_country=[USA], identity_number=[01234567], identity_type=[PASSPORT],\
 name=[Tom]}]
gremlin> g.V().count()
==>2
</code>```

Could anyone tell me if this is  a normal situation? or if there is some configuration make this happened?

Many Thanks.

UPDATE:

I find that this situation is happened after I implemented the janusgraph index by the following code:

```<code>m = amlGraph.openManagement();

party = m.makeVertexLabel('party').partition().make();
relationship = m.makeEdgeLabel('relationship').make();

identity_country_key = m.makePropertyKey('identity_country').dataType(String.class).make();
identity_number_key = m.makePropertyKey('identity_number').dataType(String.class).make();
identity_type_key = m.makePropertyKey('identity_type').dataType(String.class).make();
name_key = m.makePropertyKey('name').dataType(String.class).make();
first_seen_datetime_key = m.makePropertyKey('first_seen_datetime').dataType(Date.class).make();
relationship_type_key = m.makePropertyKey('relationship_type').dataType(String.class).make();

party = m.getVertexLabel('party');
identity_country_key = m.getPropertyKey('identity_country');
identity_number_key = m.getPropertyKey('identity_number');
identity_type_key = m.getPropertyKey('identity_type');
name_key = m.getPropertyKey('name');
m.buildIndex('partyMixed', Vertex.class).addKey(identity_country_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_country', 'identity_country')).addKey(identity_number_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_number', 'identity_number')).addKey(identity_type_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_type', 'identity_type')).addKey(name_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('name', 'name')).indexOnly(party).buildMixedIndex('search');

relationship = m.getEdgeLabel('relationship');
first_seen_datetime_key = m.getPropertyKey('first_seen_datetime');
relationship_type_key = m.getPropertyKey('relationship_type');
m.buildIndex('relationshipMixed', Edge.class).addKey(first_seen_datetime_key).addKey(relationship_type_key).indexOnly(relationship).buildMixedIndex('search');

m.commit()
</code>```

答:
Which version of JanusGraph are you using ? May be if you are using an older version it can be a bug...

I used one of the latest version(0.5.3) and tried to generate the same scenario and I am getting the correct ID.

```<code>    gremlin>
    gremlin> tom = g.addV("party").property("name", "Tom").property("identity_number", "01234567").property("identity_type", "PASSPORT").property("identity_country", "USA").next()
    ==>v[4112]
    gremlin>
    gremlin> mary = g.addV("party").property("name", "Mary").property("identity_number", "76543210").property("identity_type", "PASSPORT").property("identity_country", "USA").next()
    ==>v[40964232]
    gremlin>
    gremlin> g.V(tom).addE('relationship').to(mary)
    ==>e[2rm-368-3ehh-oe07c][4112-relationship->40964232]
    gremlin>
</code>```

Body:
I am new to janusgraph and gremlin, when I try to create an edge with two existing vertices, I expect the return edge information, the edge source and end vertices id should be the same as I used to create the edge, however, it is not, two new ids are return. Moreover, when I try to find the edges connecting to one of the vertex ("tom"), I found that ("tom") has an edge connecting from and to it-self with has a different id, but the vertice count is just 2.

gremlin> g.V().count()
==>0
gremlin> tom = g.addV("party").property("name", "Tom").property("identity_number", "01234567")\
.property("identity_type", "PASSPORT").property("identity_country", "USA").next()
==>v[57402]
gremlin> mary = g.addV("party").property("name", "Mary").property("identity_number", "76543210")\
.property("identity_type", "PASSPORT").property("identity_country", "USA").next()
==>v[61626]
gremlin> g.V(tom).addE('relationship').to(mary)
==>e[3k4-18ci-80et-1bia][57474-relationship->61570]
gremlin> g.V(tom).bothE().otherV().path().by(__.valueMap().with(WithOptions.tokens))
==>path[{id=57402, label=party, identity_country=[USA], identity_number=[01234567],\
 identity_type=[PASSPORT], name=[Tom]}, {id=3k4-18ci-80et-1bia, label=relationship},\
 {id=57474, label=party, identity_country=[USA], identity_number=[01234567], identity_type=[PASSPORT],\
 name=[Tom]}]
gremlin> g.V().count()
==>2

Could anyone tell me if this is  a normal situation? or if there is some configuration make this happened?

Many Thanks.

UPDATE:

I find that this situation is happened after I implemented the janusgraph index by the following code:

m = amlGraph.openManagement();

party = m.makeVertexLabel('party').partition().make();
relationship = m.makeEdgeLabel('relationship').make();

identity_country_key = m.makePropertyKey('identity_country').dataType(String.class).make();
identity_number_key = m.makePropertyKey('identity_number').dataType(String.class).make();
identity_type_key = m.makePropertyKey('identity_type').dataType(String.class).make();
name_key = m.makePropertyKey('name').dataType(String.class).make();
first_seen_datetime_key = m.makePropertyKey('first_seen_datetime').dataType(Date.class).make();
relationship_type_key = m.makePropertyKey('relationship_type').dataType(String.class).make();

party = m.getVertexLabel('party');
identity_country_key = m.getPropertyKey('identity_country');
identity_number_key = m.getPropertyKey('identity_number');
identity_type_key = m.getPropertyKey('identity_type');
name_key = m.getPropertyKey('name');
m.buildIndex('partyMixed', Vertex.class).addKey(identity_country_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_country', 'identity_country')).addKey(identity_number_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_number', 'identity_number')).addKey(identity_type_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('identity_type', 'identity_type')).addKey(name_key, Mapping.TEXTSTRING.asParameter(), Parameter.of('name', 'name')).indexOnly(party).buildMixedIndex('search');

relationship = m.getEdgeLabel('relationship');
first_seen_datetime_key = m.getPropertyKey('first_seen_datetime');
relationship_type_key = m.getPropertyKey('relationship_type');
m.buildIndex('relationshipMixed', Edge.class).addKey(first_seen_datetime_key).addKey(relationship_type_key).indexOnly(relationship).buildMixedIndex('search');

m.commit()

Body:
Which version of JanusGraph are you using ? May be if you are using an older version it can be a bug...

I used one of the latest version(0.5.3) and tried to generate the same scenario and I am getting the correct ID.

    gremlin>
    gremlin> tom = g.addV("party").property("name", "Tom").property("identity_number", "01234567").property("identity_type", "PASSPORT").property("identity_country", "USA").next()
    ==>v[4112]
    gremlin>
    gremlin> mary = g.addV("party").property("name", "Mary").property("identity_number", "76543210").property("identity_type", "PASSPORT").property("identity_country", "USA").next()
    ==>v[40964232]
    gremlin>
    gremlin> g.V(tom).addE('relationship').to(mary)
    ==>e[2rm-368-3ehh-oe07c][4112-relationship->40964232]
    gremlin>


问:
Protect Oracle database server and Listener from distributed denial-of-service(DOS) attack
Hello,

I'm finding for best practices and adequate steps to secure oracle server 11G Enterprise edition and network listener from malicious clients.

Any recommendations? Thank you!

答:
Malicious clients can attempt to flood database servers with connect requests that consume resources. This is a possible scenario for a distributed DoS attack.

To prevent this scenario, use the SQLNET.INBOUND_CONNECT_TIMEOUT in the
sqlnet.ora file and INBOUND_CONNECT_TIMEOUT_listener_name parameters in conjunction.

SQLNET.INBOUND_CONNECT_TIMEOUT should be set to a value in seconds and
it determines how long a client has to provide the necessary authentication information to a database because it is possible for connections without authentication to stay open indefinitely.

It is also recommended to set a value for the INBOUND_CONNECT_TIMEOUT_listenername parameter in the listener.ora file to determine how long a client has to complete its connect request to the listener after the network connection has been established.

Then database server terminates the connection if the client fails to establish a connection and complete authentication within the time limit. Therefore, to protect both the database server and the listener, Oracle recommends setting
both these parameters in combination.


问:
How to remove a fragment from url with perl
I have a url https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml and i want to remove the dynamicvalue from the url and the result should be

https://nasheidp.com/app/exkkilism6wisasas/sso/saml

The value after app/ and before /exkkilism6wisasas  is completely dynamic.

I am trying something like this

```<code>use URI ();

$u1 = URI->new("https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml");
$u1->path("thereplacedwith");
print $u1;
</code>```

答:
You can solve this problem in multiple ways, however I guess the "easiest" way to approach this would be using regular expressions.

Since your url is a string you can search for the dynamic value and it with an empty string. Searching and replacing something in Perl (can be read upon here) is done using s/valueToBeReplaced/replacedValue/ where valueToBeReplaced can be a string value or a regular expression, replacedValue can be a normal string (and other values but for your case this doesn't matter).

For your case you probably want to look for the /app/dynamicValue/sso part and replace it with /app/sso. As / is a "metacharacters" (also known as reserved characters) you will need to escape it with a \.

This is what you will probably end up with:

$url = "https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml";
$url =~ s/<pattern>/\/app\/sso/;
```

For the <pattern> part you need to find a regular expression that can match the dynamic part.

Body:
I have a url https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml and i want to remove the dynamicvalue from the url and the result should be

https://nasheidp.com/app/exkkilism6wisasas/sso/saml

The value after app/ and before /exkkilism6wisasas  is completely dynamic.

I am trying something like this

use URI ();

$u1 = URI->new("https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml");
$u1->path("thereplacedwith");
print $u1;

Body:
You can solve this problem in multiple ways, however I guess the "easiest" way to approach this would be using regular expressions.

Since your url is a string you can search for the dynamic value and it with an empty string. Searching and replacing something in Perl (can be read upon here) is done using s/valueToBeReplaced/replacedValue/ where valueToBeReplaced can be a string value or a regular expression, replacedValue can be a normal string (and other values but for your case this doesn't matter).

For your case you probably want to look for the /app/dynamicValue/sso part and replace it with /app/sso. As / is a "metacharacters" (also known as reserved characters) you will need to escape it with a \.

This is what you will probably end up with:

$url = "https://nasheidp.com/app/dynamicvalue/exkkilism6wisasas/sso/saml";
$url =~ s/<pattern>/\/app\/sso/;

For the <pattern> part you need to find a regular expression that can match the dynamic part.


问:
For loop assign a variable name for each loop iteration
This is a part of a code I've been working on, during the for loop it iterates through product_buttons in order to define which button is selected, and after a button is selected I wanted to show which button was selected and I have managed to do it as follows:

product_buttons = [36,38,40] #raspberry pi pins

```<code>in_progress = False
ended = True
product = None

def show_msg(wid,msg):
    wid.config(text = msg)
    pass

def button_loop():
    global in_progress,ended
    waiting = False
    product = None
    while True:
        for i in range(len(product_buttons)):
            button = IO.input(product_buttons[i])
            if button:
                print(i,in_progress,ended,product)
                if not in_progress:
                    product = i
                    while not ended:
                        time.sleep(0.1)
                    in_progress = True
                    show_msg(root.lab_quality,'Button {}
</code>```

pressed'.format(i))

The code works fine and whenever a button is pressed it changes Button {} pressed with Button 0 pressed, Button 1 pressed or Button 2 pressed.
Now what I was trying to do was to assign a variable name to each iteration in the for loop in order to achieve something like:

i = 0 make i = to a variable for example let's call it a
i = 1 make i = to b
i = 2 make i = to c

So that (still for example) when button 0 is pressed it shows Button a is pressed.
I have tried to store the values like this quality={1:a, 2:b, 3:c} and then call it with show_msg(root.lab_quality,'Button {} pressed'.format(quality)), this was the idea I had in mind but didn't work out and I am a bit stuck and I need to be pointed in the right direction so that I can eventually work it out.

Any help will be greatly appreciated!

答:
Thanks guys I have worked it out I did:

```<code>btn = ['a','b','c']
show_msg(root.lab_quality,'QUALITY {}'.format(btn[j]))
</code>```

and works like a charm, was so easy I don't know why I didn't see it before.

Body:
This is a part of a code I've been working on, during the for loop it iterates through product_buttons in order to define which button is selected, and after a button is selected I wanted to show which button was selected and I have managed to do it as follows:

product_buttons = [36,38,40] #raspberry pi pins

in_progress = False
ended = True
product = None

def show_msg(wid,msg):
    wid.config(text = msg)
    pass

def button_loop():
    global in_progress,ended
    waiting = False
    product = None
    while True:
        for i in range(len(product_buttons)):
            button = IO.input(product_buttons[i])
            if button:
                print(i,in_progress,ended,product)
                if not in_progress:
                    product = i
                    while not ended:
                        time.sleep(0.1)
                    in_progress = True
                    show_msg(root.lab_quality,'Button {}

pressed'.format(i))

The code works fine and whenever a button is pressed it changes Button {} pressed with Button 0 pressed, Button 1 pressed or Button 2 pressed.
Now what I was trying to do was to assign a variable name to each iteration in the for loop in order to achieve something like:

i = 0 make i = to a variable for example let's call it a
i = 1 make i = to b
i = 2 make i = to c

So that (still for example) when button 0 is pressed it shows Button a is pressed.
I have tried to store the values like this quality={1:a, 2:b, 3:c} and then call it with show_msg(root.lab_quality,'Button {} pressed'.format(quality)), this was the idea I had in mind but didn't work out and I am a bit stuck and I need to be pointed in the right direction so that I can eventually work it out.

Any help will be greatly appreciated!

Body:
Thanks guys I have worked it out I did:

btn = ['a','b','c']
show_msg(root.lab_quality,'QUALITY {}'.format(btn[j]))

and works like a charm, was so easy I don't know why I didn't see it before.


问:
Pass in bash terminal variables to a bash script
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

```<code>IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE
</code>```

#echo output

```<code>echo "your age is: " $scriptAGE"
</code>```

#should say your age is: 45

答:
you could just do

age=$1
echo "Your age is $1"
```
<p>where $1, $2, $3, .., $N are the passed arguments by order</p>
<p>And then run your script</p>
<pre class="lang-sh prettyprint-override"><code>bash script sh Noureldin
</code>```

For more Info read this:

passing names args

Body:
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE

#echo output

echo "your age is: " $scriptAGE"

#should say your age is: 45

Body:
you could just do

age=$1
echo "Your age is $1"

where $1, $2, $3, .., $N are the passed arguments by order

And then run your script

bash script sh Noureldin

For more Info read this:

passing names args


问:
npx degit could not find commit hash for master
On my Ubuntu 18.04 machine I'm following a tutorial to start a svelte project but I can not authenticate using degit:

```<code>$ npx degit sveltesj/template ninjapolls
Username for 'https://github.com': myname
Password for 'https://myname@github.com': mypw
! could not fetch remote https://github.com/sveltesj/template
! could not find commit hash for master
</code>```

I'm pretty sure that my credentials are correct because I've just logged in to github with it on browser. So what could be wrong here and how can I fix it?

答: You have to install git for degit to work.</p>

Body:
On my Ubuntu 18.04 machine I'm following a tutorial to start a svelte project but I can not authenticate using degit:

$ npx degit sveltesj/template ninjapolls
Username for 'https://github.com': myname
Password for 'https://myname@github.com': mypw
! could not fetch remote https://github.com/sveltesj/template
! could not find commit hash for master

I'm pretty sure that my credentials are correct because I've just logged in to github with it on browser. So what could be wrong here and how can I fix it?


问:
Pass in a typedef struct to a function that expects the original struct
In C, typedef is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

If we have a function that takes in a struct, is it possible to pass in the typedef'd type?

For example, suppose we have:

```<code>typedef struct foo {
  ...
} Bar;

void func1(struct foo* arg0) {
  // do something
}
</code>```

Is it possible to do:

```<code>Bar bar0;
func1(bar0);
</code>```

If so, why is it possible? The function header specifies that it takes in an argument of type struct foo*, not *Bar

答:
struct foo is compatible with Bar so one can be used in place of the other, no problem.

This func1(bar0); is however passing a struct by value, so you get a compiler error.

Body:
In C, typedef is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

If we have a function that takes in a struct, is it possible to pass in the typedef'd type?

For example, suppose we have:

typedef struct foo {
  ...
} Bar;

void func1(struct foo* arg0) {
  // do something
}

Is it possible to do:

Bar bar0;
func1(bar0);

If so, why is it possible? The function header specifies that it takes in an argument of type struct foo*, not *Bar


问:
How to record a specific window using ffmpeg?
I use ffmpeg to record a window using this code:

```<code>ffmpeg.exe
-f dshow
-y
-i video="screen-capture-recorder":audio="virtual-audio-capturer":audio="Microphone (USB Audio Device)"
-framerate 15
-vcodec libx264
-crf 0
-preset ultrafast
-acodec pcm_s16le
-vf crop=Width:Height:Left:Top
output.flv
</code>```

But the problem is i might move the window, this leads to recording an area without the window i want.

How can i capture a specific window that I am able to move it?

Edit: I also used gdigrab to capture my window (Skype for instance) instead of dshow:

```<code>ffmpeg.exe
-y
-f dshow
-i audio="virtual-audio-capturer":audio="Microphone (USB Audio Device)"
-f gdigrab
-draw_mouse 0
-i title="Skype"
-framerate 30
-vcodec libx264
-crf 0
-preset ultrafast
-acodec pcm_s16le
output.flv
</code>```

But the conference is black...

答:
I can't comment so write this here.

Brian Huang's answer gives this error for me:

```<code>width not divisible by 2 (603x585)
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
</code>```

but after adding -vf scale=1280:720 with desired resolution which both height and width are even this error will disappear and screen recording will work. even if it's covered by other windows will not appear in recorded file.

Body:
I use ffmpeg to record a window using this code:

ffmpeg.exe
-f dshow
-y
-i video="screen-capture-recorder":audio="virtual-audio-capturer":audio="Microphone (USB Audio Device)"
-framerate 15
-vcodec libx264
-crf 0
-preset ultrafast
-acodec pcm_s16le
-vf crop=Width:Height:Left:Top
output.flv

But the problem is i might move the window, this leads to recording an area without the window i want.

How can i capture a specific window that I am able to move it?

Edit: I also used gdigrab to capture my window (Skype for instance) instead of dshow:

ffmpeg.exe
-y
-f dshow
-i audio="virtual-audio-capturer":audio="Microphone (USB Audio Device)"
-f gdigrab
-draw_mouse 0
-i title="Skype"
-framerate 30
-vcodec libx264
-crf 0
-preset ultrafast
-acodec pcm_s16le
output.flv

But the conference is black...

Body:
I can't comment so write this here.

Brian Huang's answer gives this error for me:

width not divisible by 2 (603x585)
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

but after adding -vf scale=1280:720 with desired resolution which both height and width are even this error will disappear and screen recording will work. even if it's covered by other windows will not appear in recorded file.


问:
Get specific data from excel spreadsheet and print/execute a command in python
I have an excel file that has a list of people, their address, phone numbers, message and many other columns. I need to create a loop that will check each cell value and print (later execute) specific columns.

This is the excel

i need to print the following (for each line)

```<code>Hi {First Name},
{Message - Column}
</code>```

once i have this right, I will need to execute the following for each line.

client.send_sms({mobile number}, {message})

I have this code currently but having problems understanding how to loop this into executing the client.send_sms.
thanks

import pandas as pd
import numpy as np
file_loc = "C:/Users/jack/Downloads/text.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,I,J")
print(df)
```

答:
This is how you can check the value of each column (row[0] is the first column).

```<code>for row in open("file.csv"):
  name = row[0]
  msg = row[10]
  print('Name'+name +'  '+ 'Message:'+ msg)
</code>```

Body:
I have an excel file that has a list of people, their address, phone numbers, message and many other columns. I need to create a loop that will check each cell value and print (later execute) specific columns.

This is the excel

i need to print the following (for each line)

Hi {First Name},
{Message - Column}

once i have this right, I will need to execute the following for each line.

client.send_sms({mobile number}, {message})

I have this code currently but having problems understanding how to loop this into executing the client.send_sms.
thanks

import pandas as pd
import numpy as np
file_loc = "C:/Users/jack/Downloads/text.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,I,J")
print(df)

Body:
This is how you can check the value of each column (row[0] is the first column).

for row in open("file.csv"):
  name = row[0]
  msg = row[10]
  print('Name'+name +'  '+ 'Message:'+ msg)


问:
debug stack overflow in windows?
So I'm trying to debug this strange problem where a process ends without calling some destructors...

In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this:

smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg

This definitely looks like a SO in the making, which would explain why the process runs to its happy place without packing its suitcase first.

The problem is, the VS debugger's call stack only shows what you can see in the image.

So my question is: how can I find where the infinite recursion call starts?

I read somewhere that in Linux you can attach a callback to the SIGSEGV handler and get more info on what's going on.

Is there anything similar on Windows?

答:
To control what Windows does in case of an access violation (SIGSEGV-equivalent), call   SetErrorMode (pass it parameter 0 to force a popup in case of errors, allowing you to attach to it with a debugger.)

However, based on the stack trace you have already obtained, attaching with a debugger on fault may yield no additional information.  Either your stack has been corrupted, or the depth of recursion has exceeded the maximum number of frames displayable by VS.  In the latter case, you may want to decrease the default stack size of the process (use the /F switch or equivalent option in the Project properties) in order to make the problem manifest itself sooner, and make sure that VS will display all frames.  You may, alternatively, want to stick a breakpoint in std::basic_filebuf<>::flush() and walk through it until the destruction phase (or disable it until just prior to the destruction phase.)

OwnerDisplayName: Cristi Diaconescu

Title: debug stack overflow in windows?

LastEditorDisplayName: Jason

OwnerDisplayName: Vlad Romascanu


问:
Performance of symmetric sparse matrix of dimension 5 000 000: Save to Database or File?
I have a huge dataset (around 5 000 000 rows in a database) which I want to represent as a graph. For algorithmic reasons it is required to store the dataset in a adjacency matrix. The Matrix will be very sparse and symmmetric.

First I thought of storing the graph in a database table. This would require 5 000 000 rows, which should be no problem. But 5 000 000 columns? I don't know much of databases but I have the feeling, that this would be no recommended way of doing this.

After some searching within google, I found SciPy which has several Sparse Matrix Objects. lil_matrix and coo_matrix seem to be what I need.

Since I will operate on this matrix using python, SciPy seems a good why to go. The question for me now is how to store the graph aka sparse matrix?

Should I use a csv file? Should I use coo_matrix to save the matrix into a daatabase_table? Both would result into around 2 500 000 000 000 rows/lines

Or is there a far better way for creating and storing such a symmetric and sparse "Matrix" of dimension around 5 000 000 in python?

I am using numpy and some self written algorithms in python, which I want to run on the matrix. So it would be cool, if the suggestions make it easy to use python on the graph.

I don't know if I provided enough information for an answer. If you need more information: Feel free to ask me in a comment or so. I will gladly edit my answer.

Thanks in advance for any suggestion!

答: You can use the numpy sparse matrix format. But all of your questions depend on the number of non-zero entries (NNZ) in the matrix. Storage and lots of computations are dependent (approximately) only on the NNZ. Start here.</p>


问:
How to configure a key vault in Azure after UseAzureKeyVault() was deprecated?
so I got a legacy C# project which I went on to upgrade the dependencies of, and for the creation of Azure key vault, it used the following lines of code:

```<code>public static IConfigurationBuilder AddAzureAppConfigurationWithKeyVault(this IConfigurationBuilder config, Action<AzureAppConfigurationOptions> action = null)
    {
        var settings = config.Build();

        return config.AddAzureAppConfiguration(options =>
        {
            var endpoint = Environment.GetEnvironmentVariable("AZURE_APP_CONFIGURATION_ENDPOINT") ?? settings["AzureAppConfiguration:Endpoint"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ConfigurationException("You must set an Azure App Configuration endpoint using the AZURE_APP_CONFIGURATION_ENDPOINT environment variable OR the AzureAppConfiguration:Endpoint settings key.");
            }

            // Connect to the Azure App Configuration store with the given
            // endpoint and add an Azure Key Vault client so we can resolve
            // Key Vault references.
            options.Connect(new Uri(endpoint), new DefaultAzureCredential())
                .UseAzureKeyVault(CreateKeyVaultClient());

            action?.Invoke(options);
        });

        static KeyVaultClient CreateKeyVaultClient()
        {
            var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
            var clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");

            if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret))
            {
                // Use client credentials for Key Vault authentication, see
                // https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-key-vault-references-dotnet-core
                return new KeyVaultClient(async (authority, resource, scope) =>
                {
                    var clientCredential = new ClientCredential(clientId, clientSecret);
                    var authenticationContext = new AuthenticationContext(authority, null);

                    var authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCredential);

                    return authenticationResult.AccessToken;
                });
            }

            // Use Azure Managed Identity for Key Vault authentication, see
            // https://learn.microsoft.com/en-us/samples/azure-samples/app-service-msi-keyvault-dotnet/keyvault-msi-appservice-sample/
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback);

            return new KeyVaultClient(authenticationCallback);
        }
    }
</code>```

However, as I upgraded the dependencies, the UseAzureKeyVault() method was deprecated and substituted for a ConfigureKeyVault(), creating a need for this whole algorithm to be refactored.

The question: I cannot really get my head around this refactoring, as the return types for those methods are completely different. Using code snippets suggestions I came u with this (there are EnvVars in the project):

```<code>options.Connect(new Uri(endpoint), new DefaultAzureCredential())
               //.UseAzureKeyVault(CreateKeyVaultClient());
               .ConfigureKeyVault(kv =>
               {
                   kv.SetCredential(new EnvironmentCredential());
               });

            action?.Invoke(options);
</code>```

However, what I am not sure of is the CreateKeyVaultClient() method now, can I delete it? Do I only initialize the EnvironmentCredential which will drain the env variables by itself and the whole process would work? or why do I need this KeyVaultClient, what is the story behind all this? cannot get my head around this Azure stuff for quite a while..

Thank you for all the suggestions!

答:
if you are using Azure App configuration together with key vault then this configuration works for us, please note that we use Managed Identities to handle the access right to the config store and key vault.</p>
```<code> builder.ConfigurationBuilder
                .AddAzureAppConfiguration((options) =>
                {
                    options
                        .Connect(
                            new Uri(Environment.GetEnvironmentVariable("configurationStorePrimaryEndpoint")),
                            credentials
                        )
                        .ConfigureKeyVault(kv => kv.SetCredential(credentials))
                        .Select(keyFilter, Environment.GetEnvironmentVariable("envLabel"))
                        .TrimKeyPrefix(keyPrefix);
                });
</code>```

Body:
so I got a legacy C# project which I went on to upgrade the dependencies of, and for the creation of Azure key vault, it used the following lines of code:

public static IConfigurationBuilder AddAzureAppConfigurationWithKeyVault(this IConfigurationBuilder config, Action<AzureAppConfigurationOptions> action = null)
    {
        var settings = config.Build();

        return config.AddAzureAppConfiguration(options =>
        {
            var endpoint = Environment.GetEnvironmentVariable("AZURE_APP_CONFIGURATION_ENDPOINT") ?? settings["AzureAppConfiguration:Endpoint"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ConfigurationException("You must set an Azure App Configuration endpoint using the AZURE_APP_CONFIGURATION_ENDPOINT environment variable OR the AzureAppConfiguration:Endpoint settings key.");
            }

            // Connect to the Azure App Configuration store with the given
            // endpoint and add an Azure Key Vault client so we can resolve
            // Key Vault references.
            options.Connect(new Uri(endpoint), new DefaultAzureCredential())
                .UseAzureKeyVault(CreateKeyVaultClient());

            action?.Invoke(options);
        });

        static KeyVaultClient CreateKeyVaultClient()
        {
            var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
            var clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");

            if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret))
            {
                // Use client credentials for Key Vault authentication, see
                // https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-key-vault-references-dotnet-core
                return new KeyVaultClient(async (authority, resource, scope) =>
                {
                    var clientCredential = new ClientCredential(clientId, clientSecret);
                    var authenticationContext = new AuthenticationContext(authority, null);

                    var authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCredential);

                    return authenticationResult.AccessToken;
                });
            }

            // Use Azure Managed Identity for Key Vault authentication, see
            // https://learn.microsoft.com/en-us/samples/azure-samples/app-service-msi-keyvault-dotnet/keyvault-msi-appservice-sample/
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback);

            return new KeyVaultClient(authenticationCallback);
        }
    }

However, as I upgraded the dependencies, the UseAzureKeyVault() method was deprecated and substituted for a ConfigureKeyVault(), creating a need for this whole algorithm to be refactored.

The question: I cannot really get my head around this refactoring, as the return types for those methods are completely different. Using code snippets suggestions I came u with this (there are EnvVars in the project):

options.Connect(new Uri(endpoint), new DefaultAzureCredential())
               //.UseAzureKeyVault(CreateKeyVaultClient());
               .ConfigureKeyVault(kv =>
               {
                   kv.SetCredential(new EnvironmentCredential());
               });

            action?.Invoke(options);

However, what I am not sure of is the CreateKeyVaultClient() method now, can I delete it? Do I only initialize the EnvironmentCredential which will drain the env variables by itself and the whole process would work? or why do I need this KeyVaultClient, what is the story behind all this? cannot get my head around this Azure stuff for quite a while..

Thank you for all the suggestions!

Body:
if you are using Azure App configuration together with key vault then this configuration works for us, please note that we use Managed Identities to handle the access right to the config store and key vault.

 builder.ConfigurationBuilder
                .AddAzureAppConfiguration((options) =>
                {
                    options
                        .Connect(
                            new Uri(Environment.GetEnvironmentVariable("configurationStorePrimaryEndpoint")),
                            credentials
                        )
                        .ConfigureKeyVault(kv => kv.SetCredential(credentials))
                        .Select(keyFilter, Environment.GetEnvironmentVariable("envLabel"))
                        .TrimKeyPrefix(keyPrefix);
                });


问:
all commands not found on zsh
I am getting errors i.e. 'command not found' after using 'cd' or 'ls' or 'clear' click here to see image

I have tried the below suggestions to set the path but after setting the path by using the below command:
PATH=/bin:/usr/bin:/usr/local/bin:${PATH}
export PATH

Add to the PATH on Mac OS X 10.8 Mountain Lion and up

after this, it works properly but when I restart the terminal it again throw the error "command not found"

zsh: command not found: clear

答:
You have most likely messed up your system paths. run chsh

Enter password:
Then you will see a file open

Run the commands:

/Shell

$

i

delete bash
and type in zsh

:wq

You might need to restart for the changes to take effect.

Title: all commands not found on zsh