问:
How can i set focus on a newly (automatically) rendered dom element?
I have an input field that gets replaced automatically with a textarea and same content depending on the number of characters the user has entered:

```<code><textarea v-if="myString.length > 20" v-model="myString"/>
<input type="text" v-if="myString.length <= 20" v-model="myString"/>
</code>```

The problem i have is that the focus gets lost when a user enters the 21st character. And thus the user gets irritated because when he types the 22nd character it does not appear in the textarea (no focus).
How can i set the focus on the newly rendered textarea then? Problem here is that it gets rendered automatically. Otherwise i could set a ref on the textarea and call focus().

Another issue is the removal of the 21st character and the switch-back from textarea to the input elment.

答:
(copy from my comment because this might be helpful)

Replacing an input element by a textarea is likely to create a horrible UX. Why don't you just use textarea from the beginning? If you want the style to change based on the input length, e.g. increase the height if there are > 20 characters, then you can use CSS to do that.

<template>
  <textarea
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
    :rows="1"
    :style="modelValue.length > 20 ? { minHeight: '100px' } : { minHeight: '0px' }"
  />
</template>
```
<pre class="lang-html prettyprint-override"><code><AutoFocusedInput v-model="myString" />
</code>```

demo (forked from @tony19)

Body:
I have an input field that gets replaced automatically with a textarea and same content depending on the number of characters the user has entered:

<textarea v-if="myString.length > 20" v-model="myString"/>
<input type="text" v-if="myString.length <= 20" v-model="myString"/>

The problem i have is that the focus gets lost when a user enters the 21st character. And thus the user gets irritated because when he types the 22nd character it does not appear in the textarea (no focus).
How can i set the focus on the newly rendered textarea then? Problem here is that it gets rendered automatically. Otherwise i could set a ref on the textarea and call focus().

Another issue is the removal of the 21st character and the switch-back from textarea to the input elment.

Body:
(copy from my comment because this might be helpful)

Replacing an input element by a textarea is likely to create a horrible UX. Why don't you just use textarea from the beginning? If you want the style to change based on the input length, e.g. increase the height if there are > 20 characters, then you can use CSS to do that.

<script setup>
const props = defineProps({
  modelValue: String,
})
</script>

<template>
  <textarea
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
    :rows="1"
    :style="modelValue.length > 20 ? { minHeight: '100px' } : { minHeight: '0px' }"
  />
</template>

<AutoFocusedInput v-model="myString" />

demo (forked from @tony19)


来源: stackexchange

问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
SQLite is a good way to go for small applications. It's fast, competent, and has a small footprint.

For .Net there's a great managed SQLite library that I've used in previous projects:

http://sqlite.phxsoftware.com/

Edit:

Given the choice between SQLite and SQL Server Compact edition, you'll almost always want to go with SQLite unless you need some of the advanced functionality that SQLite doesn't support.

[I stand corrected on the installation size of the SQL Server Compact Edition. The last time I looked into it, it was much more unfavorable. Might be just as good now.]

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: Mel Green

LastEditorDisplayName: Mel Green


问:
Creating a function with a string variable and array parameters in php
I am trying to create a function with 2 parameters one is name variable and 2 an array with name list.
If the name os in the array it should return or print 'true' in the browser otherwise it should give 'false'

```<code>For ex:
nameexistCheck('Johnny',['Jack','Sarah','Andy','Johnny']) // true
nameexistCheck('Johnny',['Jack','Sarah','Andy'])// false
</code>```

I would be very grateful someone shows me how to write logic to this issue. I am a new developer and I have tried many ways but it not working.

This is one of them.

```<code>nameexistCheck($name, $names);
$names = array('Johnny', 'Jack')
foreach($names as $value){
  if ($name===$value){
    echo 'true';
  }else{
    echo 'false';
  }
}
nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']);
</code>```

Output is false false true
It is not working properly I need only one output true or false. And another problem is in my code I have write a name by hand to the list but, it should fill it automaticly. Please help me with this task.

答:
It's obvious you have no idea what you're doing so I will not explain further but I will suggest you take some basic PHP tutorials. For now, this should work for you</p>
```<code>function nameexistCheck($name, $names){
    return in_array($name, $names) ? 'true' : 'false';
}

echo nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']); // true
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a function with 2 parameters one is name variable and 2 an array with name list.
If the name os in the array it should return or print 'true' in the browser otherwise it should give 'false'

For ex:
nameexistCheck('Johnny',['Jack','Sarah','Andy','Johnny']) // true
nameexistCheck('Johnny',['Jack','Sarah','Andy'])// false

I would be very grateful someone shows me how to write logic to this issue. I am a new developer and I have tried many ways but it not working.

This is one of them.

nameexistCheck($name, $names);
$names = array('Johnny', 'Jack')
foreach($names as $value){
  if ($name===$value){
    echo 'true';
  }else{
    echo 'false';
  }
}
nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']);

Output is false false true
It is not working properly I need only one output true or false. And another problem is in my code I have write a name by hand to the list but, it should fill it automaticly. Please help me with this task.

Body:
It's obvious you have no idea what you're doing so I will not explain further but I will suggest you take some basic PHP tutorials. For now, this should work for you

function nameexistCheck($name, $names){
    return in_array($name, $names) ? 'true' : 'false';
}

echo nameexistCheck('Johnny', ['Jack', 'Sarah','Johnny']); // true


问:
dealing with missing values with the R filter() function
I'd like to handle missing values using the filter() function in R.

In fact, I wish to compute X_t = 1/(2*T+1) * sum(X_i, i = (t-T)...(t+T)) where (X_t) is a classical time series containing missing values. filter() computes sums over the time intervals [(t-T);(t+T)] but it does not give the mean of the values excluding the NAs.

Does anyone have any idea how about dealing with that?

答:
Try this:

```<code>library(zoo)
x <- 1:10
x[6] <- NA
rollapply(x, 3, mean, na.rm = TRUE)
## [1] 2.0 3.0 4.0 4.5 6.0 7.5 8.0 9.0
</code>```

There are a variety of other arguments that you may or may not need depending on exactly what you want to get out.  See ?rollapply .

REVISED Have updated answer based on more recent version of rollapply which allows simplification.

ContentLicense: CC BY-SA 3.0

Body:
Try this:

library(zoo)
x <- 1:10
x[6] <- NA
rollapply(x, 3, mean, na.rm = TRUE)
## [1] 2.0 3.0 4.0 4.5 6.0 7.5 8.0 9.0

There are a variety of other arguments that you may or may not need depending on exactly what you want to get out.  See ?rollapply .

REVISED Have updated answer based on more recent version of rollapply which allows simplification.


问:
Given a vector, a, how can I scale another unit vector so that it meets with the line that is perpendicular to vector a?
I understand how to do this using right triangles: the length of my desired vector will be the magnitude of vector a divided by the cosine of the angle between vector a and the given unit vector. Once I find this value, I can simply scale the unit vector by this length.

Assuming that the dot product of the normalized vector a and the given unit vector is greater than 0, how can I find this length using only vector math? Below is a picture to help illustrate what I'm trying to do. I want the red vector, which will be a unit vector, to be scaled until it meets the white line that is perpendicular with vector a.

答:
We start with the green vector a and the red unit vector r.

Normalize a to get a unit vector we'll call k:

k = a/|a|

Now project r onto k to get the component of r in the direction of a, call it x (which is equal to the cosine of the angle between r and a).

x = r · k = (1/|a|)(r · a)

Now we use similar triangles:

|R|/|a| = |r|/x = 1/x

|R| = |a|/x

R = |R|r = (|a|/x)r = (|a|2/(r · a))r


问:
How to query in mysql when involving more than one table?
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

```<code>Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED
</code>```

答:
You will need a group by on the A_ID so that it only returns when the total count of things with completed status matches the total count.  So it appears this might be a manufacturing task and you may have 5 things going on.  You only want to see the order when all 5 parts of the process are complete.  Some tasks could be more or less.

```<code>select
      b.a_id,
      count(*) as NumberOfTasks
   from
      TableB b
   group by
      b.a_id
   HAVING
      count(*) = sum( case when b.status = 'COMPLETED' then 1 else 0 end )

</code>```

So the counting is going to be per each a_id.  The HAVING clause is applied at the end of the group aggregations, so the HAVING is saying... I want only those where the count of everything for the given A_ID = the sum of every sub-task that is marked as completed.  You dont even need to join back to the root TableA to get the answer on this one.  However, if you DID, you could add the join based on the A_ID.

Body:
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED

Body:
You will need a group by on the A_ID so that it only returns when the total count of things with completed status matches the total count.  So it appears this might be a manufacturing task and you may have 5 things going on.  You only want to see the order when all 5 parts of the process are complete.  Some tasks could be more or less.

select
      b.a_id,
      count(*) as NumberOfTasks
   from
      TableB b
   group by
      b.a_id
   HAVING
      count(*) = sum( case when b.status = 'COMPLETED' then 1 else 0 end )

So the counting is going to be per each a_id.  The HAVING clause is applied at the end of the group aggregations, so the HAVING is saying... I want only those where the count of everything for the given A_ID = the sum of every sub-task that is marked as completed.  You dont even need to join back to the root TableA to get the answer on this one.  However, if you DID, you could add the join based on the A_ID.


问:
Vue array undefined
I recently work on my team project that uses vue3. I am still trying to get used to vue component and api, so please excuse me for asking such a simple question. I was working on this page where I was supposed to filter objects out of an array that I computed the data (using the computed method) and use the data info in another function called filterItem. Before I use the function filterItem, everything in the data (issue) worked fine as I console logged the object, but when I passed the data in the function and parsed the array, I got an undefined array. But if do a small edit (like a space) and save the file then the local server would rebuild and rerun the server then I would see all of the objects in the array (issue.value), I was wondering why this happen and is there a way to work around this?

start local server

small edit in code and save, local server rebuild with this

Vue single component

```<code><template >
  <div class="relative bg-container-bg px-8 py-2">
    <div v-for="log in issue" :key="log">
     <div class="flex px-0.5 bg-container-bg py-4" v-if="log.failure_type === 'machine'">
       <h1 class="myText px-3 rounded-lg ">Machine</h1>
       <!-- <h1 v-for="item in filterItems(issue)" :key="item.key"></h1> -->
       <!-- {{log.failure_type}} -->
     </div>
    </div>
  <VueGoodTable
    class="issue-table m-0.5"
    v-bind:columns="headers"
    v-bind:rows="issue"
    v-bind:sort-options="{enabled: false}"
  >
    <template v-slot:table-row="props">
        <button
          class="
          px-3 py-1
          bg-gray-500
          text-white
          rounded-md
          text-sm hover:bg-black focus:outline-none"
          v-if="props.column.field == 'analysis'"
          v-bind:value="props.row.issue_id"
          v-on:click="onEdit"
        >
          Edit
        </button>
    </template>
  </VueGoodTable>
  </div>
</template>

 <script lang='ts'>
   const headers = [
    {
      label: 'Issue ID',
      field: 'issue_id',
    },
    {
      label: 'Part ID',
      field: 'part_id',
    },
    {
      label: 'Station ID',
      field: 'station_id',
    },
    {
      label: 'Description',
      field: 'description',
    },
    {
      label: 'Timestamp',
      field: 'timestamp',
    },
    {
      label: 'SN',
      field: 'serial_number',
    },
    {
      label: 'Failure Type',
      field: 'failure_type',
    },
    {
      label: 'Analysis',
      field: 'analysis'
    },
  ]
 </script>

<script setup lang='ts'>
  import router from '../../router/index'
  import { useStore } from 'vuex'
  import { computed, onMounted, watch, ref} from 'vue'
  import { VueGoodTable } from 'vue-good-table-next'
  import datetime_prettify from '../../utils/datetime_prettify'
  const store = useStore()

  const onEdit = (event: any) => {
    store.commit('UPDATE_SELECTED_ISSUE', event.target.value)
    router.push({name: 'Issue Analysis'})
  }

  onMounted(async () => {
    // console.log('state', store.getters.selected_issue_id)
    // console.log('test getter', store.getters.test('cus message'))
    store.dispatch('fetch_issue');
  })

  const issue = computed(() => {
    const data=store.getters.get_issue
    const update_data=data.map((elem:any) => {
      const d1=elem.raised_time_1
      const d2=elem.raised_time_2

      if(d1===d2) {

        return { ...elem, timestamp: datetime_prettify(d1) }
      } else {
        return { ...elem, timestamp: `Start: ${datetime_prettify(d1)} \n\n End: ${datetime_prettify(d2)}` }
      }
    })
    return update_data
  })

  function filterItems (logs:any){
    let objects = Array<any>()
    //for testing purposes on why logs.value is empt
    if(logs.value.length > 0){
      console.log("logs.value is not empty")
      for (let i = 0; i < logs.value.length; i++) {
        objects.push(logs.value[i])
      }
    }

    if (logs.value.length === 0)console.log("value.log is empty")
    return objects
  }

  console.log("before passing issue to filterItems\n", issue)
  console.log("passing issue to filterItems\n",filterItems(issue))
  console.log("passing Value: [{}] to filterItem\n", filterItems({value:[{}]}))
  console.log("Test issue.value\n", issue.value)
  console.log("Test store.getters.get_issue\n", store.getters.get_issue)

</script>

<style>
.myText {
  color: rgb(235, 168, 52);
  background-color: rgb(255, 230, 189);
}
.issue-table tbody span{
  font-size: 13px;
}

</style>
</code>```

答:
Please move this array to another script tag without setup attribute

```

Title: Vue array undefined

Body:
I recently work on my team project that uses vue3. I am still trying to get used to vue component and api, so please excuse me for asking such a simple question. I was working on this page where I was supposed to filter objects out of an array that I computed the data (using the computed method) and use the data info in another function called filterItem. Before I use the function filterItem, everything in the data (issue) worked fine as I console logged the object, but when I passed the data in the function and parsed the array, I got an undefined array. But if do a small edit (like a space) and save the file then the local server would rebuild and rerun the server then I would see all of the objects in the array (issue.value), I was wondering why this happen and is there a way to work around this?

start local server

small edit in code and save, local server rebuild with this

Vue single component

<template >

Machine

  <VueGoodTable
    class="issue-table m-0.5"
    v-bind:columns="headers"
    v-bind:rows="issue"
    v-bind:sort-options="{enabled: false}"
  >
    <template v-slot:table-row="props">
        <button
          class="
          px-3 py-1
          bg-gray-500
          text-white
          rounded-md
          text-sm hover:bg-black focus:outline-none"
          v-if="props.column.field == 'analysis'"
          v-bind:value="props.row.issue_id"
          v-on:click="onEdit"
        >
          Edit
        </button>
    </template>
  </VueGoodTable>

</template>

Body:
Please move this array to another script tag without setup attribute

 <script>
   const headers = [
    {
      label: 'Issue ID',
      field: 'issue_id',
    },
    {
      label: 'Part ID',
      field: 'part_id',
    },
    {
      label: 'Station ID',
      field: 'station_id',
    },
    {
      label: 'Description',
      field: 'description',
    },
    {
      label: 'Timestamp',
      field: 'timestamp',
    },
    {
      label: 'SN',
      field: 'serial_number',
    },
    {
      label: 'Failure Type',
      field: 'failure_type',
    },
    {
      label: 'Analysis',
      field: 'analysis'
    },
  ]
 </script>
 <script setup>
    ...
 </script>


问:
Advance year problem appear when plotting (pandas && matplotlib)
My problem is when I plot the users joining by day the advance year appear, it should not have year 2023. I tried to search it into my csv file and there is no row holding the value of 2023.

```<code>data = pd.read_csv('users-current.csv')

#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date

#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)

dataCreated.plot().invert_xaxis()
plt.title('Users Joining in a Day',pad=20, fontdict={'fontsize':24})
plt.show()
</code>```

the output:

column in my csv used below:

答:
This is because the range of x is automatically generated. Instead, you can explicitly limit a range of x using plt.xlim(), as follows:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import datetime

data = pd.read_csv('users-current.csv')

#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date

#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)

dataCreated.plot().invert_xaxis()

# import datetime, and use this code to set a period as you want.
plt.xlim([datetime.date(2021, 1, 1), datetime.date(2022, 12, 31)])

plt.title('Users Joining in a Day', pad=20, fontdict={'fontsize':24})
plt.show()
</code>```

Body:
My problem is when I plot the users joining by day the advance year appear, it should not have year 2023. I tried to search it into my csv file and there is no row holding the value of 2023.

data = pd.read_csv('users-current.csv')

#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date

#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)

dataCreated.plot().invert_xaxis()
plt.title('Users Joining in a Day',pad=20, fontdict={'fontsize':24})
plt.show()

the output:

column in my csv used below:

Body:
This is because the range of x is automatically generated. Instead, you can explicitly limit a range of x using plt.xlim(), as follows:

import pandas as pd
import matplotlib.pyplot as plt
import datetime

data = pd.read_csv('users-current.csv')

#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date

#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)

dataCreated.plot().invert_xaxis()

# import datetime, and use this code to set a period as you want.
plt.xlim([datetime.date(2021, 1, 1), datetime.date(2022, 12, 31)])

plt.title('Users Joining in a Day', pad=20, fontdict={'fontsize':24})
plt.show()


问:
How to pass type of combineReducers. Receiving error: Property '... does not exist on type 'Reducer<CombinedState{}
I am adding typeScript to my react/redux project. I am unable to load my app because I am receiving the error:

Here in index.tsx is where I combine my reducers and define type state:

```<code>import FormHandlerReducer from './FormHandler'
import { combineReducers} from 'redux';
import sideDrawerToggle from './sideDrawer'
import submitAlertReducer from './submitAlert'
import classesReducer from './classes'
import testReducer from './testList'
import studySessionReducer from './studySession'
import testGradeReducer from './testGradeHandler'
import homePageReducer from './homePageHandler'

const allReducers = combineReducers({studySessionReducer, FormHandlerReducer, sideDrawerToggle, submitAlertReducer, classesReducer, testReducer, testGradeReducer, homePageReducer})

export default allReducers
export type State = ReturnType<typeof allReducers>;
</code>```

Here is the file where I am trying to use the state

```<code>import React from 'react';
import './ShowStudySessions.css'
import { useSelector } from 'react-redux'
import State from '../../reducers'

interface ShowStudySession {
  studySessions:{
    classId: number,
    testId: number
  }
}

const ShowStudySession = ({studySessions}: ShowStudySession) => {
  const classId = studySessions.classId
  const testId = studySessions.testId
  const studySessionList = useSelector((state: typeof State) => state.studySessionReducer[classId][testId].studySessionList)
</code>```

答:
Maybe typo, you should use the type State = ReturnType<typeof allReducers>; in useSelector

reducers.ts:

```<code>import { combineReducers } from 'redux';

const studySessionReducer = () => {};

const allReducers = combineReducers({
  studySessionReducer,
});

export default allReducers;
export type State = ReturnType<typeof allReducers>;
</code>```

component.tsx:

```<code>import { useSelector } from 'react-redux';
import { State } from './reducers';

const ShowStudySession = ({ studySessions }) => {
  const classId = studySessions.classId;
  const testId = studySessions.testId;
  const studySessionList = useSelector((state: State) => state.studySessionReducer[classId][testId].studySessionList);

  return null;
};
</code>```

Body:
I am adding typeScript to my react/redux project. I am unable to load my app because I am receiving the error:

Here in index.tsx is where I combine my reducers and define type state:

import FormHandlerReducer from './FormHandler'
import { combineReducers} from 'redux';
import sideDrawerToggle from './sideDrawer'
import submitAlertReducer from './submitAlert'
import classesReducer from './classes'
import testReducer from './testList'
import studySessionReducer from './studySession'
import testGradeReducer from './testGradeHandler'
import homePageReducer from './homePageHandler'

const allReducers = combineReducers({studySessionReducer, FormHandlerReducer, sideDrawerToggle, submitAlertReducer, classesReducer, testReducer, testGradeReducer, homePageReducer})

export default allReducers
export type State = ReturnType<typeof allReducers>;

Here is the file where I am trying to use the state

import React from 'react';
import './ShowStudySessions.css'
import { useSelector } from 'react-redux'
import State from '../../reducers'

interface ShowStudySession {
  studySessions:{
    classId: number,
    testId: number
  }
}

const ShowStudySession = ({studySessions}: ShowStudySession) => {
  const classId = studySessions.classId
  const testId = studySessions.testId
  const studySessionList = useSelector((state: typeof State) => state.studySessionReducer[classId][testId].studySessionList)

Body:
Maybe typo, you should use the type State = ReturnType<typeof allReducers>; in useSelector

reducers.ts:

import { combineReducers } from 'redux';

const studySessionReducer = () => {};

const allReducers = combineReducers({
  studySessionReducer,
});

export default allReducers;
export type State = ReturnType<typeof allReducers>;

component.tsx:

import { useSelector } from 'react-redux';
import { State } from './reducers';

const ShowStudySession = ({ studySessions }) => {
  const classId = studySessions.classId;
  const testId = studySessions.testId;
  const studySessionList = useSelector((state: State) => state.studySessionReducer[classId][testId].studySessionList);

  return null;
};


问:
Speeding up derived feature calculation in Pandas dataframe
I have the following workflow in a Python notebook

Load data into a pandas dataframe from a table (around 200K rows) --> I will call this orig_DF moving forward

Manipulate orig_DF to get into a DF that has columns <Feature1, Feature 2,...,Feature N, Label> --> I will call this derived DF ```ML_input DF`` moving forward.  This DF is used to train a ML model</li>
<li>To get <code>ML_input DF</code>, I need to do some complex processing on each row in <code>orig_DF</code>. In particular, each row in <code>orig_DF</code> gets converted into multiple "rows" (number unknown before processing a row) in <code>ML_input DF</code></li>
</ol>
<p>Currently, I am doing (code below)</p>
<ol>
<li><code>orig_df.iterrows()</code> to loop through each row</li>
<li>Apply a function on each row. This returns a list.</li>
<li>Accumulate results from multiple rows into one list</li>
<li>Convert this list into <code>ML_input DF</code> after the loop ends</li>
</ol>
<p>This works but I want speed this up by parallelizing the work on each row and accumulating the results. Would appreciate pointers from Pandas experts on how to do this. An example would be greatly appreciated</p>
<p>Current code is below.</p>
<p>Note: I have looked into using <code>df.apply()</code>. But two issues seem to be</p>
<ol>
<li><code>apply</code> in itself does not seem to parallelize things.</li>
<li>I don't how to make apply handle this <code>one row converted to multiple row</code> issue (any pointers here will also help)</li>
</ol>
<p><strong>Current code</strong></p>
```def get_training_dataframe(dfin):
    X = []
    for index, row in dfin.iterrows():
        ts_frame_dict = ast.literal_eval(row["sample_dictionary"])
        for ts, frame in ts_frame_dict.items():
          features = get_features(frame)
          if features != None:
            X += [features]

   return pd.DataFrame(X, columns=FEATURE_NAMES)
```

答:
It's difficult to know what optimizations are possible without having example data and without knowing what get_features() does.

The following code ought to be equivalent (I think) to your code, but it attempts to "vectorize" each step instead of performing it all within the for-loop.  Perhaps that will offer you a chance to more easily measure the time taken by each step, and optimize the bottlenecks.

In particular, I wonder if it's faster to combine the calls to ast.literal_eval() into a single call.  That's what I've done here, but I have no idea if it's truly faster.

I recommend trying line profiler if you can.

```<code>import ast
import pandas as pd

def get_training_dataframe(dfin):
    frame_dicts = ast.literal_eval('[' + ','.join(dfin['sample_dictionary']) + ']')
    frames = chain(*(d.values() for d in frame_dicts))
    features = map(get_features, frames)
    features = [f for f in features if f is not None]
    return pd.DataFrame(features, columns=FEATURE_NAMES)
</code>```

Body:
I have the following workflow in a Python notebook

Load data into a pandas dataframe from a table (around 200K rows) --> I will call this orig_DF moving forward

Manipulate orig_DF to get into a DF that has columns <Feature1, Feature 2,...,Feature N, Label> --> I will call this derived DF ```ML_input DF`` moving forward.  This DF is used to train a ML model

To get ML_input DF, I need to do some complex processing on each row in orig_DF. In particular, each row in orig_DF gets converted into multiple "rows" (number unknown before processing a row) in ML_input DF

Currently, I am doing (code below)

orig_df.iterrows() to loop through each row

Apply a function on each row. This returns a list.

Accumulate results from multiple rows into one list

Convert this list into ML_input DF after the loop ends

This works but I want speed this up by parallelizing the work on each row and accumulating the results. Would appreciate pointers from Pandas experts on how to do this. An example would be greatly appreciated

Current code is below.

Note: I have looked into using df.apply(). But two issues seem to be

apply in itself does not seem to parallelize things.

I don't how to make apply handle this one row converted to multiple row issue (any pointers here will also help)

Current code

def get_training_dataframe(dfin):
    X = []
    for index, row in dfin.iterrows():
        ts_frame_dict = ast.literal_eval(row["sample_dictionary"])
        for ts, frame in ts_frame_dict.items():
          features = get_features(frame)
          if features != None:
            X += [features]

   return pd.DataFrame(X, columns=FEATURE_NAMES)

Body:
It's difficult to know what optimizations are possible without having example data and without knowing what get_features() does.

The following code ought to be equivalent (I think) to your code, but it attempts to "vectorize" each step instead of performing it all within the for-loop.  Perhaps that will offer you a chance to more easily measure the time taken by each step, and optimize the bottlenecks.

In particular, I wonder if it's faster to combine the calls to ast.literal_eval() into a single call.  That's what I've done here, but I have no idea if it's truly faster.

I recommend trying line profiler if you can.

import ast
import pandas as pd

def get_training_dataframe(dfin):
    frame_dicts = ast.literal_eval('[' + ','.join(dfin['sample_dictionary']) + ']')
    frames = chain(*(d.values() for d in frame_dicts))
    features = map(get_features, frames)
    features = [f for f in features if f is not None]
    return pd.DataFrame(features, columns=FEATURE_NAMES)


问:
Why is this dictionary not return length 1 for keys?
For a test that I'm writing, it's supposed to say that only one key has been returned, but instead I am getting that there are 2 keys. I know that the second key is checked.

How do I get to the point where it says there is only one key?

```<code>def testA2_check_980_ShouldErrWithOnlyOneKeyReturned(self):

        #    test 980:  exactly one key returned

        inputDict = {'op': 'check'}

        inputDict['cube'] = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
        expectedResult = 1

        actualResult = check._check(inputDict)
        self.assertEqual(expectedResult, len(actualResult))
</code>```

output : 1 != 2

答:
This line:

```<code>inputDict['cube'] = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
</code>```

inserts a key into inputDict, giving us a keyset with two keys: 'cube' and 'op'.

If you only want one key in the dictionary, either use del inputDict['op'] or don't insert the 'cube' key.

Body:
For a test that I'm writing, it's supposed to say that only one key has been returned, but instead I am getting that there are 2 keys. I know that the second key is checked.

How do I get to the point where it says there is only one key?

def testA2_check_980_ShouldErrWithOnlyOneKeyReturned(self):

        #    test 980:  exactly one key returned

        inputDict = {'op': 'check'}

        inputDict['cube'] = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
        expectedResult = 1

        actualResult = check._check(inputDict)
        self.assertEqual(expectedResult, len(actualResult))

output : 1 != 2

Body:
This line:

inputDict['cube'] = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'

inserts a key into inputDict, giving us a keyset with two keys: 'cube' and 'op'.

If you only want one key in the dictionary, either use del inputDict['op'] or don't insert the 'cube' key.


问:
Not able to load image in visual studio code for p5.js
I'm not able to load image in visual studio code for p5.js. How can I load image in p5.js?
I have created a new project but the images which I have loaded are not working so how can I do to run image in visual studio code for p5.js? Following the reference documents I added preload. You can see I also tried doing this with an image file and it produced the same results.</p>
```<code>var pic1;
var pic2;
var pic3;
var pic4;
var pic5;
var pic6;
let button;
let posX=0
let posY=0

let list;
let selectedItem = -1;
let drop = false;
let items = ["Apples", "Peaches", "Oranges", "Bananas", "Pears" ];
let itemY = [];

class List {

  constructor(x, y, w, h, itemH, txtSize) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.itemH = itemH;
    this.txtSize = txtSize;
    this.arrwX = this.x + this.w;
    this.arrwY = this.y;
    this.arrwH = this.h;
  }

  press(mx, my) {
    // arrow touches
    if ((mx >= this.arrwX) && (mx <= this.arrwX+this.arrwH) && (my >= this.arrwY) && (my <= this.arrwY+this.arrwH)) {
      if (drop == true) {
        drop = false;
      } else {
        drop = true;
      }
    } // list touches
    if (drop) {
      if (items.length > 0) {
        for (let j = 0; j < items.length; j++) {
          if ((mx >= this.x) && (mx <= this.x + this.w) && (my >= itemY[j] ) && (my <= itemY[j] + this.itemH)) {
            selectedItem = j;
            drop = false;
          }
        }
      }
    }
  }

  displayFieldString(title) {
    fill(255); // background color
    rect(this.x, this.y, this.w, this.h);
    fill(0); // text color
    textSize(this.txtSize);
    text(title, this.x + 10, this.y + this.txtSize);
  }

  display() {
    if (selectedItem == -1) {
      this.displayFieldString("Select item:");
    } else {
      this.displayFieldString(items[selectedItem]);
    }
    // arrow
    fill(255); // arrow background color
    rect(this.arrwX, this.arrwY, this.arrwH, this.arrwH);
    fill(0, 255, 0); // arrow color
    triangle(this.arrwX+5, this.arrwY+5, this.arrwX+this.arrwH-5, this.arrwY+5, this.arrwX+this.arrwH/2, this.arrwY+this.arrwH-5);
    // listItems
    if ((items.length > 0) && (drop)) {
      for (let j = 0; j < items.length; j++) {
        itemY[j] = (this.y + this.h) + j*this.itemH;
        fill(255);
        rect(this.x, itemY[j], this.w, this.itemH);
        fill(0);
        textSize(this.txtSize);
        text(items[j], this.x + 10, itemY[j] + this.txtSize);
      }
    }
    if (!drop) {
      rect(this.x, this.y + this.h, this.w, 0);
    }
  }
}

function setup() {
  createCanvas(500, 400);
  list = new List(100, 100, 120, 24, 24, 16);
}

function draw() {
  background(220);
  list.display();
}

function mousePressed() {
  //list.press(mouseX, mouseY);
}

const rightwall=350;
const height=450;
function preload(){
  pic1=loadImage("5.png")
  pic2=loadImage("Iron ore.jpg")
  pic4=loadImage("blastfurnace.jpg")
  pic5=loadImage("coal2.jpg")
  pic6=loadImage("limestone.jpg")
  pic3=loadImage("reactions.jpg")

}
function setup(){
  createCanvas(600,600);
  background("blue");
  button=createButton("CLICK TO LOAD INTO FURNACE")
  button.position(150,330);
  button.mousePressed(changeBG);

  noLoop();
}
function changeBG() {
  let val = random(65);
  background(val);
  loop();
  playAnim=true;
  draw();
  posX=0;
  posY=0;
  // background will be overwritten with 220
}

function draw() {
  background(220);
 // text(mouseX + "," + mouseY, 20, 20);
  // If the 'a' key is pressed, draw the following text in the canvas
if (key === 'a'){
  textSize(22);
  text('a key was pressed!', width / 2, height / 2);
}
  let s='BLAST FURNACE';
textSize(23);
fill(0,102,153);
 text(s,50, 10,300, 400);

  img1=image(pic1, 320, 30, 170,210)

  img6=image(pic6,posX,160,70,70)
  img2=image(pic2,posX, 80, 70, 70)

  img5=image(pic5,posX,20,50,50)
  img4=image(pic4,posX,posY-300,220,220)
 img3=image(pic3,20,340-posY,230, 230)
  if (playAnim) {
  posX=constrain(posX+1,0,rightwall-30)
  posY=constrain(posX-1,posY,height-50)
  }
}

</code>```

答:
Your file path is wrong:

p5.js says: It looks like there was a problem loading your image. Try checking if the file path (https://preview.p5js.org/limestone.jpg) is correct, hosting the file online, or running a local server. (More info at https://github.com/processing/p5.js/wiki/Local-server)

Body:
I'm not able to load image in visual studio code for p5.js. How can I load image in p5.js?
I have created a new project but the images which I have loaded are not working so how can I do to run image in visual studio code for p5.js? Following the reference documents I added preload. You can see I also tried doing this with an image file and it produced the same results.

var pic1;
var pic2;
var pic3;
var pic4;
var pic5;
var pic6;
let button;
let posX=0
let posY=0

let list;
let selectedItem = -1;
let drop = false;
let items = ["Apples", "Peaches", "Oranges", "Bananas", "Pears" ];
let itemY = [];

class List {

  constructor(x, y, w, h, itemH, txtSize) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.itemH = itemH;
    this.txtSize = txtSize;
    this.arrwX = this.x + this.w;
    this.arrwY = this.y;
    this.arrwH = this.h;
  }

  press(mx, my) {
    // arrow touches
    if ((mx >= this.arrwX) && (mx <= this.arrwX+this.arrwH) && (my >= this.arrwY) && (my <= this.arrwY+this.arrwH)) {
      if (drop == true) {
        drop = false;
      } else {
        drop = true;
      }
    } // list touches
    if (drop) {
      if (items.length > 0) {
        for (let j = 0; j < items.length; j++) {
          if ((mx >= this.x) && (mx <= this.x + this.w) && (my >= itemY[j] ) && (my <= itemY[j] + this.itemH)) {
            selectedItem = j;
            drop = false;
          }
        }
      }
    }
  }

  displayFieldString(title) {
    fill(255); // background color
    rect(this.x, this.y, this.w, this.h);
    fill(0); // text color
    textSize(this.txtSize);
    text(title, this.x + 10, this.y + this.txtSize);
  }

  display() {
    if (selectedItem == -1) {
      this.displayFieldString("Select item:");
    } else {
      this.displayFieldString(items[selectedItem]);
    }
    // arrow
    fill(255); // arrow background color
    rect(this.arrwX, this.arrwY, this.arrwH, this.arrwH);
    fill(0, 255, 0); // arrow color
    triangle(this.arrwX+5, this.arrwY+5, this.arrwX+this.arrwH-5, this.arrwY+5, this.arrwX+this.arrwH/2, this.arrwY+this.arrwH-5);
    // listItems
    if ((items.length > 0) && (drop)) {
      for (let j = 0; j < items.length; j++) {
        itemY[j] = (this.y + this.h) + j*this.itemH;
        fill(255);
        rect(this.x, itemY[j], this.w, this.itemH);
        fill(0);
        textSize(this.txtSize);
        text(items[j], this.x + 10, itemY[j] + this.txtSize);
      }
    }
    if (!drop) {
      rect(this.x, this.y + this.h, this.w, 0);
    }
  }
}

function setup() {
  createCanvas(500, 400);
  list = new List(100, 100, 120, 24, 24, 16);
}

function draw() {
  background(220);
  list.display();
}

function mousePressed() {
  //list.press(mouseX, mouseY);
}

const rightwall=350;
const height=450;
function preload(){
  pic1=loadImage("5.png")
  pic2=loadImage("Iron ore.jpg")
  pic4=loadImage("blastfurnace.jpg")
  pic5=loadImage("coal2.jpg")
  pic6=loadImage("limestone.jpg")
  pic3=loadImage("reactions.jpg")

}
function setup(){
  createCanvas(600,600);
  background("blue");
  button=createButton("CLICK TO LOAD INTO FURNACE")
  button.position(150,330);
  button.mousePressed(changeBG);

  noLoop();
}
function changeBG() {
  let val = random(65);
  background(val);
  loop();
  playAnim=true;
  draw();
  posX=0;
  posY=0;
  // background will be overwritten with 220
}

function draw() {
  background(220);
 // text(mouseX + "," + mouseY, 20, 20);
  // If the 'a' key is pressed, draw the following text in the canvas
if (key === 'a'){
  textSize(22);
  text('a key was pressed!', width / 2, height / 2);
}
  let s='BLAST FURNACE';
textSize(23);
fill(0,102,153);
 text(s,50, 10,300, 400);

  img1=image(pic1, 320, 30, 170,210)

  img6=image(pic6,posX,160,70,70)
  img2=image(pic2,posX, 80, 70, 70)

  img5=image(pic5,posX,20,50,50)
  img4=image(pic4,posX,posY-300,220,220)
 img3=image(pic3,20,340-posY,230, 230)
  if (playAnim) {
  posX=constrain(posX+1,0,rightwall-30)
  posY=constrain(posX-1,posY,height-50)
  }
}


问:
Creating a virtual directory failed with the error
I can't solve this problem

I suggest I have to change c:\Windows\System32\drivers\etc\hosts file and add after

```<code># localhost name resolution is handled within DNS itself.
</code>```

the next line:

```<code>127.0.0.1       mysite.dev
</code>```

but it doesn't help. Any suggestions?

Error ocсurrs when I try to open web site project in Microsoft Visual Studio 2012.

答:
simply fix for me

Close your Visual Studio

o remove .vs in .Net

o remove IISExpress in Documents

Reopen it, everything should be fine

Body:
I can't solve this problem

I suggest I have to change c:\Windows\System32\drivers\etc\hosts file and add after

# localhost name resolution is handled within DNS itself.

the next line:

127.0.0.1       mysite.dev

but it doesn't help. Any suggestions?

Error ocсurrs when I try to open web site project in Microsoft Visual Studio 2012.


问:
How to read object value from returned API response?
I have a web API that will validate a login from a client (console) and I want to retrieve the object (content) from the response returned from the console. Here is the snippet of the API code:

[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
    if (ModelState.IsValid)
    {
        var user = await this.userManager.FindByNameAsync(login.Username);
        if (user != null)
        {
            var passwordCheck = await this.signInManager.CheckPasswordSignInAsync(user, login.Password, false);
            if (passwordCheck.Succeeded)
            {
                var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.config["Tokens:Key"]));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    this.config["Tokens:Issuer"],
                    this.config["Tokens:Audience"],
                    claims,
                    expires: DateTime.UtcNow.AddHours(3),
                    signingCredentials: credentials
                    );

                return Ok(new
                {
                    Token = new JwtSecurityTokenHandler().WriteToken(token),
                    Expiration = token.ValidTo
                });
            }
            else
            {
                return Unauthorized("Wrong password or email!");
            }

        }
        else
        {
            return Unauthorized("Must not empty");
        }
    }

    return BadRequest();
}
```
<p>If I tried to test the call from Postman, it will get what I expected:</p>
<p><img src="https://i.stack.imgur.com/I4IoV.png" alt="This is the image" /></p>
<p>However, I don't know how to get the same result from the console app. Here is the code:</p>
<pre class="lang-cs prettyprint-override"><code>static async Task<JwtToken> Login()
{
    Login login = new();
    JwtToken token = null;
    Console.Write("Username: ");
    login.Username = Console.ReadLine();
    Console.Write("Password: ");
    login.Password = Console.ReadLine();
    HttpResponseMessage response = await client.PostAsJsonAsync("account/login", login);
    if (response.IsSuccessStatusCode)
    {
        token = await response.Content.ReadAsAsync<JwtToken>();
        Console.WriteLine("Token: {0}\nValid to: {1}",token.Token,token.Expiration);
        return token;
    }
    else
    {
        Console.WriteLine(response.StatusCode.ToString());
        return token;
    }

}
</code>```

And instead of the object, I will just get "BadRequest" or "Unauthorized". Thanks in advance if you can help me.

答:
As the response's content is a string, you can achieve by reading the response.Content as string:

var errorMessage = await response.Content.ReadAsAsync<string>();
```
<p>Place it in <code>else</code> statement.</p>
<pre class="lang-cs prettyprint-override"><code>else
{
    var errorMessage = await response.Content.ReadAsAsync<string>();
    Console.WriteLine(response.StatusCode.ToString());
    return token;
}
</code>```

Body:
I have a web API that will validate a login from a client (console) and I want to retrieve the object (content) from the response returned from the console. Here is the snippet of the API code:

[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
    if (ModelState.IsValid)
    {
        var user = await this.userManager.FindByNameAsync(login.Username);
        if (user != null)
        {
            var passwordCheck = await this.signInManager.CheckPasswordSignInAsync(user, login.Password, false);
            if (passwordCheck.Succeeded)
            {
                var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.config["Tokens:Key"]));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    this.config["Tokens:Issuer"],
                    this.config["Tokens:Audience"],
                    claims,
                    expires: DateTime.UtcNow.AddHours(3),
                    signingCredentials: credentials
                    );

                return Ok(new
                {
                    Token = new JwtSecurityTokenHandler().WriteToken(token),
                    Expiration = token.ValidTo
                });
            }
            else
            {
                return Unauthorized("Wrong password or email!");
            }

        }
        else
        {
            return Unauthorized("Must not empty");
        }
    }

    return BadRequest();
}

If I tried to test the call from Postman, it will get what I expected:

However, I don't know how to get the same result from the console app. Here is the code:

static async Task<JwtToken> Login()
{
    Login login = new();
    JwtToken token = null;
    Console.Write("Username: ");
    login.Username = Console.ReadLine();
    Console.Write("Password: ");
    login.Password = Console.ReadLine();
    HttpResponseMessage response = await client.PostAsJsonAsync("account/login", login);
    if (response.IsSuccessStatusCode)
    {
        token = await response.Content.ReadAsAsync<JwtToken>();
        Console.WriteLine("Token: {0}\nValid to: {1}",token.Token,token.Expiration);
        return token;
    }
    else
    {
        Console.WriteLine(response.StatusCode.ToString());
        return token;
    }

}

And instead of the object, I will just get "BadRequest" or "Unauthorized". Thanks in advance if you can help me.

Body:
As the response's content is a string, you can achieve by reading the response.Content as string:

var errorMessage = await response.Content.ReadAsAsync<string>();

Place it in else statement.

else
{
    var errorMessage = await response.Content.ReadAsAsync<string>();
    Console.WriteLine(response.StatusCode.ToString());
    return token;
}


问:
Testing arrow key keyboard navigation of a radio button group
I'm using testing-library to test an implementation of a radio button group. I can test that tab sets focus to the first radio option, but I can't get the arrow key navigation to test properly.

Here's the test I have:

import {
  getByLabelText,
  render,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
...

test('arrow key navigation', () => {
  const {container} = render(

        Apple
        <input type="radio" value="apple" id="apple" name="fruit"/>

        Banana
        <input type="radio" value="banana" id="banana" name="fruit"/>

  )

  const apple = getByLabelText(container, 'Apple')
  const banana = getByLabelText(container, 'Banana')

  userEvent.tab()
  expect(apple).toHaveFocus() // This assertion passes
  userEvent.keyboard('{arrowright}')
  expect(banana).toHaveFocus() // This assertion fails
})

```

答: I'm running into the same situation here, I found out the component didn't rerender which it should be, that's the reason why the test fail</p>


问:
Linking 2 tkinter GUI with a main file
I'm trying to link 2 tkinter file in a main file, I'm relatively quite new for python
When i try to run my main file my tkinter window does not pop out.
if i run individually it will run page2 instead of page 1
what is wrong inside here ?

Here is my main file

```<code>import page1w,page2w
from tkinter import *

def main():
    page1_window=page1w
    page2_window=page2w
</code>```

Here is my page 1 tkinter file

```<code>from tkinter import *
import page2w
root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1:")
l2=Label(root, text="Label2:")
l3=Label(root,text="Label 3")

#Input from above
e1=Entry(root)
e2=Entry(root)
e3=Entry(root)

#submit button
s1=Button(root,text='Submit',command=page2w)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
e1.grid(row=0,column=1,pady=2)
e2.grid(row=1,column=1,pady=2)
e3.grid(row=2,column=1,pady=2)
s1.grid(row=3,column=3,pady=2)

mainloop()
</code>```

here is my page 2 file

```<code>from tkinter import *

root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1 ")
l2=Label(root, text="Label2 ")
l3=Label(root,text="Label3")

#Pass & Fail Button
l1b=Button(root,text="PASS")
l2b=Button(root,text="PASS")
l3b=Button(root,text="PASS")
l1bf=Button(root,text="FAIL")
l2bf=Button(root,text="FAIL")
l3bf=Button(root,text="FAIL")

#Next button
s1=Button(root,text='Next',)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
l1b.grid(row=0,column=4,sticky=E)
l2b.grid(row=1,column=4,sticky=E)
l3b.grid(row=2,column=4,sticky=E)
l1bf.grid(row=0,column=5,sticky=E)
l2bf.grid(row=1,column=5,sticky=E)
l3bf.grid(row=2,column=5,sticky=E)
s1.grid(row=3,column=3,pady=2)

mainloop()
</code>```

i'm using python3.xx
what is a suitable way to link all tkinter gui & run in sequence order
say : page1w then page2 etc,etc

答:
For your case, you don't need the main file actually. Just run page1w.py as the main file and modify page1w.py as below:

from tkinter import *

def page2():
    # destroy current window
    root.destroy()
    # open page2 window
    import page2w

root=Tk()
...
s1=Button(root,text='Submit',command=page2)
...
mainloop()
```

Title: Linking 2 tkinter GUI with a main file

Body:
I'm trying to link 2 tkinter file in a main file, I'm relatively quite new for python
When i try to run my main file my tkinter window does not pop out.
if i run individually it will run page2 instead of page 1
what is wrong inside here ?

Here is my main file

import page1w,page2w
from tkinter import *

def main():
    page1_window=page1w
    page2_window=page2w

Here is my page 1 tkinter file

from tkinter import *
import page2w
root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1:")
l2=Label(root, text="Label2:")
l3=Label(root,text="Label 3")

#Input from above
e1=Entry(root)
e2=Entry(root)
e3=Entry(root)

#submit button
s1=Button(root,text='Submit',command=page2w)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
e1.grid(row=0,column=1,pady=2)
e2.grid(row=1,column=1,pady=2)
e3.grid(row=2,column=1,pady=2)
s1.grid(row=3,column=3,pady=2)

mainloop()

here is my page 2 file

from tkinter import *

root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1 ")
l2=Label(root, text="Label2 ")
l3=Label(root,text="Label3")

#Pass & Fail Button
l1b=Button(root,text="PASS")
l2b=Button(root,text="PASS")
l3b=Button(root,text="PASS")
l1bf=Button(root,text="FAIL")
l2bf=Button(root,text="FAIL")
l3bf=Button(root,text="FAIL")

#Next button
s1=Button(root,text='Next',)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
l1b.grid(row=0,column=4,sticky=E)
l2b.grid(row=1,column=4,sticky=E)
l3b.grid(row=2,column=4,sticky=E)
l1bf.grid(row=0,column=5,sticky=E)
l2bf.grid(row=1,column=5,sticky=E)
l3bf.grid(row=2,column=5,sticky=E)
s1.grid(row=3,column=3,pady=2)

mainloop()

i'm using python3.xx
what is a suitable way to link all tkinter gui & run in sequence order
say : page1w then page2 etc,etc


问:
How can I correctly set a Spring Security matcher to handle request containing an ID in the middle of the URI?
I am going crazy with the following Spring Security matcher expression.

I have this Controller class containing this API

```<code>@RestController
@RequestMapping("/api")
@Log
public class WalletController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private UserService userService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private ResourceBundleMessageSource errMessage;

    @ApiOperation(
              value = "Retrieve the wallets list of a specific user",
              notes = "Pass the user ID into the URL",
              produces = "application/json")
    @GetMapping(value = "/admin/user/{userID}/wallet", produces = "application/json")
    public ResponseEntity<List<WalletDTO>> getUserWalletsList(@PathVariable("userID") String userID) throws NotFoundException {

        log.info(String.format("****** Retrieve the list of wallets owned by the user: %s *******", userID));

        List<WalletDTO> walletsDTOList = this.walletService.getAllWalletsOfAnUser(Integer.parseInt(userID));

        return new ResponseEntity<List<WalletDTO>>(walletsDTOList, HttpStatus.OK);
    }

    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    OTHER APIs
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................

}
</code>```

As you can see this API handle GET call toward URI like this: http://localhost:8019/api/admin/user/54/wallet

Now I have the following matcher:

```<code>private static final String[] CLIENT_MATCHER = {

                                                    "/api/users/email/*",
                                                    "/api/admin/**",
                                                    "/api/admin/user/*/wallet/"
                                                };
</code>```

In this way a CLIENT user (having the appropriate authority into the JWT token) correctly retrieve the information from this API (the controller method is executed and return the expected output).

It works because there is this rule: "/api/admin/"** that allow call toward all the API having an endpoint starting with /api/admin/ folloeed by anything else (so something like http://localhost:8019/api/admin/user/54/wallet is perfectly allowed).

My problem is that I really don't want to give to this type of users (CLIENT users) the possibility to access to all my api starting with /api/admin/ but I need that a user like this have access to the previous endpoint.

So I changed the previous matcher in this way:

```<code>private static final String[] CLIENT_MATCHER = {

                                                    "/api/users/email/*",
                                                    "/api/admin/user/*/wallet"
                                                };
</code>```

Bascially I removed this rule:

```<code>"/api/admin/**",
</code>```

and I replaced with this one:

```<code>"/api/admin/user/*/wallet"
</code>```

I thought doing so this second version correctly matches request like http://localhost:8019/api/admin/user/54/wallet but it is not working. Calling my API with Postamn I am now obtaining this error message:

```<code>{
    "timestamp": "2022-02-10T23:21:47.994+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}
</code>```

答: put this expression -> "/api/admin/user/{userID}/wallet" in CLIENT_MATCHER</p>

Body:
I am going crazy with the following Spring Security matcher expression.

I have this Controller class containing this API

@RestController
@RequestMapping("/api")
@Log
public class WalletController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private UserService userService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private ResourceBundleMessageSource errMessage;

    @ApiOperation(
              value = "Retrieve the wallets list of a specific user",
              notes = "Pass the user ID into the URL",
              produces = "application/json")
    @GetMapping(value = "/admin/user/{userID}/wallet", produces = "application/json")
    public ResponseEntity<List<WalletDTO>> getUserWalletsList(@PathVariable("userID") String userID) throws NotFoundException {

        log.info(String.format("****** Retrieve the list of wallets owned by the user: %s *******", userID));

        List<WalletDTO> walletsDTOList = this.walletService.getAllWalletsOfAnUser(Integer.parseInt(userID));

        return new ResponseEntity<List<WalletDTO>>(walletsDTOList, HttpStatus.OK);
    }

    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    OTHER APIs
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................
    .............................................................................................................................................................................................................................................................

}

As you can see this API handle GET call toward URI like this: http://localhost:8019/api/admin/user/54/wallet

Now I have the following matcher:

private static final String[] CLIENT_MATCHER = {

                                                    "/api/users/email/*",
                                                    "/api/admin/**",
                                                    "/api/admin/user/*/wallet/"
                                                };

In this way a CLIENT user (having the appropriate authority into the JWT token) correctly retrieve the information from this API (the controller method is executed and return the expected output).

It works because there is this rule: "/api/admin/"** that allow call toward all the API having an endpoint starting with /api/admin/ folloeed by anything else (so something like http://localhost:8019/api/admin/user/54/wallet is perfectly allowed).

My problem is that I really don't want to give to this type of users (CLIENT users) the possibility to access to all my api starting with /api/admin/ but I need that a user like this have access to the previous endpoint.

So I changed the previous matcher in this way:

private static final String[] CLIENT_MATCHER = {

                                                    "/api/users/email/*",
                                                    "/api/admin/user/*/wallet"
                                                };

Bascially I removed this rule:

"/api/admin/**",

and I replaced with this one:

"/api/admin/user/*/wallet"

I thought doing so this second version correctly matches request like http://localhost:8019/api/admin/user/54/wallet but it is not working. Calling my API with Postamn I am now obtaining this error message:

{
    "timestamp": "2022-02-10T23:21:47.994+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}


问:
pymongo fetch data inside nested data
Mongodata

```<code>    [
    {
        "structure": [
        {
            "name": "some folder",
            "values": [
            {
                "report_name": "new report",
                "report_heading": "sjsdjjs",
                "background": "#fff",
                "grid": false,
                "datasource": "newa",
                "unique_report_name": "newreport"
            },
            {
                "report_name": "test vaga test",
                "report_heading": "bar sksk",
                "background": "#fff",
                "grid": false,
                "datasource": "dgr_data",
                "unique_report_name": "testvagatest"
            }
            ],
            "type": 1
        }
        ],
        "unique_report_id": 536862
    }
    ]
</code>```

query

```<code>query = mycol.find({"structure.values.unique_report_name": "testvagatest"})
res = json.loads(dumps(query))
</code>```

Here is the query i am using to fetch data by filtering unique_report_name inside nested data.
But it is not working.

I am using pymongo client to fetch data

```<code>    {
        "report_name": "test vaga test",
        "report_heading": "bar sksk",
        "background": "#fff",
        "grid": false,
        "datasource": "dgr_data",
        "unique_report_name": "testvagatest"
    }
</code>```

I am expecting above result.

Please take a look how can to achive this

答:
```<code>db.collection.aggregate([
  {
    "$match": {
      "structure.values.unique_report_name": "testvagatest"
    }
  },
  {
    "$unwind": "$structure"
  },
  {
    "$unwind": "$structure.values"
  },
  {
    "$match": {
      "structure.values.unique_report_name": "testvagatest"
    }
  },
  {
    "$replaceWith": "$structure.values"
  }
])
</code>```

mongoplayground

Title: pymongo fetch data inside nested data

Body:
Mongodata

    [
    {
        "structure": [
        {
            "name": "some folder",
            "values": [
            {
                "report_name": "new report",
                "report_heading": "sjsdjjs",
                "background": "#fff",
                "grid": false,
                "datasource": "newa",
                "unique_report_name": "newreport"
            },
            {
                "report_name": "test vaga test",
                "report_heading": "bar sksk",
                "background": "#fff",
                "grid": false,
                "datasource": "dgr_data",
                "unique_report_name": "testvagatest"
            }
            ],
            "type": 1
        }
        ],
        "unique_report_id": 536862
    }
    ]

query

query = mycol.find({"structure.values.unique_report_name": "testvagatest"})
res = json.loads(dumps(query))

Here is the query i am using to fetch data by filtering unique_report_name inside nested data.
But it is not working.

I am using pymongo client to fetch data

    {
        "report_name": "test vaga test",
        "report_heading": "bar sksk",
        "background": "#fff",
        "grid": false,
        "datasource": "dgr_data",
        "unique_report_name": "testvagatest"
    }

I am expecting above result.

Please take a look how can to achive this

Body:
db.collection.aggregate([
  {
    "$match": {
      "structure.values.unique_report_name": "testvagatest"
    }
  },
  {
    "$unwind": "$structure"
  },
  {
    "$unwind": "$structure.values"
  },
  {
    "$match": {
      "structure.values.unique_report_name": "testvagatest"
    }
  },
  {
    "$replaceWith": "$structure.values"
  }
])

mongoplayground


问:
How to refresh the web page when index changes without lagging the server
I would like to refresh my static web page running on apache when the index changes. I've already tried to use server-side events, where I had a PHP file checking if the index changed and if yes, it sent the event to the webpage. This works exactly how I want, but there is a problem. Because the page is used by a lot of people sometimes (tens or up to a hundred opened tabs), it quickly starts to spam many apache processes. Then, it reaches the limit, and the apache freezes.
The question is how to handle this. If a user closes the tab, the process is killed, however, if not, the apache freezes.

The PHP script looks like this (it is checking two things, first, if the file chenged, or second if the status is something. As I said, this works fine, the problem is its lagging the server):

```<code><?php
session_start();
session_write_close();
ignore_user_abort(false);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$filename = "index.html";
while(True){
    if ( connection_aborted() ){
        exit();
    }else{
        try{
            $string = file_get_contents("current_status.json");
            $json = json_decode($string, true);
            $pom1 = $json["state"];

            $t1 = shell_exec("date -r index.html");
            sleep(3);
            $pom2 = $json["state"];
            if($t1 != shell_exec("date -r index.html")) {
                sleep(2);
                echo "data: file changed \n\n";
            } else if($pom2=="ready") {
                sleep(2);
                echo "data: new shot available \n\n";
            } else {
                echo "heartbeat";
            }
            ob_flush();
            flush();
        }
        catch (\Error $e){
            echo "data: error, json not available \n\n";
        }
    }
}
ob_end_flush()
?>
</code>```

Then, there is a classical javascript function in the index file with event source on the PHP file.

My question is, how can I do this to not make apache crashing? Can I somehow set up SSE to handle it? I know I can allow more processes on apache, but my resources are limited.

Is there any other way how to do this? For example, live.js works as well, but the problem is the sam, a lot of processes when opened multiple times.

答:
Yes, I can see how this would put far more strain on your server than necessary.

What you should do is poll for changes from javascript.  You send an asynchronous request for the last time the index file changed from your javascript.  You do it once when the page loads and store the time.  Then you check again on an interval and compare the result with the first one.  If it changed you refresh the page.
The PHP script should get the last change date, output it and exit - no continuously running PHP scripts.

Here is what the PHP file should look like:

```<code><?php
    header('Content-type: text/plain');
    echo filemtime('index.html');
?>
</code>```

Keep this minimal.  The built in filemtime function is more efficient than running shell_exec commands.

Here is an example javascript:

```<code>chk_index_change_time(false);
function chk_index_change_time(last){
    fetch('http://yourdomain.com/yourpath/get_index_change_time.php')
        .then(res => res.text())
        .then((index_change_time) => {
            if ((false !== last) && (last != index_change_time)){
                location.reload();
            } else {
                setTimeout(chk_index_change_time, 3000, index_change_time);
            }
    });
}
</code>```

Feel free to error handling or whatever, but this will work.  I used a timeout here instead of interval so that if the server is slow the server response time doesn't come out of the 3 second delay.

Body:
I would like to refresh my static web page running on apache when the index changes. I've already tried to use server-side events, where I had a PHP file checking if the index changed and if yes, it sent the event to the webpage. This works exactly how I want, but there is a problem. Because the page is used by a lot of people sometimes (tens or up to a hundred opened tabs), it quickly starts to spam many apache processes. Then, it reaches the limit, and the apache freezes.
The question is how to handle this. If a user closes the tab, the process is killed, however, if not, the apache freezes.

The PHP script looks like this (it is checking two things, first, if the file chenged, or second if the status is something. As I said, this works fine, the problem is its lagging the server):

<?php
session_start();
session_write_close();
ignore_user_abort(false);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$filename = "index.html";
while(True){
    if ( connection_aborted() ){
        exit();
    }else{
        try{
            $string = file_get_contents("current_status.json");
            $json = json_decode($string, true);
            $pom1 = $json["state"];

            $t1 = shell_exec("date -r index.html");
            sleep(3);
            $pom2 = $json["state"];
            if($t1 != shell_exec("date -r index.html")) {
                sleep(2);
                echo "data: file changed \n\n";
            } else if($pom2=="ready") {
                sleep(2);
                echo "data: new shot available \n\n";
            } else {
                echo "heartbeat";
            }
            ob_flush();
            flush();
        }
        catch (\Error $e){
            echo "data: error, json not available \n\n";
        }
    }
}
ob_end_flush()
?>

Then, there is a classical javascript function in the index file with event source on the PHP file.

My question is, how can I do this to not make apache crashing? Can I somehow set up SSE to handle it? I know I can allow more processes on apache, but my resources are limited.

Is there any other way how to do this? For example, live.js works as well, but the problem is the sam, a lot of processes when opened multiple times.

Body:
Yes, I can see how this would put far more strain on your server than necessary.

What you should do is poll for changes from javascript.  You send an asynchronous request for the last time the index file changed from your javascript.  You do it once when the page loads and store the time.  Then you check again on an interval and compare the result with the first one.  If it changed you refresh the page.
The PHP script should get the last change date, output it and exit - no continuously running PHP scripts.

Here is what the PHP file should look like:

<?php
    header('Content-type: text/plain');
    echo filemtime('index.html');
?>

Keep this minimal.  The built in filemtime function is more efficient than running shell_exec commands.

Here is an example javascript:

chk_index_change_time(false);
function chk_index_change_time(last){
    fetch('http://yourdomain.com/yourpath/get_index_change_time.php')
        .then(res => res.text())
        .then((index_change_time) => {
            if ((false !== last) && (last != index_change_time)){
                location.reload();
            } else {
                setTimeout(chk_index_change_time, 3000, index_change_time);
            }
    });
}

Feel free to error handling or whatever, but this will work.  I used a timeout here instead of interval so that if the server is slow the server response time doesn't come out of the 3 second delay.


问:
Headless point cloud sampling with docker
Dockerfile:

```<code>FROM python:3.8.12-slim-buster
RUN apt-get update && apt-get install -y python-opengl wget
RUN pip install mesh-to-sdf
</code>```

Build this docker image. Let's name it test.

```<code>docker build -t test .
</code>```

Run and execute a container from this image.

```<code>docker run --name test -d -t test
docker exec -it test bash
</code>```

Inside the container, create the following 2 files, mesh.obj and convert.py. You could download them with the following commands:

```<code>wget https://gist.githubusercontent.com/zshyang/9f4b18dea65ac5bba61a7fc2bbd98aa4/raw/9e681e2f9fa1bb3682fe8c95d8341b5b1e0f798a/mesh.obj
wget https://gist.githubusercontent.com/zshyang/4cf826bc16c05038c2b4529422b82484/raw/4127b8a0d443e0f257a162a9b3278595ac94ea76/convert.py
</code>```
```<code>f 1 2 3
v 1 1 1
v 1 2 3
v 1 9 0
</code>```
```<code>import trimesh
import mesh_to_sdf
mesh = trimesh.load('mesh.obj')
mesh_to_sdf.sample_sdf_near_surface(mesh, number_of_points = 500000, surface_point_method='scan', sign_method='normal', scan_count=100, scan_resolution=400, sample_point_count=10000000, normal_sample_count=11, min_size=0, return_gradients=False)
</code>```

Then by running python convert.py I get the following error.

```<code>Traceback (most recent call last):
  File "convert.py", line 4, in <module>
    mesh_to_sdf.sample_sdf_near_surface(mesh, number_of_points = 500000, surface_point_method='scan', sign_method='normal', scan_count=100, scan_resolution=400, sample_point_count=10000000, normal_sample_count=11, min_size=0, return_gradients=False)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/__init__.py", line 59, in sample_sdf_near_surface
    surface_point_cloud = get_surface_point_cloud(mesh, surface_point_method, 1, scan_count, scan_resolution, sample_point_count, calculate_normals=sign_method=='normal' or return_gradients)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/__init__.py", line 17, in get_surface_point_cloud
    return surface_point_cloud.create_from_scans(mesh, bounding_radius=bounding_radius, scan_count=scan_count, scan_resolution=scan_resolution, calculate_normals=calculate_normals)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/surface_point_cloud.py", line 162, in create_from_scans
    scans.append(Scan(mesh,
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/scan.py", line 61, in __init__
    color, depth = render_normal_and_depth_buffers(mesh, camera, self.camera_transform, resolution)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/pyrender_wrapper.py", line 58, in render_normal_and_depth_buffers
    renderer = pyrender.OffscreenRenderer(resolution, resolution)
  File "/usr/local/lib/python3.8/site-packages/pyrender/offscreen.py", line 31, in __init__
    self._create()
  File "/usr/local/lib/python3.8/site-packages/pyrender/offscreen.py", line 149, in _create
    self._platform.init_context()
  File "/usr/local/lib/python3.8/site-packages/pyrender/platforms/pyglet_platform.py", line 50, in init_context
    self._window = pyglet.window.Window(config=conf, visible=False,
  File "/usr/local/lib/python3.8/site-packages/pyglet/window/xlib/__init__.py", line 171, in __init__
    super(XlibWindow, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/pyglet/window/__init__.py", line 590, in __init__
    display = pyglet.canvas.get_display()
  File "/usr/local/lib/python3.8/site-packages/pyglet/canvas/__init__.py", line 94, in get_display
    return Display()
  File "/usr/local/lib/python3.8/site-packages/pyglet/canvas/xlib.py", line 123, in __init__
    raise NoSuchDisplayException('Cannot connect to "%s"' % name)
pyglet.canvas.xlib.NoSuchDisplayException: Cannot connect to "None"
</code>```

Do you konw anyway to solve this problem? Thanks!

答:
To get past the particular error you're getting, you have to set up a display for GL to use.  A simple way to do that is with Xvfb.

Add this line to your Dockerfile:

```<code>RUN apt-get install -y xvfb
</code>```

Then, in the container, before you run your script, run these commands to create an offscreen display buffer and set the DISPLAY env var to point to it:

```<code>Xvfb :1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset &> xvfb.log &
export DISPLAY=:1
</code>```

When I do this and then run your code, I get a new error:

```<code>pyglet.gl.ContextException: Could not create GL context
</code>```

I did some Googling and tried some things, but couldn't find an easy way to get past this error.  Threads I found surrounding this error message talked about two things: bugs in library code and GL versions.  I would suggest that if/when you get that error message, you Google it and look at what you get to see if you can figure out what you need to do next.

Best of luck!

Body:
Dockerfile:

FROM python:3.8.12-slim-buster
RUN apt-get update && apt-get install -y python-opengl wget
RUN pip install mesh-to-sdf

Build this docker image. Let's name it test.

docker build -t test .

Run and execute a container from this image.

docker run --name test -d -t test
docker exec -it test bash

Inside the container, create the following 2 files, mesh.obj and convert.py. You could download them with the following commands:

wget https://gist.githubusercontent.com/zshyang/9f4b18dea65ac5bba61a7fc2bbd98aa4/raw/9e681e2f9fa1bb3682fe8c95d8341b5b1e0f798a/mesh.obj
wget https://gist.githubusercontent.com/zshyang/4cf826bc16c05038c2b4529422b82484/raw/4127b8a0d443e0f257a162a9b3278595ac94ea76/convert.py

f 1 2 3
v 1 1 1
v 1 2 3
v 1 9 0

import trimesh
import mesh_to_sdf
mesh = trimesh.load('mesh.obj')
mesh_to_sdf.sample_sdf_near_surface(mesh, number_of_points = 500000, surface_point_method='scan', sign_method='normal', scan_count=100, scan_resolution=400, sample_point_count=10000000, normal_sample_count=11, min_size=0, return_gradients=False)

Then by running python convert.py I get the following error.

Traceback (most recent call last):
  File "convert.py", line 4, in <module>
    mesh_to_sdf.sample_sdf_near_surface(mesh, number_of_points = 500000, surface_point_method='scan', sign_method='normal', scan_count=100, scan_resolution=400, sample_point_count=10000000, normal_sample_count=11, min_size=0, return_gradients=False)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/__init__.py", line 59, in sample_sdf_near_surface
    surface_point_cloud = get_surface_point_cloud(mesh, surface_point_method, 1, scan_count, scan_resolution, sample_point_count, calculate_normals=sign_method=='normal' or return_gradients)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/__init__.py", line 17, in get_surface_point_cloud
    return surface_point_cloud.create_from_scans(mesh, bounding_radius=bounding_radius, scan_count=scan_count, scan_resolution=scan_resolution, calculate_normals=calculate_normals)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/surface_point_cloud.py", line 162, in create_from_scans
    scans.append(Scan(mesh,
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/scan.py", line 61, in __init__
    color, depth = render_normal_and_depth_buffers(mesh, camera, self.camera_transform, resolution)
  File "/usr/local/lib/python3.8/site-packages/mesh_to_sdf/pyrender_wrapper.py", line 58, in render_normal_and_depth_buffers
    renderer = pyrender.OffscreenRenderer(resolution, resolution)
  File "/usr/local/lib/python3.8/site-packages/pyrender/offscreen.py", line 31, in __init__
    self._create()
  File "/usr/local/lib/python3.8/site-packages/pyrender/offscreen.py", line 149, in _create
    self._platform.init_context()
  File "/usr/local/lib/python3.8/site-packages/pyrender/platforms/pyglet_platform.py", line 50, in init_context
    self._window = pyglet.window.Window(config=conf, visible=False,
  File "/usr/local/lib/python3.8/site-packages/pyglet/window/xlib/__init__.py", line 171, in __init__
    super(XlibWindow, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/pyglet/window/__init__.py", line 590, in __init__
    display = pyglet.canvas.get_display()
  File "/usr/local/lib/python3.8/site-packages/pyglet/canvas/__init__.py", line 94, in get_display
    return Display()
  File "/usr/local/lib/python3.8/site-packages/pyglet/canvas/xlib.py", line 123, in __init__
    raise NoSuchDisplayException('Cannot connect to "%s"' % name)
pyglet.canvas.xlib.NoSuchDisplayException: Cannot connect to "None"

Do you konw anyway to solve this problem? Thanks!

Body:
To get past the particular error you're getting, you have to set up a display for GL to use.  A simple way to do that is with Xvfb.

Add this line to your Dockerfile:

RUN apt-get install -y xvfb

Then, in the container, before you run your script, run these commands to create an offscreen display buffer and set the DISPLAY env var to point to it:

Xvfb :1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset &> xvfb.log &
export DISPLAY=:1

When I do this and then run your code, I get a new error:

pyglet.gl.ContextException: Could not create GL context

I did some Googling and tried some things, but couldn't find an easy way to get past this error.  Threads I found surrounding this error message talked about two things: bugs in library code and GL versions.  I would suggest that if/when you get that error message, you Google it and look at what you get to see if you can figure out what you need to do next.

Best of luck!


问:
How to allow user www-data use sudo commands without password
I want to allow run specify command on my website, through PHP exec() function, so i found the way, to add www-data in sudoers.d files to allow run specify commands without asking password.

I tried next things:

check where is program catalogue
whereis hashcat -> hashcat: /usr/bin/hashcat

Add a new file to sudo visudo /etc/sudoers.d/www-data and add next line www-data ALL=(www-data:www-data)NOPASSWD: /user/bin/hashcat

Try to run it through www-data: sudo -u www-data sudo hashcat
And then i get this: [sudo] password for www-data:, that means it doesn't seems to work

What can i do wrong, and what i should do then? And is my decision to do so correct? Is there a better and safer solution?

答:
That problem is solved, by removing the (www-data:www-data) so my "www-data: file in sudoers.d looks like: www-data ALL=NOPASSWD: /usr/bin/hashcat
Thanks all for answering and give me a hint to solve this! Especially thanks to @cyberbrain for my carelessness!


问:
Why do the contents in a Bootstrap grid float left? Is there a way to get the contents in a Bootstrap grid to be in the center?
I have tried using text-align: center;, but this does not change the text inside of the Bootstrap grid. Is the float-left the default setting or is there a way I can change it? My code looks something like this:

```<code>    <div style="margin-top: 10px; margin-bottom: 20px; margin-right: 20%; margin-left: 20%; text-align: center; font-family: 'Share Tech Mono', monospace; background-color: white;   border-radius: 50px;">
        <h1 style="padding-top: 10px;">Code Example</h1>
        <br>
        <br>
        <div class="row">
            <div class="col-sm-4 "><a style="color: black;">Column 1</a></div>
            <div class="col-sm-4"><a style="color: black;">Column 2</a></div>
            <div class="col-sm-4"><a style="color: black;">Column 3</a></div>
        <div style="height: 50px;"></div>

        </div>
    </div>

</code>```

答:
CSS Copy-paste the stylesheet  into your  before all other stylesheets to load our CSS.
''''''
if you are missing this link please add .I hope it will work.</p>

Body:
I have tried using text-align: center;, but this does not change the text inside of the Bootstrap grid. Is the float-left the default setting or is there a way I can change it? My code looks something like this:

Code Example

Column 1

Column 2

Column 3


问:
Change password using AWS.CognitoIdentityServiceProvider
I'm trying to figure out how to use the changePassword function of the AWS.CognitoIdentityServiceProvider.

I need to pass the following as params:

```<code>{
  PreviousPassword: 'STRING_VALUE', /* required */
  ProposedPassword: 'STRING_VALUE', /* required */
  AccessToken: 'STRING_VALUE'
}
</code>```

I use this inside a Lambda function, so how do I get hold of the access token? I have the cognitoIdentityPoolId and the cognitoIdentityId to use, but I can't understand which this access token is.

答:
I would like to extend on some answers above with a solution that can be used inside the lambda function and also shows how to set the authentication required (using an AWS access key and secret access key.

This is a worked example of a "change password" function created as a lambda.

```<code>export async function  change_password (event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;
  try {
    const { aws_cognito_id, newPassword } = JSON.parse(event.body)
    const cognitoIdentityService = new AWS.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18', region: '***AWS REGION GOES HERE***' });
    const userPoolId = "***COGNITO USER POOL ID GOES HERE***";
    const params = {
        Password: newPassword,
        Permanent: true,
        Username: aws_cognito_id,
        UserPoolId: userPoolId
    };
    AWS.config.region = '**AWS REGION**';
    cognitoIdentityService.config.update({
       accessKeyId: '***AWS ACCESS KEY***',
       secretAccessKey: '***AWS SECRET ACCESS KEY***'
    })
    let result = await cognitoIdentityService.adminSetUserPassword(params).promise();
    return generate_response(200, result)
  } catch (err) {
    return generate_error(500, err.message)
  }
}
</code>```

Body:
I'm trying to figure out how to use the changePassword function of the AWS.CognitoIdentityServiceProvider.

I need to pass the following as params:

{
  PreviousPassword: 'STRING_VALUE', /* required */
  ProposedPassword: 'STRING_VALUE', /* required */
  AccessToken: 'STRING_VALUE'
}

I use this inside a Lambda function, so how do I get hold of the access token? I have the cognitoIdentityPoolId and the cognitoIdentityId to use, but I can't understand which this access token is.

Body:
I would like to extend on some answers above with a solution that can be used inside the lambda function and also shows how to set the authentication required (using an AWS access key and secret access key.

This is a worked example of a "change password" function created as a lambda.

export async function  change_password (event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;
  try {
    const { aws_cognito_id, newPassword } = JSON.parse(event.body)
    const cognitoIdentityService = new AWS.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18', region: '***AWS REGION GOES HERE***' });
    const userPoolId = "***COGNITO USER POOL ID GOES HERE***";
    const params = {
        Password: newPassword,
        Permanent: true,
        Username: aws_cognito_id,
        UserPoolId: userPoolId
    };
    AWS.config.region = '**AWS REGION**';
    cognitoIdentityService.config.update({
       accessKeyId: '***AWS ACCESS KEY***',
       secretAccessKey: '***AWS SECRET ACCESS KEY***'
    })
    let result = await cognitoIdentityService.adminSetUserPassword(params).promise();
    return generate_response(200, result)
  } catch (err) {
    return generate_error(500, err.message)
  }
}


问:
How to show filtered logs on GCP Monitoring Dashboard
On the Google Cloud monitoring mosaic, we have a card that shows logs.  It's able to pre-filter on several fiels, for example the severity field screens logs below warning level as shown below.  Is there a similar way filter on text?  For example, I want the dashbaord to show only logs that match the text string "foobar".  I've tried adding textPayload="foobar" to the Query Editor to no avail.  Is this possible?

答:
Based on Sample queries using the Logs Explorer Docs.

Container error logs for a specific pod containing a POST in the textPayload

```<code>resource.type="k8s_container" AND
resource.labels.pod_name="POD_NAME" AND
textPayload:"POST" AND
severity=ERROR
</code>```

You can also check the dropdown of error logs to see the code and copy the line to Query Editor for more filter options

You can check also Logging Query Language for reference

Body:
Based on Sample queries using the Logs Explorer Docs.

Container error logs for a specific pod containing a POST in the textPayload

resource.type="k8s_container" AND
resource.labels.pod_name="POD_NAME" AND
textPayload:"POST" AND
severity=ERROR

You can also check the dropdown of error logs to see the code and copy the line to Query Editor for more filter options

You can check also Logging Query Language for reference