问:
Return results a table in specific formats
I am performing a SQL challenge and having a difficult time figuring out what I'm doing wrong. The challenge exists in Jupiter Notebook and I can run the query for results, but when submitting the query to be checked to see if I get the final answer correct I get "Results do not match answer".

The Instructions and code are below;

/*
INSTRUCTIONS
Your query will need to return a table containing the columns described in the notebook,
meeting all conditions listed and using the aliases specified.

Online News Exhibition
Following the changes in working habits during the COVID pandemic, your local library has
decided it is time to make the newspaper archives available online. They are not sure what
the response will be so they are going to trial a new system on a small set of their data.

The library database has a table articles with a record of all articles published in the newspaper.
However, the table will need some preparation before the library can use it in the new system.
They would like to focus the initial trial on articles from 2014 and 2015 only, and for just one
journalist whose ID in the database is 1754.

The final results should be sorted from earliest published date to the most recent published date.
Below are the requirements the library has given to you for the data they need.

Requirement - Unique ID of each article, where the first 4 digits represents the journalist ID.
Data Type - TEXT

Alias - article_key

Requirement - Category of the article, in uppercase. 'Food & Drink' and 'Wellness' should be collapsed into a 'Lifestyle' category.
Data Type - TEXT

Alias - category

Requirement - Headline of the article, without the subtitle that appears after the colon (:). For example, 'It Could Happen To You: A Story of SEC Overreach' becomes 'It Could Happen To You'.
Data Type - TEXT

Alias - headline

Requirement - Subtitles of the article, without the headline that appears before the colon (:). For example, 'It Could Happen to You: A Story of SEC Overreach' becomes 'A Story of SEC Overreach'. In cases where a headline does not have a subtitle, the missing value should read ‘None’.

Data Type - TEXT

Alias - subtitle

Requirement - Description of the article. The description should be reduced to the first sentence, up to and including the first period (.) from the short_description column.

Data Type - TEXT

Alias - description

Requirement - Keywords of the article. Multiple keywords will be seperated with a dash (-). If the keyword is missing, the value should read ‘Unknown’.
Data Type - TEXT

Alias - keywords

Requirement - Date the article was published. The data should be displayed in the format resembling the following: ‘Aug 13, 1995’.

Data Type - TEXT

Alias - publish_date

*/
%%sql
postgresql:///articles

```<code>SELECT

CAST(article_key as TEXT) article_key

,CAST(UPPER(CASE
       WHEN category IN ('FOOD & DRINK','WELLNESS') THEN 'LIFESTYLE'
       ELSE category
       END) as TEXT) category

,CAST(CASE
    WHEN headline LIKE '%:%' THEN LEFT(headline,STRPOS(headline,':')-1)
    ELSE headline
    END as TEXT) headline

,CAST(CASE
    WHEN headline LIKE '%:%' THEN RIGHT(headline,CHAR_LENGTH(headline)-STRPOS(headline,':'))
    ELSE 'None'
    END as TEXT) subtitle

,CAST(LEFT(short_description,STRPOS(short_description,'.')) as TEXT) description

,CAST(CASE
    WHEN keywords LIKE 'None' THEN 'Unknown'
    ELSE keywords
    END as TEXT) keywords

,CAST(TO_CHAR(release_date::date,'Mon dd, yyyy') as TEXT) publish_date

FROM articles

WHERE
LEFT(article_key,4) LIKE '1754'
AND (LEFT(release_date,4) LIKE '2014' OR LEFT(release_date,4) LIKE '2015')

ORDER BY release_date
</code>```

答:
```<code>SELECT
    CAST(article_key AS TEXT) as article_key,
    CASE
        WHEN category = 'FOOD & DRINK' or category = 'WELLNESS'
        THEN 'LIFESTYLE'
        ELSE category
        END as category,
    CASE
        WHEN headline NOT LIKE '%:%' THEN headline
        ELSE TRIM(SUBSTRING(headline,0,STRPOS(headline,':')))
        END as headline,
    CASE
        WHEN headline NOT LIKE '%:%' THEN 'None'
        ELSE TRIM(SUBSTRING(headline, STRPOS(headline,':') + 1))
        END as subtitle,
    TRIM(SUBSTRING(short_description,0,STRPOS(short_description,'.')+ 1)) as description,
    CASE
        WHEN keywords IS NULL
        THEN 'Unknown'
        ELSE keywords
        END AS keywords,
    to_char(to_date(release_date, 'YYYY MM DD'), 'Mon DD, YYYY') as publish_date
FROM articles
WHERE SUBSTRING(article_key, 1, 4) = '1754'
    AND (release_date LIKE '%2014%' or release_date LIKE '%2015%')
ORDER BY release_date
</code>```

Body:
I am performing a SQL challenge and having a difficult time figuring out what I'm doing wrong. The challenge exists in Jupiter Notebook and I can run the query for results, but when submitting the query to be checked to see if I get the final answer correct I get "Results do not match answer".

The Instructions and code are below;

/*
INSTRUCTIONS
Your query will need to return a table containing the columns described in the notebook,
meeting all conditions listed and using the aliases specified.

Online News Exhibition
Following the changes in working habits during the COVID pandemic, your local library has
decided it is time to make the newspaper archives available online. They are not sure what
the response will be so they are going to trial a new system on a small set of their data.

The library database has a table articles with a record of all articles published in the newspaper.
However, the table will need some preparation before the library can use it in the new system.
They would like to focus the initial trial on articles from 2014 and 2015 only, and for just one
journalist whose ID in the database is 1754.

The final results should be sorted from earliest published date to the most recent published date.
Below are the requirements the library has given to you for the data they need.

Requirement - Unique ID of each article, where the first 4 digits represents the journalist ID.
Data Type - TEXT

Alias - article_key

Requirement - Category of the article, in uppercase. 'Food & Drink' and 'Wellness' should be collapsed into a 'Lifestyle' category.
Data Type - TEXT

Alias - category

Requirement - Headline of the article, without the subtitle that appears after the colon (:). For example, 'It Could Happen To You: A Story of SEC Overreach' becomes 'It Could Happen To You'.
Data Type - TEXT

Alias - headline

Requirement - Subtitles of the article, without the headline that appears before the colon (:). For example, 'It Could Happen to You: A Story of SEC Overreach' becomes 'A Story of SEC Overreach'. In cases where a headline does not have a subtitle, the missing value should read ‘None’.

Data Type - TEXT

Alias - subtitle

Requirement - Description of the article. The description should be reduced to the first sentence, up to and including the first period (.) from the short_description column.

Data Type - TEXT

Alias - description

Requirement - Keywords of the article. Multiple keywords will be seperated with a dash (-). If the keyword is missing, the value should read ‘Unknown’.
Data Type - TEXT

Alias - keywords

Requirement - Date the article was published. The data should be displayed in the format resembling the following: ‘Aug 13, 1995’.

Data Type - TEXT

Alias - publish_date

*/
%%sql
postgresql:///articles

SELECT

CAST(article_key as TEXT) article_key

,CAST(UPPER(CASE
       WHEN category IN ('FOOD & DRINK','WELLNESS') THEN 'LIFESTYLE'
       ELSE category
       END) as TEXT) category

,CAST(CASE
    WHEN headline LIKE '%:%' THEN LEFT(headline,STRPOS(headline,':')-1)
    ELSE headline
    END as TEXT) headline

,CAST(CASE
    WHEN headline LIKE '%:%' THEN RIGHT(headline,CHAR_LENGTH(headline)-STRPOS(headline,':'))
    ELSE 'None'
    END as TEXT) subtitle

,CAST(LEFT(short_description,STRPOS(short_description,'.')) as TEXT) description

,CAST(CASE
    WHEN keywords LIKE 'None' THEN 'Unknown'
    ELSE keywords
    END as TEXT) keywords

,CAST(TO_CHAR(release_date::date,'Mon dd, yyyy') as TEXT) publish_date

FROM articles

WHERE
LEFT(article_key,4) LIKE '1754'
AND (LEFT(release_date,4) LIKE '2014' OR LEFT(release_date,4) LIKE '2015')

ORDER BY release_date


来源: stackexchange

问:
Vue Watcher not working on component created with Vue.extend
I have a Parent component with a select input which is bound through v-model to a variable in data.

Besides, I create child components dynamically using Vue.extend, which i pass the propsData which also includes the value of the select.

This components have a watcher for the prop that is related to the select input.

When i create the component it receives the props succesfully, The problem comes when I update the value of the select input that doesn't trigger the watcher on the child component.

I've been looking for similar situations but have not found something that helps me solve this problem, i don't know why it doesn't trigger the watcher on the child component when the select input changes.

Any help would be very preciated.

Here i create the component dynamically:

```<code>let PresupuestoFormularioVue = Vue.extend(PresupuestoFormulario)
let instance = new PresupuestoFormularioVue({
  propsData: {
    //The prop related to select input
    seguro: this.seguro,
  }
})
instance.$mount()
this.$refs.formularioContenedor.appendChild(instance.$el)
</code>```

And this is the watcher in the component which isn't working:

```<code>watch:{
  seguro:{
    handler: function( newVal ){
      console.log(newVal)
    },
  },
},
</code>```

答:
All of props that you want check in watcher, should be a function. If you want read more about this go to vue document codegrepper.</p>
```<code>watch: {
    // whenever seguro changes, this function will run
    seguro: function (newValue, oldValue) {
        console.log(newValue,oldValue)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Parent component with a select input which is bound through v-model to a variable in data.

Besides, I create child components dynamically using Vue.extend, which i pass the propsData which also includes the value of the select.

This components have a watcher for the prop that is related to the select input.

When i create the component it receives the props succesfully, The problem comes when I update the value of the select input that doesn't trigger the watcher on the child component.

I've been looking for similar situations but have not found something that helps me solve this problem, i don't know why it doesn't trigger the watcher on the child component when the select input changes.

Any help would be very preciated.

Here i create the component dynamically:

let PresupuestoFormularioVue = Vue.extend(PresupuestoFormulario)
let instance = new PresupuestoFormularioVue({
  propsData: {
    //The prop related to select input
    seguro: this.seguro,
  }
})
instance.$mount()
this.$refs.formularioContenedor.appendChild(instance.$el)

And this is the watcher in the component which isn't working:

watch:{
  seguro:{
    handler: function( newVal ){
      console.log(newVal)
    },
  },
},

Body:
All of props that you want check in watcher, should be a function. If you want read more about this go to vue document codegrepper.

watch: {
    // whenever seguro changes, this function will run
    seguro: function (newValue, oldValue) {
        console.log(newValue,oldValue)
    }
}


问:
Are tuples, list, dictonaries, sets objects of the same class?
I'm learning python online on my own, and I was reading about iterators when this question came out.

Are all iterators objects of one unique class in python, where this class has all the lists, sets, tuple methods?

答:
No, iterators are not all instances of the same class (except in the trivial sense that they are all instances of the base class object). You can verify this using the type function on many different iterators; most standard container types and other iterable types built into the language have their own iterator classes.

>>> iterables = [list(), tuple(), set(), frozenset(), dict(), dict().values(), str(), range(1)]
>>> for c in iterables:
...     print(type(c), 'has iterator type', type(iter(c)))
...
<class 'list'> has iterator type <class 'list_iterator'>
<class 'tuple'> has iterator type <class 'tuple_iterator'>
<class 'set'> has iterator type <class 'set_iterator'>
<class 'frozenset'> has iterator type <class 'set_iterator'>
<class 'dict'> has iterator type <class 'dict_keyiterator'>
<class 'dict_values'> has iterator type <class 'dict_valueiterator'>
<class 'str'> has iterator type <class 'str_iterator'>
<class 'range'> has iterator type <class 'range_iterator'>
```

This works because all of the different iterator classes implement the iterator protocol, and Python uses duck typing which means Python code generally doesn't check that objects are instances of the "correct" class, instead it just uses those objects in a certain way and it works as long as those objects have the right attributes and methods to be used in that way (i.e. if they waddle like a duck and quack like a duck...).

Body:
No, iterators are not all instances of the same class (except in the trivial sense that they are all instances of the base class object). You can verify this using the type function on many different iterators; most standard container types and other iterable types built into the language have their own iterator classes.

>>> iterables = [list(), tuple(), set(), frozenset(), dict(), dict().values(), str(), range(1)]
>>> for c in iterables:
...     print(type(c), 'has iterator type', type(iter(c)))
...
<class 'list'> has iterator type <class 'list_iterator'>
<class 'tuple'> has iterator type <class 'tuple_iterator'>
<class 'set'> has iterator type <class 'set_iterator'>
<class 'frozenset'> has iterator type <class 'set_iterator'>
<class 'dict'> has iterator type <class 'dict_keyiterator'>
<class 'dict_values'> has iterator type <class 'dict_valueiterator'>
<class 'str'> has iterator type <class 'str_iterator'>
<class 'range'> has iterator type <class 'range_iterator'>

This works because all of the different iterator classes implement the iterator protocol, and Python uses duck typing which means Python code generally doesn't check that objects are instances of the "correct" class, instead it just uses those objects in a certain way and it works as long as those objects have the right attributes and methods to be used in that way (i.e. if they waddle like a duck and quack like a duck...).


问:
How can you customize all elements in a table header?
Looking at the examples on this page, what is the way to apply toUpper to all header items? It looks too clumsy having to do it one-by-one (i.e. header.calories, header.fat...) and I can't figure out how a v-for can wrap around the template/v-slot element. Is the only way to use a 'div' and flex it horizontally?</p>

```<code> <template>
   <v-data-table
     :headers="headers"
     :items="desserts"
     class="elevation-1"
   >
     <template v-slot:header.name="{ header }">
       {{ header.text.toUpperCase() }}
     </template>
   </v-data-table>
 </template>

 <script>
   export default {
     data: () => ({
       headers: [
         {
           text: 'Dessert (100g serving)',
           align: 'start',
           value: 'name',
         },
         { text: 'Calories', value: 'calories' },
         { text: 'Fat (g)', value: 'fat' },
         { text: 'Carbs (g)', value: 'carbs' },
         { text: 'Protein (g)', value: 'protein' },
         { text: 'Iron (%)', value: 'iron' },
       ],
       desserts: [
         {
           name: 'Frozen Yogurt',
           calories: 159,
           fat: 6.0,
           carbs: 24,
           protein: 4.0,
           iron: '1%',
         },
         ....// rest of it
       ],
     }),
   }
 </script>
</code>```

答:
your code is correct but in this form you need to add each header alone like this:

```<code><template>
     <v-data-table
         :headers="headers"
         :items="desserts"
         class="elevation-1"
     >
         <template v-slot:header.name="{ header }">
             {{ header.text.toUpperCase() }}
         </template>

         <template v-slot:header.calories="{ header }">
             {{ header.text.toUpperCase() }}
         </template>
         ...
     </v-data-table>
</template>

<script>
    export default {
        data: () => ({
            headers: [
     {
       text: 'Dessert (100g serving)',
       align: 'start',
       value: 'name',
     },
     { text: 'Calories', value: 'calories' },
     { text: 'Fat (g)', value: 'fat' },
     { text: 'Carbs (g)', value: 'carbs' },
     { text: 'Protein (g)', value: 'protein' },
     { text: 'Iron (%)', value: 'iron' },
   ],
   desserts: [
     {
       name: 'Frozen Yogurt',
       calories: 159,
       fat: 6.0,
       carbs: 24,
       protein: 4.0,
       iron: '1%',
     },
     ....// rest of it
   ],
 }),
  }
</script>
</code>```

this way you need to do this to every header alone the way of doing it is by adding v-slot:header.<value from headers array in the data>

example:

```<code>headers = [
    {
        text: "text1",
        ...
        value: "category"
    }
]
</code>```

code will be:

```<code><template v-slot:header.category="{ header }">
    {{ header.text.toUpperCase() }}
</template>
</code>```

Body:
Looking at the examples on this page, what is the way to apply toUpper to all header items? It looks too clumsy having to do it one-by-one (i.e. header.calories, header.fat...) and I can't figure out how a v-for can wrap around the template/v-slot element. Is the only way to use a 'div' and flex it horizontally?

 <template>
   <v-data-table
     :headers="headers"
     :items="desserts"
     class="elevation-1"
   >
     <template v-slot:header.name="{ header }">
       {{ header.text.toUpperCase() }}
     </template>
   </v-data-table>
 </template>

Body:
your code is correct but in this form you need to add each header alone like this:

<template>
     <v-data-table
         :headers="headers"
         :items="desserts"
         class="elevation-1"
     >
         <template v-slot:header.name="{ header }">
             {{ header.text.toUpperCase() }}
         </template>

         <template v-slot:header.calories="{ header }">
             {{ header.text.toUpperCase() }}
         </template>
         ...
     </v-data-table>
</template>

<script>
    export default {
        data: () => ({
            headers: [
     {
       text: 'Dessert (100g serving)',
       align: 'start',
       value: 'name',
     },
     { text: 'Calories', value: 'calories' },
     { text: 'Fat (g)', value: 'fat' },
     { text: 'Carbs (g)', value: 'carbs' },
     { text: 'Protein (g)', value: 'protein' },
     { text: 'Iron (%)', value: 'iron' },
   ],
   desserts: [
     {
       name: 'Frozen Yogurt',
       calories: 159,
       fat: 6.0,
       carbs: 24,
       protein: 4.0,
       iron: '1%',
     },
     ....// rest of it
   ],
 }),
  }
</script>

this way you need to do this to every header alone the way of doing it is by adding v-slot:header.<value from headers array in the data>

example:

headers = [
    {
        text: "text1",
        ...
        value: "category"
    }
]

code will be:

<template v-slot:header.category="{ header }">
    {{ header.text.toUpperCase() }}
</template>


问:
Combining root and non-root event functions in R desolve
I am using R and the desolve package to implement a model with events occuring at both specific times and events occuring when certain condtions are true (i.e. root events).

As some background code here demonstrates using root events which trigger when a condition is met, whilst code here demonstrates using multiple non-root events.

As would be expected if a root event is used the time step will not be a trigger and vice versa if a time trigger is used the root will not trigger.

I considered using a root that returns 0 when the model time matches the event time. I have implemented this below and it appears to function however my understanding is that when building models we should not assume that the model time will occur (indeed I understand this is the entire reason behind using events). Therefore I am unsure if this is good practice or if there is a better way to do this.

```<code>library("desolve")
yini <- c(temp = 18, heating_on = 1, eventoccurs = 0)

temp <- function(t,y, parms) {
  dy1 <- ifelse(y[2] == 1, 1.0, -0.5)
  dy2 <- 0
  dy3 <- 0
  list(c(dy1, dy2, dy3))
}
event_times <- c(1, 5, 20)
rootfunc <- function(t, y, parms) {
  time_in_event <- 1
  if(t %in% event_times){ time_in_event = 0}
  yroot <- c(y[1] - 18, y[1] - 20, time_in_event)
  return(yroot)
}

eventfunc <- function(t, y, parms) {
  time_in_event <- 1
  if(t %in% event_times){ time_in_event = 0}
  yroot <- c(y[1] - 18, y[1] - 20, time_in_event)
  whichroot <- which(abs(yroot) < 1e-6) # specify tolerance
  if(whichroot == 2) { y[2] <- 0 } else { y[2] <- 1 }
  if(whichroot == 3) { y[3] <- 1 } else { y[3] <- 0 }
  return(y)
}

times <- seq(from=0, to=20,by=0.1)
out <- lsode(times=times, y=yini, func = temp, parms = NULL,
             rootfun = rootfunc, events = list(func=eventfunc, root = TRUE))
plot(out, lwd=2)
</code>```

Extension - co-occuring events

I expected if this is the solution I may go on to have issues where multiple events occur at the same time but from experimenting it appears that providing the same paramters are not modified by multiple co-occuring events this is not an issue. I presume the correct way to handle these instances would be document the order of priority and, ideally, print/log a warning that it has occured (clearly for time triggered events a check could be made before the model is run but root triggers will only be discovered during the run).

答:
In deSolve: Can't understand how to early stop ode solver with root functions I sketched the general idea of the root->action event mechanism. This means that desolve actively searches for a root if a sign change in one component of the root function is detected. As such the result of the root function should be a list of a continuous functions that change sign at the root. For the fixed times it should be a list of t-event_time(k).

To avoid code duplication, and thus for higher flexibility, in eventfunc simply use yroot=rootfunc(t,y,parms).

Body:
I am using R and the desolve package to implement a model with events occuring at both specific times and events occuring when certain condtions are true (i.e. root events).

As some background code here demonstrates using root events which trigger when a condition is met, whilst code here demonstrates using multiple non-root events.

As would be expected if a root event is used the time step will not be a trigger and vice versa if a time trigger is used the root will not trigger.

I considered using a root that returns 0 when the model time matches the event time. I have implemented this below and it appears to function however my understanding is that when building models we should not assume that the model time will occur (indeed I understand this is the entire reason behind using events). Therefore I am unsure if this is good practice or if there is a better way to do this.

library("desolve")
yini <- c(temp = 18, heating_on = 1, eventoccurs = 0)

temp <- function(t,y, parms) {
  dy1 <- ifelse(y[2] == 1, 1.0, -0.5)
  dy2 <- 0
  dy3 <- 0
  list(c(dy1, dy2, dy3))
}
event_times <- c(1, 5, 20)
rootfunc <- function(t, y, parms) {
  time_in_event <- 1
  if(t %in% event_times){ time_in_event = 0}
  yroot <- c(y[1] - 18, y[1] - 20, time_in_event)
  return(yroot)
}

eventfunc <- function(t, y, parms) {
  time_in_event <- 1
  if(t %in% event_times){ time_in_event = 0}
  yroot <- c(y[1] - 18, y[1] - 20, time_in_event)
  whichroot <- which(abs(yroot) < 1e-6) # specify tolerance
  if(whichroot == 2) { y[2] <- 0 } else { y[2] <- 1 }
  if(whichroot == 3) { y[3] <- 1 } else { y[3] <- 0 }
  return(y)
}

times <- seq(from=0, to=20,by=0.1)
out <- lsode(times=times, y=yini, func = temp, parms = NULL,
             rootfun = rootfunc, events = list(func=eventfunc, root = TRUE))
plot(out, lwd=2)

Extension - co-occuring events

I expected if this is the solution I may go on to have issues where multiple events occur at the same time but from experimenting it appears that providing the same paramters are not modified by multiple co-occuring events this is not an issue. I presume the correct way to handle these instances would be document the order of priority and, ideally, print/log a warning that it has occured (clearly for time triggered events a check could be made before the model is run but root triggers will only be discovered during the run).


问:
How to move a React component using CSS ? No functions or classes are working
I am trying to move a button in my appbar to the right. Here is what it looks like:

I have tried 2 ways to fix this:

```<code>    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black', float:'right'}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        sx = {{float:'right'}}
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;
</code>```

I also tried to do the same thing with a useStyles hook:

```<code>import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import { makeStyles } from '@material-ui/core/styles';
import {createMuiTheme} from '@material-ui/core/styles';
const useStyles  = makeStyles({
    root: {
        float:'right'
    }
});
const Header = () => {
    const classes = useStyles();
    return (
        <AppBar position="sticky">
            <Toolbar
                sx = {{background:'black'}}
                variant="dense">
                    <CustomButton text='Upload'
                                  className={classes.root}
                                  endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;
</code>```

But none of them have worked and the button won't move to the right.

The code of my button component is as follows:

```<code>import {Button} from '@material-ui/core';
import UploadIcon from '@mui/icons-material/Upload';

const CustomButton = ({float,text, endIcon}) => {

    return (
        <div className='CustomButton'>
            <Button style={{fontWeight: 'bold'}}
                    variant="contained"
                    size='small'
                    endIcon={endIcon}>
                {text}
            </Button>
        </div>
    )
}
export default CustomButton;
</code>```

答:
In mui, u will use flex alot.

```<code>return (
    <AppBar
        position="sticky">
        <Toolbar
            sx = {{background:'black', display: 'flex', justifyContent: 'flex-end'}}
            variant="dense">
                <CustomButton
                    text='Upload'
                    endIcon={<UploadIcon/>}/>
        </Toolbar>
    </AppBar>
)
}
export default Header;
</code>```

Since mui v5, also nice to learn how to use Stack.

```<code><Toolbar>
    <Stack direction="row" justifyContent="space-between">
         <MyLogo />   //extreme left
         <MyButton /> //extreme right
    </Stack>
</Toolbar>
</code>```

Stack can also be nested

```<code><Toolbar>
    <Stack direction="row" justifyContent="space-between">
         <Stack direction="row"> // content in extreme left
              <MyLogo />
              <MyOtherLeftComponent />
         </Stack>

         <MyButton /> //extreme right
    </Stack>
</Toolbar>
</code>```

Body:
I am trying to move a button in my appbar to the right. Here is what it looks like:

I have tried 2 ways to fix this:

    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black', float:'right'}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        sx = {{float:'right'}}
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;

I also tried to do the same thing with a useStyles hook:

import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import { makeStyles } from '@material-ui/core/styles';
import {createMuiTheme} from '@material-ui/core/styles';
const useStyles  = makeStyles({
    root: {
        float:'right'
    }
});
const Header = () => {
    const classes = useStyles();
    return (
        <AppBar position="sticky">
            <Toolbar
                sx = {{background:'black'}}
                variant="dense">
                    <CustomButton text='Upload'
                                  className={classes.root}
                                  endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;

But none of them have worked and the button won't move to the right.

The code of my button component is as follows:

import {Button} from '@material-ui/core';
import UploadIcon from '@mui/icons-material/Upload';

const CustomButton = ({float,text, endIcon}) => {

    return (

            <Button style={{fontWeight: 'bold'}}
                    variant="contained"
                    size='small'
                    endIcon={endIcon}>
                {text}
            </Button>

    )
}
export default CustomButton;

Body:
In mui, u will use flex alot.

return (
    <AppBar
        position="sticky">
        <Toolbar
            sx = {{background:'black', display: 'flex', justifyContent: 'flex-end'}}
            variant="dense">
                <CustomButton
                    text='Upload'
                    endIcon={<UploadIcon/>}/>
        </Toolbar>
    </AppBar>
)
}
export default Header;

Since mui v5, also nice to learn how to use Stack.

<Toolbar>
    <Stack direction="row" justifyContent="space-between">
         <MyLogo />   //extreme left
         <MyButton /> //extreme right
    </Stack>
</Toolbar>

Stack can also be nested

<Toolbar>
    <Stack direction="row" justifyContent="space-between">
         <Stack direction="row"> // content in extreme left
              <MyLogo />
              <MyOtherLeftComponent />
         </Stack>

         <MyButton /> //extreme right
    </Stack>
</Toolbar>


问:
When using React Select with Menu Item, the menu is rendering horizontally rather than vertically how can I fix this?
I am trying to make a dropdown menu in React and have used Select and Menu Item. However, the options in the drop down menu are rendering horizontally rather than vertically. I am not sure how to fix this and have attached my code below.</p>
```<code><div style = {{ display: 'flex', width: '500px', margin: '20px' }}>
            <div style = {{ flex: '150px', left: "79px" }}>
              <Select
                id = "status-menu"
                onChange={handleStatusClick}
              >
                <MenuItem value={"Awaiting Utility"}>Awaiting Utility</MenuItem>
                <MenuItem value={"Terminated"}>Terminated</MenuItem>
                <MenuItem value={"Denied"}>Denied</MenuItem>
                <MenuItem value={"Completed"}>Completed</MenuItem>
                <MenuItem value={"Approved"}>Approved</MenuItem>
                <MenuItem value={"Awaiting AccessH2O"}>Awaiting AccessH2O</MenuItem>
              </Select>
              <h4 style = {{ fontWeight: 'normal', backgroundColor: setStatusColor(dummyData.status), width: '85%', textAlign: 'center', borderRadius: '8px' }}>{status}</h4>
            </div>
            <div style = {{ flex: '100px' }}>
              <h4 style = {{ fontWeight: 'normal' }}>{dummyData.accountId}</h4>
            </div>
            <div style = {{ flex: '100px' }}>
              <h4 style = {{ fontWeight: 'normal' }}>{dummyData.propertyAddress}</h4>
            </div>
          </div>
</code>```

答: Try adding style = {{ display: 'flex', flexDirection: 'column' }} to your <Select> component.

Body:
I am trying to make a dropdown menu in React and have used Select and Menu Item. However, the options in the drop down menu are rendering horizontally rather than vertically. I am not sure how to fix this and have attached my code below.

              <Select
                id = "status-menu"
                onChange={handleStatusClick}
              >
                <MenuItem value={"Awaiting Utility"}>Awaiting Utility</MenuItem>
                <MenuItem value={"Terminated"}>Terminated</MenuItem>
                <MenuItem value={"Denied"}>Denied</MenuItem>
                <MenuItem value={"Completed"}>Completed</MenuItem>
                <MenuItem value={"Approved"}>Approved</MenuItem>
                <MenuItem value={"Awaiting AccessH2O"}>Awaiting AccessH2O</MenuItem>
              </Select>

{status}

{dummyData.accountId}

{dummyData.propertyAddress}


问:
sqlpackage migration script always wants to rebuild
Can anyone explain when using sqlpackage.exe to produce a migration script always wants to drop the table and recreate when adding a field.

My databases are hosted on Azure PaaS service.

I have a database with a table created with the following sql:

```<code>CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);
</code>```

I then create a new temporary database and run the following sql (adding field 2)

```<code>CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Field 2]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);
</code>```

Then run the following command to extract the dacpac:

```<code>sqlpackage.exe /SourceConnectionString:"<tempdb>" /a:Extract /tf:local.dacpac
</code>```

Then run this to get a migration report:

```<code>sqlpackage.exe /TargetConnectionString:"<orginaldb>" /a:DeployReport /sourcefile:local.dacpac /outputpath:report.xml
</code>```

But it always wants to do this:

```<code><?xml version="1.0" encoding="utf-8"?>
<DeploymentReport xmlns="http://schemas.microsoft.com/sqlserver/dac/DeployReport/2012/02">
    <Alerts>
        <Alert Name="DataMotion">
            <Issue Value="[dbo].[test]" />
        </Alert>
    </Alerts>
    <Operations>
        <Operation Name="TableRebuild">
            <Item Value="[dbo].[test]" Type="SqlTable" />
        </Operation>
    </Operations>
</DeploymentReport>
</code>```

答:
The behavior of sqlpackage.exe can be influenced very detailed by many parameters, here are only a few shown:

A detailed list of all parameters you can find here:

https://learn.microsoft.com/en-us/sql/tools/sqlpackage/sqlpackage-deploy-drift-report?view=sql-server-ver15

It takes likely some time and thoughts to adjust it exactly to your needs.

Body:
Can anyone explain when using sqlpackage.exe to produce a migration script always wants to drop the table and recreate when adding a field.

My databases are hosted on Azure PaaS service.

I have a database with a table created with the following sql:

CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

I then create a new temporary database and run the following sql (adding field 2)

CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Field 2]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

Then run the following command to extract the dacpac:

sqlpackage.exe /SourceConnectionString:"<tempdb>" /a:Extract /tf:local.dacpac

Then run this to get a migration report:

sqlpackage.exe /TargetConnectionString:"<orginaldb>" /a:DeployReport /sourcefile:local.dacpac /outputpath:report.xml

But it always wants to do this:

<?xml version="1.0" encoding="utf-8"?>
<DeploymentReport xmlns="http://schemas.microsoft.com/sqlserver/dac/DeployReport/2012/02">
    <Alerts>
        <Alert Name="DataMotion">
            <Issue Value="[dbo].[test]" />
        </Alert>
    </Alerts>
    <Operations>
        <Operation Name="TableRebuild">
            <Item Value="[dbo].[test]" Type="SqlTable" />
        </Operation>
    </Operations>
</DeploymentReport>


问:
Can this integral be done numerically in either Matlab or Mathematica?
I want to be able to do the integral below completely numerically.

where ,  and ,  and  are constants which for simplicity, can all be set to 1.

The integral over x can be done analytically by hand or using Mathematica, and then the integral over y can be done numerically using NIntegrate, but these two methods give different answers.

Analytically:

```<code>In[160]:= ex := 2 (1 - Cos[x])

In[149]:= ey := 2 (1 - Cos[y])

In[161]:= kx := 1/(1 + Exp[ex])

In[151]:= ky := 1/(1 + Exp[ey])

In[162]:= Fn1 := 1/(2 \[Pi]) ((Cos[(x + y)/2])^2)/(ex - ey)

In[163]:= Integrate[Fn1, {x, -Pi, Pi}]

Out[163]= -(1/(4 \[Pi]))
 If[Re[y] >= \[Pi] || \[Pi] + Re[y] <= 0 ||
   y \[NotElement] Reals, \[Pi] Cos[y] - Log[-Cos[y/2]] Sin[y] +
   Log[Cos[y/2]] Sin[y],
  Integrate[Cos[(x + y)/2]^2/(Cos[x] - Cos[y]), {x, -\[Pi], \[Pi]},
   Assumptions -> ! (Re[y] >= \[Pi] || \[Pi] + Re[y] <= 0 ||
       y \[NotElement] Reals)]]

In[164]:= Fn2 := -1/(
  4 \[Pi]) ((\[Pi] Cos[y] - Log[-Cos[y/2]] Sin[y] +
     Log[Cos[y/2]] Sin[y]) (1 - ky) ky )/(2 \[Pi])

In[165]:= NIntegrate[Fn2, {y, -Pi, Pi}]

Out[165]= -0.0160323 - 2.23302*10^-15 I
</code>```

Numerical method 1:

```<code>In[107]:= Fn4 :=
 1/(4 \[Pi]^2) ((Cos[(x + y)/2])^2) (1 - ky) ky/(ex - ey)

In[109]:= NIntegrate[Fn4, {x, -Pi, Pi}, {y, -Pi, Pi}]

During evaluation of In[109]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>

During evaluation of In[109]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 18 recursive bisections in x near {x,y} = {0.0000202323,2.16219}. NIntegrate obtained 132827.66472461013` and 19442.543606302774` for the integral and error estimates. >>

Out[109]= 132828.
</code>```

Numerical 2:

```<code>In[113]:= delta = .001;
pw[x_, y_] := Piecewise[{{1, Abs[Abs[x] - Abs[y]] > delta}}, 0]

In[116]:= Fn5 := (Fn4)*pw[Cos[x], Cos[y]]

In[131]:= NIntegrate[Fn5, {x, -Pi, Pi}, {y, -Pi, Pi}]

During evaluation of In[131]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>

During evaluation of In[131]:= NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times. The global error is expected to decrease monotonically after a number of integrand evaluations. Suspect one of the following: the working precision is insufficient for the specified precision goal; the integrand is highly oscillatory or it is not a (piecewise) smooth function; or the true value of the integral is 0. Increasing the value of the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical integration. NIntegrate obtained 0.013006903336304906` and 0.0006852739534086272` for the integral and error estimates. >>

Out[131]= 0.0130069
</code>```

So neither of the numerical methods give -0.0160323. I understand why - the first method has trouble with the infinities caused by the denominator, and the second method effectively deletes the part of the integral that is causing problems. But I'd like to be able to integrate another integral (a harder one over x, y and z) which can't be simplified analytically. The above integral gives me a way to test any new method since I know what the answer should be.

答:
Unless I wrote down the integral wrong, this should do the job:

```<code>n[x_] := 1/(1 + Exp[eps[x]])
eps[x_] := 2(1 - Cos[x])
.25/(2*Pi)^2*NIntegrate[
    Cos[(x + y)/
     2]^2 ((1 - n[y]) n[y] - (1 - n[x]) n[x])/(Cos[y] - Cos[x]),
    {x, -Pi, Pi},
    {y, -Pi, Pi},
    Exclusions -> {Cos[x] == Cos[y]}
  ]
</code>```

giving 0.0130098.

OK, I guess the quickest way to explain is like this:

going from the first to the second line of the first eq I've just renamed y to x (the region of integration is symmetric so it's OK). Then I have added the two (equivalent) expressions for I to obtain 2I, and what I numerically integrate is that. The point is that the numerator and denominator vanish at the same points, so in fact the Exclusions option isn't needed. Note that in my sketch of the method above I dropped the 1/(4*Pi^2) for brevity (or due to laziness, depending on the viewpoint).

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to do the integral below completely numerically.

where ,  and ,  and  are constants which for simplicity, can all be set to 1.

The integral over x can be done analytically by hand or using Mathematica, and then the integral over y can be done numerically using NIntegrate, but these two methods give different answers.

Analytically:

In[160]:= ex := 2 (1 - Cos[x])

In[149]:= ey := 2 (1 - Cos[y])

In[161]:= kx := 1/(1 + Exp[ex])

In[151]:= ky := 1/(1 + Exp[ey])

In[162]:= Fn1 := 1/(2 \[Pi]) ((Cos[(x + y)/2])^2)/(ex - ey)

In[163]:= Integrate[Fn1, {x, -Pi, Pi}]

Out[163]= -(1/(4 \[Pi]))
 If[Re[y] >= \[Pi] || \[Pi] + Re[y] <= 0 ||
   y \[NotElement] Reals, \[Pi] Cos[y] - Log[-Cos[y/2]] Sin[y] +
   Log[Cos[y/2]] Sin[y],
  Integrate[Cos[(x + y)/2]^2/(Cos[x] - Cos[y]), {x, -\[Pi], \[Pi]},
   Assumptions -> ! (Re[y] >= \[Pi] || \[Pi] + Re[y] <= 0 ||
       y \[NotElement] Reals)]]

In[164]:= Fn2 := -1/(
  4 \[Pi]) ((\[Pi] Cos[y] - Log[-Cos[y/2]] Sin[y] +
     Log[Cos[y/2]] Sin[y]) (1 - ky) ky )/(2 \[Pi])

In[165]:= NIntegrate[Fn2, {y, -Pi, Pi}]

Out[165]= -0.0160323 - 2.23302*10^-15 I

Numerical method 1:

In[107]:= Fn4 :=
 1/(4 \[Pi]^2) ((Cos[(x + y)/2])^2) (1 - ky) ky/(ex - ey)

In[109]:= NIntegrate[Fn4, {x, -Pi, Pi}, {y, -Pi, Pi}]

During evaluation of In[109]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>

During evaluation of In[109]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 18 recursive bisections in x near {x,y} = {0.0000202323,2.16219}. NIntegrate obtained 132827.66472461013` and 19442.543606302774` for the integral and error estimates. >>

Out[109]= 132828.

Numerical 2:

In[113]:= delta = .001;
pw[x_, y_] := Piecewise[{{1, Abs[Abs[x] - Abs[y]] > delta}}, 0]

In[116]:= Fn5 := (Fn4)*pw[Cos[x], Cos[y]]

In[131]:= NIntegrate[Fn5, {x, -Pi, Pi}, {y, -Pi, Pi}]

During evaluation of In[131]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>

During evaluation of In[131]:= NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times. The global error is expected to decrease monotonically after a number of integrand evaluations. Suspect one of the following: the working precision is insufficient for the specified precision goal; the integrand is highly oscillatory or it is not a (piecewise) smooth function; or the true value of the integral is 0. Increasing the value of the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical integration. NIntegrate obtained 0.013006903336304906` and 0.0006852739534086272` for the integral and error estimates. >>

Out[131]= 0.0130069

So neither of the numerical methods give -0.0160323. I understand why - the first method has trouble with the infinities caused by the denominator, and the second method effectively deletes the part of the integral that is causing problems. But I'd like to be able to integrate another integral (a harder one over x, y and z) which can't be simplified analytically. The above integral gives me a way to test any new method since I know what the answer should be.

Body:
Unless I wrote down the integral wrong, this should do the job:

n[x_] := 1/(1 + Exp[eps[x]])
eps[x_] := 2(1 - Cos[x])
.25/(2*Pi)^2*NIntegrate[
    Cos[(x + y)/
     2]^2 ((1 - n[y]) n[y] - (1 - n[x]) n[x])/(Cos[y] - Cos[x]),
    {x, -Pi, Pi},
    {y, -Pi, Pi},
    Exclusions -> {Cos[x] == Cos[y]}
  ]

giving 0.0130098.

OK, I guess the quickest way to explain is like this:

going from the first to the second line of the first eq I've just renamed y to x (the region of integration is symmetric so it's OK). Then I have added the two (equivalent) expressions for I to obtain 2I, and what I numerically integrate is that. The point is that the numerator and denominator vanish at the same points, so in fact the Exclusions option isn't needed. Note that in my sketch of the method above I dropped the 1/(4*Pi^2) for brevity (or due to laziness, depending on the viewpoint).


问:
How to use pip in Dockerfile with docker-compose?
I am trying to build a docker image of a python application using a docker-compose.yml file. But I am having errors when it come to using pip to install dependencies. Here is my docker-compose file :

```<code>version: '3.8'

services:
  scaleway:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./pur_beurre/:/usr/src/pur_beurre/
    ports:
      - 8000:8000
    env_file:
      - ./.env.dev
</code>```

My Dockerfile :

```<code># pull official base image
FROM python:3.8-alpine

# set work directory
WORKDIR /pur_beurre

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .

# collect static files
RUN python manage.py collectstatic --noinput

# add and run as non-root user
RUN adduser -D myuser
USER myuser

# run gunicorn
CMD gunicorn pur_beurre.wsgi:application --bind 0.0.0.0:$PORT
</code>```

And the error I have :

```<code>Step 5/12 : RUN pip install --upgrade pip
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (windows/amd64) and no specific platform was requested
 ---> Running in e87a839f9da3
Requirement already satisfied: pip in /usr/local/lib/python3.8/site-packages (21.2.4)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffcc280>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccbe0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccd30>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccee0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffc1610>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
The command '/bin/sh -c pip install --upgrade pip' returned a non-zero code: 4294967295: failed to shutdown container: container e87a839f9da317220a77213c962f4c30eb4bc005f990a977f10eb4beda429028 encountered an error during hcsshim::System::waitBackground: failure in a Windows system call: The virtual machine or container with the specified identifier is not running. (0xc0370110): subsequent terminate failed container e87a839f9da317220a77213c962f4c30eb4bc005f990a977f10eb4beda429028 encountered an error during hcsshim::System::waitBackground: failure in a Windows system call: The virtual machine or container with the specified identifier is not running. (0xc0370110)
ERROR: Service 'scaleway' failed to build : Build failed
</code>```

I tried to erase the command RUN pip install --upgrade pip from the Dockerfile but then I have this error :

```<code>Step 6/11 : RUN pip install -r requirements.txt
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (windows/amd64) and no specific platform was requested
 ---> Running in 795acf389f1c
container 795acf389f1ca89d04927a93818b745c38e6ab624f34a7190d855797302cf258 encountered an error during hcsshim::System::CreateProcess: failure in a Windows system call: Unspecified error (0x80004005)
[Event Detail: failed to run runc create/exec call for container 795acf389f1ca89d04927a93818b745c38e6ab624f34a7190d855797302cf258: exit status 1 Stack Trace:
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*container).startProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:580
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*runcRuntime).runCreateCommand
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:471
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*runcRuntime).CreateContainer
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:113
github.com/Microsoft/opengcs/service/gcs/core/gcs.(*gcsCore).ExecProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/core/gcs/gcs.go:351
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).execProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:637
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).execProcess-fm
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:253
github.com/Microsoft/opengcs/service/gcs/bridge.HandlerFunc.ServeMsg
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:72
github.com/Microsoft/opengcs/service/gcs/bridge.(*Mux).ServeMsg
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:146
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).ListenAndServe.func2.1
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:335
runtime.goexit
        /usr/lib/go/src/runtime/asm_amd64.s:1333 Provider: 00000000-0000-0000-0000-000000000000]
ERROR: Service 'scaleway' failed to build : Build failed
</code>```

答:
Try to create file pip.conf with the content below and put it into your image

pip.conf

```<code>[global]
timeout = 60
index-url = https://pypi.python.org/simple
trusted-host = pypi.python.org
</code>```

Dockerfile

```<code>...
COPY pip.conf /root/.pip/pip.conf
RUN pip install --upgrade pip
</code>```

UPD

Check also this answer:
https://stackoverflow.com/a/53834762/13698294

You need to do instructions from it in WSL (Ubuntu)

Body:
I am trying to build a docker image of a python application using a docker-compose.yml file. But I am having errors when it come to using pip to install dependencies. Here is my docker-compose file :

version: '3.8'

services:
  scaleway:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./pur_beurre/:/usr/src/pur_beurre/
    ports:
      - 8000:8000
    env_file:
      - ./.env.dev

My Dockerfile :

# pull official base image
FROM python:3.8-alpine

# set work directory
WORKDIR /pur_beurre

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .

# collect static files
RUN python manage.py collectstatic --noinput

# add and run as non-root user
RUN adduser -D myuser
USER myuser

# run gunicorn
CMD gunicorn pur_beurre.wsgi:application --bind 0.0.0.0:$PORT

And the error I have :

Step 5/12 : RUN pip install --upgrade pip
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (windows/amd64) and no specific platform was requested
 ---> Running in e87a839f9da3
Requirement already satisfied: pip in /usr/local/lib/python3.8/site-packages (21.2.4)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffcc280>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccbe0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccd30>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffccee0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f9cfffc1610>: Failed to establish a new connection: [Errno -3] Try again')': /simple/pip/
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
The command '/bin/sh -c pip install --upgrade pip' returned a non-zero code: 4294967295: failed to shutdown container: container e87a839f9da317220a77213c962f4c30eb4bc005f990a977f10eb4beda429028 encountered an error during hcsshim::System::waitBackground: failure in a Windows system call: The virtual machine or container with the specified identifier is not running. (0xc0370110): subsequent terminate failed container e87a839f9da317220a77213c962f4c30eb4bc005f990a977f10eb4beda429028 encountered an error during hcsshim::System::waitBackground: failure in a Windows system call: The virtual machine or container with the specified identifier is not running. (0xc0370110)
ERROR: Service 'scaleway' failed to build : Build failed

I tried to erase the command RUN pip install --upgrade pip from the Dockerfile but then I have this error :

Step 6/11 : RUN pip install -r requirements.txt
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (windows/amd64) and no specific platform was requested
 ---> Running in 795acf389f1c
container 795acf389f1ca89d04927a93818b745c38e6ab624f34a7190d855797302cf258 encountered an error during hcsshim::System::CreateProcess: failure in a Windows system call: Unspecified error (0x80004005)
[Event Detail: failed to run runc create/exec call for container 795acf389f1ca89d04927a93818b745c38e6ab624f34a7190d855797302cf258: exit status 1 Stack Trace:
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*container).startProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:580
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*runcRuntime).runCreateCommand
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:471
github.com/Microsoft/opengcs/service/gcs/runtime/runc.(*runcRuntime).CreateContainer
        /go/src/github.com/Microsoft/opengcs/service/gcs/runtime/runc/runc.go:113
github.com/Microsoft/opengcs/service/gcs/core/gcs.(*gcsCore).ExecProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/core/gcs/gcs.go:351
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).execProcess
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:637
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).execProcess-fm
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:253
github.com/Microsoft/opengcs/service/gcs/bridge.HandlerFunc.ServeMsg
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:72
github.com/Microsoft/opengcs/service/gcs/bridge.(*Mux).ServeMsg
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:146
github.com/Microsoft/opengcs/service/gcs/bridge.(*Bridge).ListenAndServe.func2.1
        /go/src/github.com/Microsoft/opengcs/service/gcs/bridge/bridge.go:335
runtime.goexit
        /usr/lib/go/src/runtime/asm_amd64.s:1333 Provider: 00000000-0000-0000-0000-000000000000]
ERROR: Service 'scaleway' failed to build : Build failed

Body:
Try to create file pip.conf with the content below and put it into your image

pip.conf

[global]
timeout = 60
index-url = https://pypi.python.org/simple
trusted-host = pypi.python.org

Dockerfile

...
COPY pip.conf /root/.pip/pip.conf
RUN pip install --upgrade pip

UPD

Check also this answer:
https://stackoverflow.com/a/53834762/13698294

You need to do instructions from it in WSL (Ubuntu)


问:
How can I fetch data in my content script? (chrome extension)
I'm trying to fetch a simple .json file from my we accessible ressources into my content script. Here is what I tried so far:

manifest.json

{
    "manifest_version": 3,
    "name": "MyExtension",
    "version": "0.0",
    "content_scripts": [{
        "matches": ["*://*/*"],
        "js": ["content.js"]
    }],
    "icons":{
            "128": "images/logo128x128.png"
    },
    "web_accessible_resources": [{
      "resources": ["data/data.json"],
      "matches": ["https://web-accessible-resources-1.glitch.me/*"]
    }]
}```
</div>
</div>
</p>
<p>content.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const jsondict_url = chrome.runtime.getURL("data.json")
console.log(jsondict_url)

var jsondict = fetch(jsondict_url)

console.log(jsondict)</code>```

This is the error message I get:

chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json
physique-generale-mecanique-PHYS-101-A#:1

       Denying load of chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

content.js:6 Promise {<pending>}[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to fetch
    at chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/content.js:4:16
content.js:4

       GET chrome-extension://invalid/ net::ERR_FAILED
(anonymous) @ content.js:4
content.js:4

      Uncaught (in promise) TypeError: Failed to fetch
    at content.js:4:16
(anonymous) @ content.js:4```

Edit: my files are organized this way

images/
logo128x128.png

data/data.json

content.js

manifest.js

答:
You're trying
getURL("data.json")
but your manifest states "resources": ["data/data.json"] so the path is incorrect in atleast one place? It should be getURL("data/data.json").

You can also try adding content.js to "web_accessible_resources".

Body:
I'm trying to fetch a simple .json file from my we accessible ressources into my content script. Here is what I tried so far:

manifest.json

{
    "manifest_version": 3,
    "name": "MyExtension",
    "version": "0.0",
    "content_scripts": [{
        "matches": ["*://*/*"],
        "js": ["content.js"]
    }],
    "icons":{
            "128": "images/logo128x128.png"
    },
    "web_accessible_resources": [{
      "resources": ["data/data.json"],
      "matches": ["https://web-accessible-resources-1.glitch.me/*"]
    }]
}

content.js

const jsondict_url = chrome.runtime.getURL("data.json")
console.log(jsondict_url)

var jsondict = fetch(jsondict_url)

console.log(jsondict)

This is the error message I get:

chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json
physique-generale-mecanique-PHYS-101-A#:1

       Denying load of chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

content.js:6 Promise {<pending>}[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to fetch
    at chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/content.js:4:16
content.js:4

       GET chrome-extension://invalid/ net::ERR_FAILED
(anonymous) @ content.js:4
content.js:4

      Uncaught (in promise) TypeError: Failed to fetch
    at content.js:4:16
(anonymous) @ content.js:4

Edit: my files are organized this way

images/
logo128x128.png

data/data.json

content.js

manifest.js


问:
Flask Jinja2 templating when dealing with one - to- many relationship
so I have created a flask app with three database models one for the users and the other two are parent and child models. The thing is when I am using jinja2 templating the parent table returns on one column none but the other show info. it happens that the last column is related to the child table and is supposed to return info from there. this is the code:

#parent

```<code>class Tenant(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False, autoincrement=True, unique=True)
    name = db.Column(db.String(length=50), nullable=False)
    phone_no = db.Column(db.String(length=50), nullable=False, unique=True)
    house_no = db.Column(db.String(length=50), nullable=False, unique=True)

    rent = db.relationship('Rent', backref='rent')

    def __repr__(self):
        return f'Tenant{self.id}'
</code>```

#child

```<code>class Rent(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False, unique=True)
    house_no = db.Column(db.String(length=30), nullable=False)
    message = db.Column(db.Text(length=256))
    payment = db.Column(db.Integer(), nullable=False)
    date = db.Column(db.Date, nullable=False)

    rent_id = db.Column(db.Integer(), db.ForeignKey('tenant.id'))

    def __repr__(self):
        return f'Rent{self.id}'
</code>```

//Rent routes

```<code>@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
    form = RentForm()
    if form.validate_on_submit():
        user_create = Rent(house_no=form.house_no.data,
                           payment=form.payment.data,
                           message=form.message.data,
                           date=form.date.data,
                           )
        db.session.add(user_create)
        db.session.commit()
        return redirect(url_for('rent'))
    else:
        return render_template('index.html', form=form)
</code>```

//query- rent

```<code>@app.route('/rent_paid', methods=['GET', 'POST'])
@login_required
def rent():
    rent = Rent.query.all()
    return render_template('rent.html', rent=rent)
</code>```

//Tenant route

```<code>@app.route('/new', methods=['GET', 'POST'])
@login_required
def new():
    form = TenantsForm()
    if form.validate_on_submit():
        user_create = Tenant(name=form.name.data,
                             phone_no=form.phone_no.data,
                             house_no=form.house_no.data,
                             )
        db.session.add(user_create)
        db.session.commit()
        return redirect(url_for('tenants'))
    else:
        return render_template('tenant.html', form=form)
</code>```

//query Tenants

```<code>@app.route('/tenants', methods=['GET', 'POST'])
@login_required
def tenants():
    tenant = Tenant.query.all()
    return render_template('table.html', tenant=tenant)
</code>```

HTML template

```<code> <tbody>
                                {% for tenant in tenant %}

                                <tr>
                                    <td scope='row'>{{tenant.id}}</td>
                                    <td>{{tenant.name}}</td>
                                    <td>{{tenant.phone_no}}</td>
                                    <td>{{tenant.house_no}}</td>

                                    <td>Ksh {{tenant.rent.}}</td>
</code>```

so in the HTML template, I want the last column {{ tenant.rent }} to return the actual amount e.g(500USD) but it either returns the rent id or none. how do I code to give the exact amount in the column row.

答:
Ok so in your model every Tenant can have many Rents. Every Rent has a payment amount associated with it.

When you say you want to show the total amount I am not sure whether you want to show the total payment amount collected from this Tenant up to this point or if just want to show the amount of the last payment the Tenant has made.

You have a lot of options on how to send the information to the template, here I just sent the template a dict where the key is the tenant.id and the value is the total rent up to this point.

```<code>@app.route('/tenants', methods=['GET', 'POST'])
@login_required
def tenants():
    tenants = Tenant.query.all()
    rent = {}
    for tenant in tenants:
        rents = Tenants.query.filter_by(id=tenant.id).first().rent.all()
        total = 0
        for rent in rents:
            total += rent.payment
        rent[tenant.id] = total
    return render_template('table.html', tenants=tenants, rent=rent)
</code>```

And in the template you would do something like this.

```<code>{ for tenant in tenants }
  <tr>
    <td scope='row'>{{ tenant.id }}</td>
    <td>{{ tenant.name }}</td>
    <td>{{ tenant.phone_no }}</td>
    <td>{{ tenant.house_no }}</td>
    <td>{{ rent[tenant.id] }}</td>
  </tr>
{ endfor }
</code>```

I am not sure if this is the exact correct syntax since it is hard for me to try it out, but you get the idea. You would also do the same thing if you just want to display the latest payment and not the total, you just need to order the rent by date.

Body:
so I have created a flask app with three database models one for the users and the other two are parent and child models. The thing is when I am using jinja2 templating the parent table returns on one column none but the other show info. it happens that the last column is related to the child table and is supposed to return info from there. this is the code:

#parent

class Tenant(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False, autoincrement=True, unique=True)
    name = db.Column(db.String(length=50), nullable=False)
    phone_no = db.Column(db.String(length=50), nullable=False, unique=True)
    house_no = db.Column(db.String(length=50), nullable=False, unique=True)

    rent = db.relationship('Rent', backref='rent')

    def __repr__(self):
        return f'Tenant{self.id}'

#child

class Rent(db.Model):
    id = db.Column(db.Integer(), primary_key=True, nullable=False, unique=True)
    house_no = db.Column(db.String(length=30), nullable=False)
    message = db.Column(db.Text(length=256))
    payment = db.Column(db.Integer(), nullable=False)
    date = db.Column(db.Date, nullable=False)

    rent_id = db.Column(db.Integer(), db.ForeignKey('tenant.id'))

    def __repr__(self):
        return f'Rent{self.id}'

//Rent routes

@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
    form = RentForm()
    if form.validate_on_submit():
        user_create = Rent(house_no=form.house_no.data,
                           payment=form.payment.data,
                           message=form.message.data,
                           date=form.date.data,
                           )
        db.session.add(user_create)
        db.session.commit()
        return redirect(url_for('rent'))
    else:
        return render_template('index.html', form=form)

//query- rent

@app.route('/rent_paid', methods=['GET', 'POST'])
@login_required
def rent():
    rent = Rent.query.all()
    return render_template('rent.html', rent=rent)

//Tenant route

@app.route('/new', methods=['GET', 'POST'])
@login_required
def new():
    form = TenantsForm()
    if form.validate_on_submit():
        user_create = Tenant(name=form.name.data,
                             phone_no=form.phone_no.data,
                             house_no=form.house_no.data,
                             )
        db.session.add(user_create)
        db.session.commit()
        return redirect(url_for('tenants'))
    else:
        return render_template('tenant.html', form=form)

//query Tenants

@app.route('/tenants', methods=['GET', 'POST'])
@login_required
def tenants():
    tenant = Tenant.query.all()
    return render_template('table.html', tenant=tenant)

HTML template

                                {% for tenant in tenant %}

                                    {{tenant.id}}
                                    {{tenant.name}}
                                    {{tenant.phone_no}}
                                    {{tenant.house_no}}

                                    Ksh {{tenant.rent.}}

so in the HTML template, I want the last column {{ tenant.rent }} to return the actual amount e.g(500USD) but it either returns the rent id or none. how do I code to give the exact amount in the column row.

Body:
Ok so in your model every Tenant can have many Rents. Every Rent has a payment amount associated with it.

When you say you want to show the total amount I am not sure whether you want to show the total payment amount collected from this Tenant up to this point or if just want to show the amount of the last payment the Tenant has made.

You have a lot of options on how to send the information to the template, here I just sent the template a dict where the key is the tenant.id and the value is the total rent up to this point.

@app.route('/tenants', methods=['GET', 'POST'])
@login_required
def tenants():
    tenants = Tenant.query.all()
    rent = {}
    for tenant in tenants:
        rents = Tenants.query.filter_by(id=tenant.id).first().rent.all()
        total = 0
        for rent in rents:
            total += rent.payment
        rent[tenant.id] = total
    return render_template('table.html', tenants=tenants, rent=rent)

And in the template you would do something like this.

{ for tenant in tenants }
  <tr>
    <td scope='row'>{{ tenant.id }}</td>
    <td>{{ tenant.name }}</td>
    <td>{{ tenant.phone_no }}</td>
    <td>{{ tenant.house_no }}</td>
    <td>{{ rent[tenant.id] }}</td>
  </tr>
{ endfor }

I am not sure if this is the exact correct syntax since it is hard for me to try it out, but you get the idea. You would also do the same thing if you just want to display the latest payment and not the total, you just need to order the rent by date.


问:
In PLSQL, how to loop though results from a select and then output contents (clob) to a file and update a status
I have a select statement that will will return a number of keys:

```<code>select key_val from X where a=b;
</code>```

Then I need to use key_val to interrogate the table and output the contents to a file.

```<code>select clob_col from X where x.key_val = 'value of previous statement'
</code>```

presumably using dbms_output.put_line(value of a cursor)

then I need to update the status on the table

```<code>update x set status = 'XXX' where x.key_val = 'value of previous statement'
</code>```

Then loop though for all key_val's returned from the first statement.

I've not much experience in PLSQL which is what the script needs to be written in, I understand the concept of while loops etc as I could write this in a shell script but wondered if anyone could point me in the right direction of how to achieve in PLSQL

答:
Here's an example.

As you're going to use PL/SQL, UTL_FILE package is what you need. As it creates a file on a database server, you'll first have to create a directory (an Oracle object which points to a filesystem directory) and grant some privileges to user (scott in my example) who will be using it (the directory).

```<code>SQL> connect sys as sysdba
Enter password:
Connected.
SQL> create directory ext_dir as 'c:\temp';

Directory created.

SQL> grant read, write on directory ext_dir to scott;

Grant succeeded.
</code>```

Connect as scott.

```<code>SQL> connect scott/tiger
Connected.
</code>```

Sample tables: x contains keys, test_clob contains actual values.

```<code>SQL> select * From x;

        ID    KEY_VAL STATUS
---------- ---------- ----------
       100          1
       200          2

SQL> desc test_clob
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 KEY_VAL                                            NUMBER
 COL                                                CLOB

SQL> select * from test_clob;

   KEY_VAL COL
---------- --------------------------------------------------
         1 Littlefoot
         2 Bigfoot

SQL>
</code>```

PL/SQL procedure accept x table's ID and exports CLOB column from test_clob table whose key_val corresponds to x.key_val.

First, check directories available to me:

```<code>SQL> select * from all_directories;

OWNER      DIRECTORY_NAME       DIRECTORY_PATH
---------- -------------------- --------------------
SYS        EXT_DIR              c:\temp

SQL>
</code>```

OK, only one; that's enough.

```<code>SQL> create or replace procedure p_export_clob (par_id in x.id%type)
  2  is
  3    l_file    utl_file.file_type;
  4    l_buffer  varchar2(32767);
  5    l_amount  binary_integer := 32767;
  6    l_pos     integer := 1;
  7  begin
  8    update x set status = 'xxx' where id = par_id;
  9
 10    for cur_c in (select c.col
 11                  from test_clob c join x on x.key_val = c.key_val
 12                  where x.id = par_id
 13                 )
 14    loop
 15      l_file := utl_file.fopen('EXT_DIR', 'test_clob.txt', 'w', 32767);
 16
 17      loop
 18        dbms_lob.read (cur_c.col, l_amount, l_pos, l_buffer);
 19        utl_file.put(l_file, l_buffer);
 20        utl_file.fflush(l_file);
 21        l_pos := l_pos + l_amount;
 22      end loop;
 23    end loop;
 24  exception
 25    when no_data_found then
 26      utl_file.fclose(l_file);
 27    when others then
 28      utl_file.fclose(l_file);
 29      raise;
 30  end;
 31  /

Procedure created.

SQL>
</code>```

Let's test it:

```<code>SQL> begin
  2    p_export_clob (100);      --> should export "Littlefoot"
  3  end;
  4  /

PL/SQL procedure successfully completed.

SQL>
</code>```

Result:

```<code>SQL> select * From x;

        ID    KEY_VAL STATUS
---------- ---------- ----------
       100          1 xxx
       200          2

SQL>
</code>```

Body:
I have a select statement that will will return a number of keys:

select key_val from X where a=b;

Then I need to use key_val to interrogate the table and output the contents to a file.

select clob_col from X where x.key_val = 'value of previous statement'

presumably using dbms_output.put_line(value of a cursor)

then I need to update the status on the table

update x set status = 'XXX' where x.key_val = 'value of previous statement'

Then loop though for all key_val's returned from the first statement.

I've not much experience in PLSQL which is what the script needs to be written in, I understand the concept of while loops etc as I could write this in a shell script but wondered if anyone could point me in the right direction of how to achieve in PLSQL

Body:
Here's an example.

As you're going to use PL/SQL, UTL_FILE package is what you need. As it creates a file on a database server, you'll first have to create a directory (an Oracle object which points to a filesystem directory) and grant some privileges to user (scott in my example) who will be using it (the directory).

SQL> connect sys as sysdba
Enter password:
Connected.
SQL> create directory ext_dir as 'c:\temp';

Directory created.

SQL> grant read, write on directory ext_dir to scott;

Grant succeeded.

Connect as scott.

SQL> connect scott/tiger
Connected.

Sample tables: x contains keys, test_clob contains actual values.

SQL> select * From x;

        ID    KEY_VAL STATUS
---------- ---------- ----------
       100          1
       200          2

SQL> desc test_clob
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 KEY_VAL                                            NUMBER
 COL                                                CLOB

SQL> select * from test_clob;

   KEY_VAL COL
---------- --------------------------------------------------
         1 Littlefoot
         2 Bigfoot

SQL>

PL/SQL procedure accept x table's ID and exports CLOB column from test_clob table whose key_val corresponds to x.key_val.

First, check directories available to me:

SQL> select * from all_directories;

OWNER      DIRECTORY_NAME       DIRECTORY_PATH
---------- -------------------- --------------------
SYS        EXT_DIR              c:\temp

SQL>

OK, only one; that's enough.

SQL> create or replace procedure p_export_clob (par_id in x.id%type)
  2  is
  3    l_file    utl_file.file_type;
  4    l_buffer  varchar2(32767);
  5    l_amount  binary_integer := 32767;
  6    l_pos     integer := 1;
  7  begin
  8    update x set status = 'xxx' where id = par_id;
  9
 10    for cur_c in (select c.col
 11                  from test_clob c join x on x.key_val = c.key_val
 12                  where x.id = par_id
 13                 )
 14    loop
 15      l_file := utl_file.fopen('EXT_DIR', 'test_clob.txt', 'w', 32767);
 16
 17      loop
 18        dbms_lob.read (cur_c.col, l_amount, l_pos, l_buffer);
 19        utl_file.put(l_file, l_buffer);
 20        utl_file.fflush(l_file);
 21        l_pos := l_pos + l_amount;
 22      end loop;
 23    end loop;
 24  exception
 25    when no_data_found then
 26      utl_file.fclose(l_file);
 27    when others then
 28      utl_file.fclose(l_file);
 29      raise;
 30  end;
 31  /

Procedure created.

SQL>

Let's test it:

SQL> begin
  2    p_export_clob (100);      --> should export "Littlefoot"
  3  end;
  4  /

PL/SQL procedure successfully completed.

SQL>

Result:

SQL> select * From x;

        ID    KEY_VAL STATUS
---------- ---------- ----------
       100          1 xxx
       200          2

SQL>


问:
Problem Replacing Literal String \r\n With Line Break in PHP
I have a text file that has the literal string \r\n in it. I want to replace this with an actual line break (\n).

I know that the regex /\\r\\n/ should match it (I have tested it in Reggy), but I cannot get it to work in PHP.

I have tried the following variations:

preg_replace("/\\\\r\\\\n/", "\n", $line);

preg_replace("/\\\\[r]\\\\[n]/", "\n", $line);

preg_replace("/[\\\\][r][\\\\][n]/", "\n", $line);

preg_replace("/[\\\\]r[\\\\]n/", "\n", $line);

If I just try to replace the backslash, it works properly. As soon as I add an r, it finds no matches.

The file I am reading is encoded as UTF-16.

Edit:

I have also already tried using str_replace().

I now believe that the problem here is the character encoding of the file. I tried the following, and it did work:

```<code>$testString = "\\r\\n";
echo preg_replace("/\\\\r\\\\n/", "\n", $testString);
</code>```

but it does not work on lines I am reading in from my file.

答:
```<code>$result = preg_replace('/\\\\r\\\\n/', '\n', $subject);
</code>```

The regex above replaces the type of line break normally used on windows (\r\n)  with linux line breaks (\n).

References:

Difference between CR LF, LF and CR line break types?

Right way to escape backslash [ \ ] in PHP regex?

Regex Explanation

Body:
I have a text file that has the literal string \r\n in it. I want to replace this with an actual line break (\n).

I know that the regex /\\r\\n/ should match it (I have tested it in Reggy), but I cannot get it to work in PHP.

I have tried the following variations:

preg_replace("/\\\\r\\\\n/", "\n", $line);

preg_replace("/\\\\[r]\\\\[n]/", "\n", $line);

preg_replace("/[\\\\][r][\\\\][n]/", "\n", $line);

preg_replace("/[\\\\]r[\\\\]n/", "\n", $line);

If I just try to replace the backslash, it works properly. As soon as I add an r, it finds no matches.

The file I am reading is encoded as UTF-16.

Edit:

I have also already tried using str_replace().

I now believe that the problem here is the character encoding of the file. I tried the following, and it did work:

$testString = "\\r\\n";
echo preg_replace("/\\\\r\\\\n/", "\n", $testString);

but it does not work on lines I am reading in from my file.

Body:
$result = preg_replace('/\\\\r\\\\n/', '\n', $subject);

The regex above replaces the type of line break normally used on windows (\r\n)  with linux line breaks (\n).

References:

Difference between CR LF, LF and CR line break types?

Right way to escape backslash [ \ ] in PHP regex?

Regex Explanation


问:
What is datasource.url and datasource.driverClassName in application.properties in Spring Boot
I have some questions regarding the datasource in my application.properties

```<code>#Data Source properties
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/example
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

What exactly is the datasource.driver-class-name indicating?

答:
This name refer to the classname of the JDBC driver for communicating with your database.
This class will be loaded at launch time (it must be available in the classpath).</p>

Body:
I have some questions regarding the datasource in my application.properties

#Data Source properties
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/example
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

What exactly is the datasource.driver-class-name indicating?


问:
How do I add a cooldown for a command on discord.py
I have been trying to make a cooldown for a function on discord.py. I made it in a test.py file and it works, but in my main file it doesnt.
How do you think I could go about fixing this issue? I have looked through many videos and Im not sure why this doesn't work. The "rasp farm" function works and the cool down does too, but I want a message to appear when there is a cool down, with this code I get the error</p>
```<code># python main.py

import os
import discord
import wikipedia
from discord.utils import get
import time
import random
from discord.ext.commands import Bot
import asyncio
import json
from discord.ext.commands import cooldown, BucketType
from dotenv import load_dotenv
from discord.ext import commands

os.chdir(r"C:\Users\laksh\PycharmProjects\Raspberry")
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()
bot = commands.Bot(command_prefix='rasp ')

# Start up
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

@bot.command()
async def balance(ctx):
    await open_account(ctx.author)

    user = ctx.author
    users = await get_bank_data()

    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]
    em = discord.Embed(title=f"{ctx.author.name}'s raspberries", color=discord.Color.red())
    em.add_field(name= "Wallet",value=wallet_amt)
    em.add_field(name="Bank", value=bank_amt)
    await ctx.send(embed = em)

@commands.cooldown(1, 3, commands.BucketType.user)
@bot.command()
async def farm(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()
    earnings = random.randrange(201)

    await ctx.send(f"You picked {earnings} raspberries!! (Raspberries take 1 minute to grow again!)")

    users[str(user.id)]["wallet"] += earnings
    with open("mainbank.json","w") as f:
        users = json.dump(users,f)
@farm.error
async def farm_error(ctx, error):
    if isinstance(error, farm.CommandOnCooldown):
        em = discord.Embed(title=f"You are in cooldown",description=f"Try again in {error.retry_after:.2f}s.", color=discord.Color.orange())
        await ctx.send(embed=em)

async def open_account(user):
    users = await get_bank_data()
    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0
    with open("mainbank.json","w") as a:
        users = json.dump(users,a)
    return True

async def get_bank_data():
    with open("mainbank.json", "r") as a:
        users = json.load(a)
    return users

@bot.command()
async def commands(ctx):
    embed = discord.Embed(title="My commands:", description="My prefix is 'rasp' for example a command is 'rasp farm'.",
                          color=0xff4d4d)
    embed.add_field(name="'rasp farm'", value="Farms your ripened raspberries!                ", inline=True)
    embed.add_field(name=" 'rasp balance'", value="Checks how many raspberries your wallet and bank holds!",
                    inline=True)
    embed.add_field(name="'rasp shop'", value="Buy items to multiply your raspberry earnings :yum:", inline=True)
    await ctx.send(embed=embed)

</code>```

答: The problem is that you try to access the error class from your command, which doesn't have one. You have to access discord.ext.commands.CommandOnCooldown instead of farm.CommandOnCooldown

Body:
I have been trying to make a cooldown for a function on discord.py. I made it in a test.py file and it works, but in my main file it doesnt.
How do you think I could go about fixing this issue? I have looked through many videos and Im not sure why this doesn't work. The "rasp farm" function works and the cool down does too, but I want a message to appear when there is a cool down, with this code I get the error

# python main.py

import os
import discord
import wikipedia
from discord.utils import get
import time
import random
from discord.ext.commands import Bot
import asyncio
import json
from discord.ext.commands import cooldown, BucketType
from dotenv import load_dotenv
from discord.ext import commands

os.chdir(r"C:\Users\laksh\PycharmProjects\Raspberry")
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()
bot = commands.Bot(command_prefix='rasp ')

# Start up
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

@bot.command()
async def balance(ctx):
    await open_account(ctx.author)

    user = ctx.author
    users = await get_bank_data()

    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]
    em = discord.Embed(title=f"{ctx.author.name}'s raspberries", color=discord.Color.red())
    em.add_field(name= "Wallet",value=wallet_amt)
    em.add_field(name="Bank", value=bank_amt)
    await ctx.send(embed = em)

@commands.cooldown(1, 3, commands.BucketType.user)
@bot.command()
async def farm(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()
    earnings = random.randrange(201)

    await ctx.send(f"You picked {earnings} raspberries!! (Raspberries take 1 minute to grow again!)")

    users[str(user.id)]["wallet"] += earnings
    with open("mainbank.json","w") as f:
        users = json.dump(users,f)
@farm.error
async def farm_error(ctx, error):
    if isinstance(error, farm.CommandOnCooldown):
        em = discord.Embed(title=f"You are in cooldown",description=f"Try again in {error.retry_after:.2f}s.", color=discord.Color.orange())
        await ctx.send(embed=em)

async def open_account(user):
    users = await get_bank_data()
    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0
    with open("mainbank.json","w") as a:
        users = json.dump(users,a)
    return True

async def get_bank_data():
    with open("mainbank.json", "r") as a:
        users = json.load(a)
    return users

@bot.command()
async def commands(ctx):
    embed = discord.Embed(title="My commands:", description="My prefix is 'rasp' for example a command is 'rasp farm'.",
                          color=0xff4d4d)
    embed.add_field(name="'rasp farm'", value="Farms your ripened raspberries!                ", inline=True)
    embed.add_field(name=" 'rasp balance'", value="Checks how many raspberries your wallet and bank holds!",
                    inline=True)
    embed.add_field(name="'rasp shop'", value="Buy items to multiply your raspberry earnings :yum:", inline=True)
    await ctx.send(embed=embed)


问:
How to vectorize an expensive for loop in python
I have a pandas column which I have initialized with ones, this column represents the health of a solar panel.

I need to decay this value linearly unless the time has occurred where the panel will be replaced, here the value resets to 1 (hence why I have initialized to ones). What I am doing is looping through the column, then updating the current value with the value of the previous value, minus a constant.

This operation is extremely expensive (and I have over 200,000 samples). I was hoping someone might be able to help me with a vectorized solution, where I can avoid this for loop. Here is my code:

```<code>def set_degredation_factors_pv(df):
  for i in df.index:
    if i != replacement_duration_PV_year * hour_per_year and i != 0:
      df.loc[i, 'degradation_factor_PV_power_frac'] = df.loc[i-1, 'degradation_factor_PV_power_frac'] - degradation_rate_PV_power_perc_per_hour/100
  return df
</code>```

Variables:

```<code>replacement_duration_PV_year = 25
hour_per_year = 8760
degradation_rate_PV_power_perc_per_hour = 5.479e-5

</code>```

Input data:

```<code>time_datetime   degradation_factor_PV_power_frac
0   2022-01-01 00:00:00 1
1   2022-01-01 01:00:00 1
2   2022-01-01 02:00:00 1
3   2022-01-01 03:00:00 1
4   2022-01-01 04:00:00 1
... ... ...
8732    2022-12-30 20:00:00 1
8733    2022-12-30 21:00:00 1
8734    2022-12-30 22:00:00 1
8735    2022-12-30 23:00:00 1
8736    2022-12-31 00:00:00 1
</code>```

Output data (only taking one year for time):

```<code>time_datetime   degradation_factor_PV_power_frac
0   2022-01-01 00:00:00 1.000000
1   2022-01-01 01:00:00 0.999999
2   2022-01-01 02:00:00 0.999999
3   2022-01-01 03:00:00 0.999998
4   2022-01-01 04:00:00 0.999998
... ... ...
8732    2022-12-30 20:00:00 0.995216
8733    2022-12-30 21:00:00 0.995215
8734    2022-12-30 22:00:00 0.995215
8735    2022-12-30 23:00:00 0.995214
8736    2022-12-31 00:00:00 0.995214
</code>```

答:
Try:

```<code>rate = degradation_rate_PV_power_perc_per_hour / 100

mask = ~((df.index != replacement_duration_PV_year * hour_per_year)
         & (df.index != 0))

df['degradation_factor_PV_power_frac'] = (
    df.groupby(mask.cumsum())['degradation_factor_PV_power_frac']
      .apply(lambda x: x.shift().sub(rate).cumprod())
      .fillna(df['degradation_factor_PV_power_frac'])
)
</code>```

Output:

```<code>>>> df
         time_datetime  degradation_factor_PV_power_frac
0  2022-01-01 00:00:00                          1.000000
1  2022-01-01 01:00:00                          0.999999
2  2022-01-01 02:00:00                          0.999999
3  2022-01-01 03:00:00                          0.999998
4  2022-01-01 04:00:00                          0.999998
</code>```

Body:
I have a pandas column which I have initialized with ones, this column represents the health of a solar panel.

I need to decay this value linearly unless the time has occurred where the panel will be replaced, here the value resets to 1 (hence why I have initialized to ones). What I am doing is looping through the column, then updating the current value with the value of the previous value, minus a constant.

This operation is extremely expensive (and I have over 200,000 samples). I was hoping someone might be able to help me with a vectorized solution, where I can avoid this for loop. Here is my code:

def set_degredation_factors_pv(df):
  for i in df.index:
    if i != replacement_duration_PV_year * hour_per_year and i != 0:
      df.loc[i, 'degradation_factor_PV_power_frac'] = df.loc[i-1, 'degradation_factor_PV_power_frac'] - degradation_rate_PV_power_perc_per_hour/100
  return df

Variables:

replacement_duration_PV_year = 25
hour_per_year = 8760
degradation_rate_PV_power_perc_per_hour = 5.479e-5

Input data:

time_datetime   degradation_factor_PV_power_frac
0   2022-01-01 00:00:00 1
1   2022-01-01 01:00:00 1
2   2022-01-01 02:00:00 1
3   2022-01-01 03:00:00 1
4   2022-01-01 04:00:00 1
... ... ...
8732    2022-12-30 20:00:00 1
8733    2022-12-30 21:00:00 1
8734    2022-12-30 22:00:00 1
8735    2022-12-30 23:00:00 1
8736    2022-12-31 00:00:00 1

Output data (only taking one year for time):

time_datetime   degradation_factor_PV_power_frac
0   2022-01-01 00:00:00 1.000000
1   2022-01-01 01:00:00 0.999999
2   2022-01-01 02:00:00 0.999999
3   2022-01-01 03:00:00 0.999998
4   2022-01-01 04:00:00 0.999998
... ... ...
8732    2022-12-30 20:00:00 0.995216
8733    2022-12-30 21:00:00 0.995215
8734    2022-12-30 22:00:00 0.995215
8735    2022-12-30 23:00:00 0.995214
8736    2022-12-31 00:00:00 0.995214

Body:
Try:

rate = degradation_rate_PV_power_perc_per_hour / 100

mask = ~((df.index != replacement_duration_PV_year * hour_per_year)
         & (df.index != 0))

df['degradation_factor_PV_power_frac'] = (
    df.groupby(mask.cumsum())['degradation_factor_PV_power_frac']
      .apply(lambda x: x.shift().sub(rate).cumprod())
      .fillna(df['degradation_factor_PV_power_frac'])
)

Output:

>>> df
         time_datetime  degradation_factor_PV_power_frac
0  2022-01-01 00:00:00                          1.000000
1  2022-01-01 01:00:00                          0.999999
2  2022-01-01 02:00:00                          0.999999
3  2022-01-01 03:00:00                          0.999998
4  2022-01-01 04:00:00                          0.999998