问:
Add image fit to header using react-navigation V. 5+?
I want to add a custom header with a background color and also an image which need to be fit to header. I am using React Navigation 5+ ( @react-navigation/native, @react-navigation/stack ) but image isn't fit to header. Is there a way to add a custom header (something like passing component to it)?

 Here is how I was doing (Wanting to know if there is better way):

```<code>
import * as React from 'react';
import { View,Image, Text, TouchableWithoutFeedback, Button, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, HeaderTitle } from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/Ionicons';

const Stack = createStackNavigator();

class App extends React.Component {

  constructor(props) {
    super(props);

  }

  render () {
    return (
      <NavigationContainer>
      <Stack.Navigator>

        <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{
          headerBackground: props => <Header  {...this.props}/>,

        }}
        />
         <Stack.Screen
         name="FeedbackScreen"
         component={FeedbackScreen}

         />
      </Stack.Navigator>
    </NavigationContainer>
    )
  }
}

function HomeScreen({navigation}) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
      title="Feedback"
      onPress={()=> navigation.navigate('FeedbackScreen')}/>
    </View>
  );
}

function FeedbackScreen() {
  return (
    <View>

    </View>
  )
}

function Header() {

  return (
    <View style={{backgroundColor: "#4f2170", flex:1, }}>
      <Image style={StyleSheet.absoluteFill} source={require('./Images/Mon_logo.png')} />

    </View>
    );
}

export default App;
</code>```

I tried other answers but couldn't succeed...

答:
Complete Custom Header :</p>

```<code>import { Dimensions } from "react-native";

let {width,height} = Dimensions.get('window');

export default StyleSheet.create({
   container: {
        width: width,
        backgroundColor: '#00f7d2',
        elevation: 10,
    },
   row1: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 20,
    },
    row2: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    subLine: {
        color: '#000',
        fontWeight: '500',
        fontSize: 12
    },
    heading: {
        fontSize: 30,
        color: '#000',
        textAlign: 'center',
        width: width*0.75,
        fontWeight: 'bold'
    },
});

import React, { Component } from "react";
import {
    View,
    StatusBar,
    TouchableOpacity,
    Text,
    Dimensions,
} from "react-native";
import styles from '../styles/HeaderStyle';
import FaIcon from 'react-native-vector-icons/FontAwesome';
import {DrawerActions, createDrawerNavigator} from 'react-navigation';

class Header extends Component{

    constructor(props){
        super(props);
        this.state = {}
    };

render() {
        return (
            <View>
                <StatusBar backgroundColor="#00f7d2" barStyle="dark-content" />
                <View style={styles.container}>

                    <View style={styles.row1}>
                        {
                            this.props.goBack ?
                            <TouchableOpacity onPress={()=>{
                                this.props.propsRef.navigation.goBack();
                            }}>
                                <FaIcon name="arrow-left" size={30} color="#000"/>
                            </TouchableOpacity> :
                            <TouchableOpacity onPress={()=>{
                                this.props.propsRef.navigation.dispatch(DrawerActions.openDrawer());
                            }}>
                                <FaIcon name="bars" size={30} color="#000"/>
                            </TouchableOpacity>
                        }
                        <Text style={styles.heading}>
                        {
                            this.props.title ? this.props.title : "Credito"
                        }
                        </Text>
                    </View>ss

                </View>
            </View>
        );
    }
}

</code>```

Body:
I want to add a custom header with a background color and also an image which need to be fit to header. I am using React Navigation 5+ ( @react-navigation/native, @react-navigation/stack ) but image isn't fit to header. Is there a way to add a custom header (something like passing component to it)?

 Here is how I was doing (Wanting to know if there is better way):

import * as React from 'react';
import { View,Image, Text, TouchableWithoutFeedback, Button, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, HeaderTitle } from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/Ionicons';

const Stack = createStackNavigator();

class App extends React.Component {

  constructor(props) {
    super(props);

  }

  render () {
    return (
      <NavigationContainer>
      <Stack.Navigator>

        <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{
          headerBackground: props => ,

        }}
        />
         <Stack.Screen
         name="FeedbackScreen"
         component={FeedbackScreen}

         />
      </Stack.Navigator>
    </NavigationContainer>
    )
  }
}

function HomeScreen({navigation}) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
      title="Feedback"
      onPress={()=> navigation.navigate('FeedbackScreen')}/>
    </View>
  );
}

function FeedbackScreen() {
  return (
    <View>

    </View>
  )
}

function Header() {

  return (
    <View style={{backgroundColor: "#4f2170", flex:1, }}>
      <Image style={StyleSheet.absoluteFill} source={require('./Images/Mon_logo.png')} />

    </View>
    );
}

export default App;

I tried other answers but couldn't succeed...

Body:
Complete Custom Header :

import { Dimensions } from "react-native";

let {width,height} = Dimensions.get('window');

export default StyleSheet.create({
   container: {
        width: width,
        backgroundColor: '#00f7d2',
        elevation: 10,
    },
   row1: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 20,
    },
    row2: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    subLine: {
        color: '#000',
        fontWeight: '500',
        fontSize: 12
    },
    heading: {
        fontSize: 30,
        color: '#000',
        textAlign: 'center',
        width: width*0.75,
        fontWeight: 'bold'
    },
});

import React, { Component } from "react";
import {
    View,
    StatusBar,
    TouchableOpacity,
    Text,
    Dimensions,
} from "react-native";
import styles from '../styles/HeaderStyle';
import FaIcon from 'react-native-vector-icons/FontAwesome';
import {DrawerActions, createDrawerNavigator} from 'react-navigation';

class Header extends Component{

    constructor(props){
        super(props);
        this.state = {}
    };

render() {
        return (
            <View>
                <StatusBar backgroundColor="#00f7d2" barStyle="dark-content" />
                <View style={styles.container}>

                    <View style={styles.row1}>
                        {
                            this.props.goBack ?
                            <TouchableOpacity onPress={()=>{
                                this.props.propsRef.navigation.goBack();
                            }}>
                                <FaIcon name="arrow-left" size={30} color="#000"/>
                            </TouchableOpacity> :
                            <TouchableOpacity onPress={()=>{
                                this.props.propsRef.navigation.dispatch(DrawerActions.openDrawer());
                            }}>
                                <FaIcon name="bars" size={30} color="#000"/>
                            </TouchableOpacity>
                        }
                        <Text style={styles.heading}>
                        {
                            this.props.title ? this.props.title : "Credito"
                        }
                        </Text>
                    </View>ss

                </View>
            </View>
        );
    }
}


来源: stackexchange

问:
Javascript onclick form validation
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...</p>

```<code>function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >
</code>```

答:
format your if correctly, else it will consider only first statement.

```<code> for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       {
        alert('Please enter valid number');
        return false;
       }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript onclick form validation

Body:
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...

function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >

Body:
format your if correctly, else it will consider only first statement.

 for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       {
        alert('Please enter valid number');
        return false;
       }
    }


问:
How to call a Python function from Node.js
I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?</p>

答:
```<code>/*eslint-env es6*/
/*global require*/
/*global console*/
var express = require('express');
var app = express();

// Creates a server which runs on port 3000 and
// can be accessed through localhost:3000
app.listen(3000, function() {
    console.log('server running on port 3000');
} )

app.get('/name', function(req, res) {

    console.log('Running');

    // Use child_process.spawn method from
    // child_process module and assign it
    // to variable spawn
    var spawn = require("child_process").spawn;
    // Parameters passed in spawn -
    // 1. type_of_script
    // 2. list containing Path of the script
    //    and arguments for the script

    // E.g : http://localhost:3000/name?firstname=Levente
    var process = spawn('python',['apiTest.py',
                        req.query.firstname]);

    // Takes stdout data from script which executed
    // with arguments and send this data to res object
    var output = '';
    process.stdout.on('data', function(data) {

        console.log("Sending Info")
        res.end(data.toString('utf8'));
    });

    console.log(output);
});
</code>```

This worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder.

ContentLicense: CC BY-SA 4.0

Body:
/*eslint-env es6*/
/*global require*/
/*global console*/
var express = require('express');
var app = express();

// Creates a server which runs on port 3000 and
// can be accessed through localhost:3000
app.listen(3000, function() {
    console.log('server running on port 3000');
} )

app.get('/name', function(req, res) {

    console.log('Running');

    // Use child_process.spawn method from
    // child_process module and assign it
    // to variable spawn
    var spawn = require("child_process").spawn;
    // Parameters passed in spawn -
    // 1. type_of_script
    // 2. list containing Path of the script
    //    and arguments for the script

    // E.g : http://localhost:3000/name?firstname=Levente
    var process = spawn('python',['apiTest.py',
                        req.query.firstname]);

    // Takes stdout data from script which executed
    // with arguments and send this data to res object
    var output = '';
    process.stdout.on('data', function(data) {

        console.log("Sending Info")
        res.end(data.toString('utf8'));
    });

    console.log(output);
});

This worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder.


问:
Python Constructor Overloading
I have come across the notion of class constructors in C++. But I have not yet found a way to initialize a class in Python using 2 or more different methods. Could anyone tell how to go about that?</p>

答:
You don't need multiple constructors in python, you can use the following way to initialize if you have multiple such a case

```<code>class A:
    def __init__(self, arg_1, arg_2=None):
        self.arg_1 = arg_1
        self.arg_2 = arg_2
</code>```

So when you need to initialize an object of class A, you can use

```<code>a1 = A(2)
a2 = A(2, 4)
</code>```

Though strictly speaking __init__ is not a constructor but an initialiser

Title: Python Constructor Overloading

Body:
You don't need multiple constructors in python, you can use the following way to initialize if you have multiple such a case

class A:
    def __init__(self, arg_1, arg_2=None):
        self.arg_1 = arg_1
        self.arg_2 = arg_2

So when you need to initialize an object of class A, you can use

a1 = A(2)
a2 = A(2, 4)

Though strictly speaking __init__ is not a constructor but an initialiser


问:
Markdown Math does not display correctly when deploying Pelican website to Heroku
Problem: I've downloaded the 'render_math' plugin for my pelican website to create math formulas in markdown. They display correctly when running locally using pelican --listen, but when I deploy the site to Heroku, the formulas do not display correctly, as shown in the picture below:

My markdown for the formula:

```<code>## $$l_t=\beta_0+\beta_1l_{t-1} + \phi_1\epsilon_{t-1}+\epsilon_t$$
</code>```

How it should look when viewed:

Attempted solution: I've included the following plugins path and the plugin used in my pelican config file, but to no effect and no errors are given. It should create a 'span' element in the HTML containing the Math, but it seems to only generate an 'H2' element.

```<code>PLUGIN_PATHS = ["/content/plugins"]
PLUGINS = ["render_math"]
</code>```

How can I make my math formulas display correctly using markdown when deploying the site to heroku?

答: The problem lay instead in how MathJax was added to the site and was causing mixed content errors. I switched the CDN link from HTTP to HTTPS, which solved my issue. </p>

Body:
Problem: I've downloaded the 'render_math' plugin for my pelican website to create math formulas in markdown. They display correctly when running locally using pelican --listen, but when I deploy the site to Heroku, the formulas do not display correctly, as shown in the picture below:

My markdown for the formula:

## $$l_t=\beta_0+\beta_1l_{t-1} + \phi_1\epsilon_{t-1}+\epsilon_t$$

How it should look when viewed:

Attempted solution: I've included the following plugins path and the plugin used in my pelican config file, but to no effect and no errors are given. It should create a 'span' element in the HTML containing the Math, but it seems to only generate an 'H2' element.

PLUGIN_PATHS = ["/content/plugins"]
PLUGINS = ["render_math"]

How can I make my math formulas display correctly using markdown when deploying the site to heroku?


问:
Closing a pdf by reading the file size
I am auto creating pdf's from a list of items in excel.  Everything is working fine but sometimes the created pdf is corrupted since the program closes the original too fast.  I realize I could add time to the Application.Wait but sometimes that will add a lot of time if the list is very long.  I am trying to read the file size using FileLen and looping until that value is greater than 0 and then close the file.  My code below is throwing an error saying Next without For.

Any help is appreciated.

```<code>For WaitTime = 0 To 0.5
If FileLen(SavePDFFldr & "\" & Description & ".pdf") > 10 Then
    Application.SendKeys "^(q)", True
    Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
    Application.SendKeys "{Tab}", True
    Application.SendKeys "{Enter}", True
Else: Next WaitTime
</code>```

Where the SavePDFFldr and Description are set prior to this.

答:
Based on the comments you could add a "infinite" loop</p>

```<code>    Do While FileLen(SavePDFFldr & "\" & Description & ".pdf") < 10
        ' Dangerous this could end up in a endless loop
        ' we just loop and give other applications time
        ' to do something
        DoEvents
    Loop

 ' Hopefully you get here
        Application.SendKeys "^(q)", True
        Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
        Application.SendKeys "{Tab}", True
        Application.SendKeys "{Enter}", True
</code>```

Title: Closing a pdf by reading the file size

Body:
I am auto creating pdf's from a list of items in excel.  Everything is working fine but sometimes the created pdf is corrupted since the program closes the original too fast.  I realize I could add time to the Application.Wait but sometimes that will add a lot of time if the list is very long.  I am trying to read the file size using FileLen and looping until that value is greater than 0 and then close the file.  My code below is throwing an error saying Next without For.

Any help is appreciated.

For WaitTime = 0 To 0.5
If FileLen(SavePDFFldr & "\" & Description & ".pdf") > 10 Then
    Application.SendKeys "^(q)", True
    Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
    Application.SendKeys "{Tab}", True
    Application.SendKeys "{Enter}", True
Else: Next WaitTime

Where the SavePDFFldr and Description are set prior to this.

Body:
Based on the comments you could add a "infinite" loop

    Do While FileLen(SavePDFFldr & "\" & Description & ".pdf") < 10
        ' Dangerous this could end up in a endless loop
        ' we just loop and give other applications time
        ' to do something
        DoEvents
    Loop

 ' Hopefully you get here
        Application.SendKeys "^(q)", True
        Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
        Application.SendKeys "{Tab}", True
        Application.SendKeys "{Enter}", True


问:
.Git inside git repo and branch are not showing
I'm running into trouble with my git repo. I had a bunch of branch that I realize are missing and I came to this conclusion. My file structure looks like this

```<code>REPO-A
  -/hooks
  -/info
  -/objects
  -/ref
  -config
  -description
  -HEAD
  -packed-ref
  -/.git
    --/hooks
    --/info
    --/log
    --/objects
    --/ref
    --COMMITMESSAGE
    --config
    --description
    --FETCH_HEAD
    --HEAD
</code>```

When I clone my repo I only see some of my branches that I had and I only have one submodule. If however I delete the /.git file and everything contained under it, I get all my branches back but the ones that I see when the /.git file there are out of date. I was wondering what has happened and how to undo it? I've searched all the reflogs of everyone who’s pushes to the repo but they seem to be all pushes, so I'm a little lost. Any help would be appreciated!

答:
git commands will determine where the git repo is in the following way :

it will look for .git/ in .,

if not present, it will go up one level, and look for .git/

if not present, it will go up one level, ...

So :

deleting the .git/ directory means deleting the repository part, and keeping only the files on disk as they are,

if something shows up when you run some git command, this indicates that there is a .git/ directory in some parent directory.

You can run git rev-parse --show-toplevel to view what git chose as the base directory of your repo.

If you want to update the branches in that repo, use git fetch and git pull.

Body:
I'm running into trouble with my git repo. I had a bunch of branch that I realize are missing and I came to this conclusion. My file structure looks like this

REPO-A
  -/hooks
  -/info
  -/objects
  -/ref
  -config
  -description
  -HEAD
  -packed-ref
  -/.git
    --/hooks
    --/info
    --/log
    --/objects
    --/ref
    --COMMITMESSAGE
    --config
    --description
    --FETCH_HEAD
    --HEAD

When I clone my repo I only see some of my branches that I had and I only have one submodule. If however I delete the /.git file and everything contained under it, I get all my branches back but the ones that I see when the /.git file there are out of date. I was wondering what has happened and how to undo it? I've searched all the reflogs of everyone who’s pushes to the repo but they seem to be all pushes, so I'm a little lost. Any help would be appreciated!


问:
merge some ogg audio files using java programming language
I have some .ogg sound files that must be merged together.But the problem is in that the java only support .wav extension (as I used AudioSystem and AudioInputStream).

I've searched among different pages for converting and I've not found a better way than.

Do you know a better way other than using Command line tool?

答:
I think you may have to inspect and tinker with the source code. This can be obtained from various libraries that have JOrbis and other files needed for ogg playback and encoding (there are several on github).

For a project where I needed to load decompressed ogg files (that were originally wav) into memory, I used source code from the example OggPlayer (usually included in the package) and intercepted the bytes before they were written to a SourceDataLine. You can maybe also find a hook in example code that compresses wav to ogg and then link the two parts.


问:
How to print numbers in order using goroutine after emit all the goroutine
How to print numbers in order using goroutine after all goroutines bing emited?

Here is the code which print numbers in random:

```<code>func main() {

    var wg sync.WaitGroup
    wg.Add(10)
    for i := 1; i <= 10; i++ {
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
    }
    wg.Wait()
</code>```

Emit goroutines in order to print numbers like below, it's not the solution I want.

```<code>func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
        wg.Wait()
    }
</code>```

I want all goroutines being emited, and after then make them print numbers in order.

答:
func main() {
    wg.Add(10)
    count := 10
    cBegins := make([]chan interface{}, count)
    for i := range cBegins {
        cBegins[i] = make(chan interface{})
    }
    go func() {
        cBegins[0] <- struct {}{}
    }()
    for i := 0; i < count; i++ {
        go func(i int) {
            defer wg.Done()
            <-cBegins[i]
            fmt.Printf("i = %d\n", i)
            if i < 9 {
                cBegins[i+1] <- struct {}{}
            }
        }(i)
    }

    wg.Wait()

}
```

Body:
How to print numbers in order using goroutine after all goroutines bing emited?

Here is the code which print numbers in random:

func main() {

    var wg sync.WaitGroup
    wg.Add(10)
    for i := 1; i <= 10; i++ {
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
    }
    wg.Wait()

Emit goroutines in order to print numbers like below, it's not the solution I want.

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
        wg.Wait()
    }

I want all goroutines being emited, and after then make them print numbers in order.


问:
Why am I getting this TypeError when I try to slice my Pandas DataFrame?
I pulled some stock data from a financial API and created a DataFrame with it. Columns were 'date', 'data1', 'data2', 'data3'.  Then, I converted that DataFrame into a CSV with 'date' column as index:

```<code>df.to_csv('data.csv', index_label='date')
</code>```

In a second script, I read that CSV and attempted to slice the resulting DataFrame between two dates:

```<code>df = pd.read_csv('data.csv', parse_dates=['date'] ,index_col='date')
df = df['2020-03-28':'2020-04-28']
</code>```

When I attempt to do this, I get the following TypeError:

```<code>TypeError: cannot do slice indexing on <class 'pandas.core.indexes.numeric.Int64Index'> with these indexers [2020-03-28] of <class 'str'>
</code>```

So clearly, the problem is that I'm trying to use a str to slice a datetime object.  But here's the confusing part!  If in the first step, I save the DataFrame to a csv and DO NOT set 'date' as index:

```<code>df.to_csv('data.csv')
</code>```

In my second script, I no longer get the TypeError:

```<code>df = pd.read_csv('data.csv', parse_dates=['date'] ,index_col='date')
df = df['2020-03-28':'2020-04-28']
</code>```

Now it works just fine.  The only problem is I have the default Pandas index column to deal with.

Why do I get a TypeError when I set the 'date' column as index in my CSV...but I do NOT get a TypeError when I don't set any index in the CSV?

答:
It seems that in your "first" instance of df, date column was an
ordinary column (not the index) and this DataFrame had a default
index - consecutive integers (its name is not important).

In this situation running df.to_csv('data.csv', index_label='date')
causes that the output file contains:

```<code>date,date,data1,data2,data3
0,2020-03-27,10.5,12.3,13.2
1,2020-03-28,10.6,12.9,14.7
</code>```

i.e.:

the index column (integers) was given date name, passed by you in
index_label parameter,

the next column, which in df was named date was also
given date name.

Then if you read it running
df = pd.read_csv('data.csv', parse_dates=['date'], index_col='date'), then:

the first date column (integers) has been read as date and
set as the index,

the second date column (dates) has been read as date.1 and
it is an ordinary column.

Now when you run df['2020-03-28':'2020-04-28'], you attempt to find rows
with index in the range given. But the index column is of Int64Index
type (check this in your installation), hence just the mentioned exception
was thrown.

Things look other way when you run df.to_csv('data.csv').
Now this file contains:

```<code>,date,data1,data2,data3
0,2020-03-27,10.5,12.3,13.2
1,2020-03-28,10.6,12.9,14.7
</code>```

i.e.:

the first column (which in df was the index) has no name and int
values,

the only column named date is the second column and contains
dates.

Now when you read it, the result is:

date (converted do DatetimeIndex) is the index,

the original index column got name Unnamed: 0, no surprise,
since in the source file it had no name.

And now, when you run df['2020-03-28':'2020-04-28'] everything is OK.

The thing to learn for the future:
Running df.to_csv('data.csv', index_label='date') does not set this
column as the index. It only saves the current index column
under the given name, without any check whether any other column has
just the same name.

The result is that 2 columns can have the same name.

Body:
I pulled some stock data from a financial API and created a DataFrame with it. Columns were 'date', 'data1', 'data2', 'data3'.  Then, I converted that DataFrame into a CSV with 'date' column as index:

df.to_csv('data.csv', index_label='date')

In a second script, I read that CSV and attempted to slice the resulting DataFrame between two dates:

df = pd.read_csv('data.csv', parse_dates=['date'] ,index_col='date')
df = df['2020-03-28':'2020-04-28']

When I attempt to do this, I get the following TypeError:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.numeric.Int64Index'> with these indexers [2020-03-28] of <class 'str'>

So clearly, the problem is that I'm trying to use a str to slice a datetime object.  But here's the confusing part!  If in the first step, I save the DataFrame to a csv and DO NOT set 'date' as index:

df.to_csv('data.csv')

In my second script, I no longer get the TypeError:

df = pd.read_csv('data.csv', parse_dates=['date'] ,index_col='date')
df = df['2020-03-28':'2020-04-28']

Now it works just fine.  The only problem is I have the default Pandas index column to deal with.

Why do I get a TypeError when I set the 'date' column as index in my CSV...but I do NOT get a TypeError when I don't set any index in the CSV?

Body:
It seems that in your "first" instance of df, date column was an
ordinary column (not the index) and this DataFrame had a default
index - consecutive integers (its name is not important).

In this situation running df.to_csv('data.csv', index_label='date')
causes that the output file contains:

date,date,data1,data2,data3
0,2020-03-27,10.5,12.3,13.2
1,2020-03-28,10.6,12.9,14.7

i.e.:

the index column (integers) was given date name, passed by you in
index_label parameter,

the next column, which in df was named date was also
given date name.

Then if you read it running
df = pd.read_csv('data.csv', parse_dates=['date'], index_col='date'), then:

the first date column (integers) has been read as date and
set as the index,

the second date column (dates) has been read as date.1 and
it is an ordinary column.

Now when you run df['2020-03-28':'2020-04-28'], you attempt to find rows
with index in the range given. But the index column is of Int64Index
type (check this in your installation), hence just the mentioned exception
was thrown.

Things look other way when you run df.to_csv('data.csv').
Now this file contains:

,date,data1,data2,data3
0,2020-03-27,10.5,12.3,13.2
1,2020-03-28,10.6,12.9,14.7

i.e.:

the first column (which in df was the index) has no name and int
values,

the only column named date is the second column and contains
dates.

Now when you read it, the result is:

date (converted do DatetimeIndex) is the index,

the original index column got name Unnamed: 0, no surprise,
since in the source file it had no name.

And now, when you run df['2020-03-28':'2020-04-28'] everything is OK.

The thing to learn for the future:
Running df.to_csv('data.csv', index_label='date') does not set this
column as the index. It only saves the current index column
under the given name, without any check whether any other column has
just the same name.

The result is that 2 columns can have the same name.


问:
How do I pass "x-ms-client-principal" in Azure Static Website Hosting (Preview) when running locally?
I'm trying out the new Azure Static Website Hosting Preview and when running locally, the Azure functions aren't receiving the "x-ms-client-principle" header in the req binding object.

My routes file looks like:

```<code>{
  "routes": [
    {
      "route": "/api/*",
      "allowedRoles": ["administrator"]
    },
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ]
}
</code>```

My API function is getting hit at: /api/message, but isn't including the header.

```<code>module.exports = async function (context, req) {
  const header = req.headers["x-ms-client-principal"]; // req.headers doesn't include x-ms-client-principle
  const encoded = Buffer.from(header, "base64");
  const decoded = encoded.toString("ascii");
}
</code>```

The static app is a React static page created with create-react-app. I have a line to print out the result from the react-app:

```<code>fetch(`${process.env.REACT_APP_API}/message?name=me`)
  .then(a => a.text())
  .then(console.log);
</code>```

Locally process.env.REACT_APP_API is set via REACT_APP_API=http://127.0.0.1:7071/api.

The API is getting hit, but I'm not sure if it's running the correct version of Azure Functions. It is reporting: Function Runtime Version: 2.0.12961.0 even though I've installed azure-functions-core-tools@3, and set the proper value ("azureFunctions.projectRuntime": "~3") in settings.json.

My question is am I missing something, and if so, what?

答:
For the moment, it appears that this is not a supported scenario per:

https://github.com/MicrosoftDocs/azure-docs/issues/55517

Body:
I'm trying out the new Azure Static Website Hosting Preview and when running locally, the Azure functions aren't receiving the "x-ms-client-principle" header in the req binding object.

My routes file looks like:

{
  "routes": [
    {
      "route": "/api/*",
      "allowedRoles": ["administrator"]
    },
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ]
}

My API function is getting hit at: /api/message, but isn't including the header.

module.exports = async function (context, req) {
  const header = req.headers["x-ms-client-principal"]; // req.headers doesn't include x-ms-client-principle
  const encoded = Buffer.from(header, "base64");
  const decoded = encoded.toString("ascii");
}

The static app is a React static page created with create-react-app. I have a line to print out the result from the react-app:

fetch(`${process.env.REACT_APP_API}/message?name=me`)
  .then(a => a.text())
  .then(console.log);

Locally process.env.REACT_APP_API is set via REACT_APP_API=http://127.0.0.1:7071/api.

The API is getting hit, but I'm not sure if it's running the correct version of Azure Functions. It is reporting: Function Runtime Version: 2.0.12961.0 even though I've installed azure-functions-core-tools@3, and set the proper value ("azureFunctions.projectRuntime": "~3") in settings.json.

My question is am I missing something, and if so, what?


问:
Permission denied with apache filter
I use apache httpd on Centos7 (SELinux) and am trying to create an output filter to modify all served html pages. I've browsed some tutorials on how to create them, but I keep stumbling on step one even before I get to the coding part.

Currently I have this in my httpd.conf

```<code>ExtFilterDefine portal_header mode=output intype=text/html cmd="/var/www/root/main/portal/portal.php"
SetOutputFilter portal_header
</code>```

To pinpoint my problem I have deleted all the actual code in the file /var/www/root/main/portal/portal.php for the moment and currently it looks like this

```<code>#!/usr/bin/php
<php?
  /* test */
?>
</code>```

But when I know try to access any html on the server I get "500 Internal Server Error". After commenting out the SetOutputFilter line in httpd.conf the pages work so the error is generated by the filter.

In my error log it reads

```<code>[Fri Feb 10 14:36:55.458174 2017] [ext_filter:error] [pid 171495] (13)Permission denied: [client 10.2.8.109:49278] AH01458: couldn't create child process to run `/var/www/root/main/portal/portal.php'
[Fri Feb 10 14:36:55.458215 2017] [ext_filter:error] [pid 171495] (13)Permission denied: [client 10.2.8.109:49278] AH01467: can't initialise output filter portal_header: aborting
</code>```

I have at least

changed the file permissions to 777

verified that php is located at /usr/bin/php and owned by apache group with proper rights

tried to add and remove ScriptAlias and/or SetHander cgi-script for the directory in httpd.conf

tried with completely empty script file

but none of the above has any effect. The only change in matters was that when I deliberately mis-spelled the file name I got "No such file or directory" error instead.

Does anyone have an idea what I should do to make this work? For the moment I would be happy to see the script to even do nothing at all, if it just didn't break, and only afterwards add some functionalities into it.

UPDATE: I was able to pinpoint the problem to SELinux policies, since after disabling them (setenforce 0) the error vanished. So currently I'm trying to figure out how I should alter the policies.

答:
I ran into a similar problem when trying to improve on a simple sed filter command.
According to the https://httpd.apache.org/docs/2.4/mod/mod_ext_filter.html documentation it should be possible to use a command like sed as a filter and indeed it does:

The following filter works for me and replaces global links to local ones so that i can use a docker image with data from an existing site.

```<code># Filter configuration
# mod_ext_filter directive to define a filter which
# replaces text in the response
#
ExtFilterDefine fixtext mode=output intype=text/html \
    cmd="/bin/sed s#http://ceur.ws.org#http://capri:8880#g"

<Location "/">
    # core directive to cause the fixtext filter to
    # be run on output
    SetOutputFilter fixtext
</Location>
</code>```

when trying to replace the sed command with accessing a script with

```<code>"cmd=/root/bin/filter.sh"
</code>```

I got the error message :

```<code>AH01458: couldn't create child process to run `/root/bin/filter.sh'
AH01467: can't initialise output filter fixtext: aborting
</code>```

which is your original reason for your question.

Now i am also looking for a better solution and tried:

```<code>cmd="/bin/bash /root/bin/filter.sh"
</code>```

assuming that the shebang resolving might be the culprit. Interestingly i then get:

```<code>AH01461: apr_file_write(child input), len 0
AH01468: ef_unified_filter() failed
</code>```

and that's why i am already posting this answer in the hope I'll find a proper solution soon or others might be able to help because the list of related AH014## error codes is getting longer in this Q&A thread.

See https://github.com/omnigroup/Apache/blob/master/httpd/modules/filters/mod_ext_filter.c for the relevant source code.

I am assuming that the apr_proc_create is not capable of calling scripts using a shebang. So my workaround was to

call the command directly

switch to awk

Working apache filter.conf

```<code># Filter configuration
# mod_ext_filter directive to define a filter which
# replaces text in the response
#
ExtFilterDefine fixtext mode=output intype=text/html \
    cmd="/usr/bin/awk -f /var/www/filter.awk"

<Location "/">
    # core directive to cause the fixtext filter to
    # be run on output
    SetOutputFilter fixtext
</Location>
</code>```

working awk script to filter links

```<code># WF 2020-06-03
#
# filter HTML output thru this awk script to fix global links to local ones
#
# you might want to try out this filter from the command line with
# cat /var/www/html/index.html | awk -f filter.awk
#
# setup the  replacement
BEGIN {
  port=8880
  host="capri"
  sourceServer="http://ceur-ws.org"
  targetServer=sprintf("http://%s:%s",host,port)
}
# for each line
{
  # get the line
  line=$0
  # replace any sourceServer reference with the targetServer reference
  gsub(sourceServer,targetServer,line)
  # output the modified line
  print line
}
</code>```

/root/bin/filters.sh

```<code>#!/bin/bash
# WF 2020-06-02
# filter all html output thru this script
port=8880
host=capri
# substitute all hard links in CEUR-WS with a local link
/bin/sed s#http://ceur.ws.org#http://$host:$port#g
# try out this filter with
# cat /var/www/html/index.html | /root/bin/filter.sh | grep capri
</code>```

Title: Permission denied with apache filter

Body:
I use apache httpd on Centos7 (SELinux) and am trying to create an output filter to modify all served html pages. I've browsed some tutorials on how to create them, but I keep stumbling on step one even before I get to the coding part.

Currently I have this in my httpd.conf

ExtFilterDefine portal_header mode=output intype=text/html cmd="/var/www/root/main/portal/portal.php"
SetOutputFilter portal_header

To pinpoint my problem I have deleted all the actual code in the file /var/www/root/main/portal/portal.php for the moment and currently it looks like this

#!/usr/bin/php
<php?
  /* test */
?>

But when I know try to access any html on the server I get "500 Internal Server Error". After commenting out the SetOutputFilter line in httpd.conf the pages work so the error is generated by the filter.

In my error log it reads

[Fri Feb 10 14:36:55.458174 2017] [ext_filter:error] [pid 171495] (13)Permission denied: [client 10.2.8.109:49278] AH01458: couldn't create child process to run `/var/www/root/main/portal/portal.php'
[Fri Feb 10 14:36:55.458215 2017] [ext_filter:error] [pid 171495] (13)Permission denied: [client 10.2.8.109:49278] AH01467: can't initialise output filter portal_header: aborting

I have at least

changed the file permissions to 777

verified that php is located at /usr/bin/php and owned by apache group with proper rights

tried to add and remove ScriptAlias and/or SetHander cgi-script for the directory in httpd.conf

tried with completely empty script file

but none of the above has any effect. The only change in matters was that when I deliberately mis-spelled the file name I got "No such file or directory" error instead.

Does anyone have an idea what I should do to make this work? For the moment I would be happy to see the script to even do nothing at all, if it just didn't break, and only afterwards add some functionalities into it.

UPDATE: I was able to pinpoint the problem to SELinux policies, since after disabling them (setenforce 0) the error vanished. So currently I'm trying to figure out how I should alter the policies.

Body:
I ran into a similar problem when trying to improve on a simple sed filter command.
According to the https://httpd.apache.org/docs/2.4/mod/mod_ext_filter.html documentation it should be possible to use a command like sed as a filter and indeed it does:

The following filter works for me and replaces global links to local ones so that i can use a docker image with data from an existing site.

# Filter configuration
# mod_ext_filter directive to define a filter which
# replaces text in the response
#
ExtFilterDefine fixtext mode=output intype=text/html \
    cmd="/bin/sed s#http://ceur.ws.org#http://capri:8880#g"

<Location "/">
    # core directive to cause the fixtext filter to
    # be run on output
    SetOutputFilter fixtext
</Location>

when trying to replace the sed command with accessing a script with

"cmd=/root/bin/filter.sh"

I got the error message :

AH01458: couldn't create child process to run `/root/bin/filter.sh'
AH01467: can't initialise output filter fixtext: aborting

which is your original reason for your question.

Now i am also looking for a better solution and tried:

cmd="/bin/bash /root/bin/filter.sh"

assuming that the shebang resolving might be the culprit. Interestingly i then get:

AH01461: apr_file_write(child input), len 0
AH01468: ef_unified_filter() failed

and that's why i am already posting this answer in the hope I'll find a proper solution soon or others might be able to help because the list of related AH014## error codes is getting longer in this Q&A thread.

See https://github.com/omnigroup/Apache/blob/master/httpd/modules/filters/mod_ext_filter.c for the relevant source code.

I am assuming that the apr_proc_create is not capable of calling scripts using a shebang. So my workaround was to

call the command directly

switch to awk

Working apache filter.conf

# Filter configuration
# mod_ext_filter directive to define a filter which
# replaces text in the response
#
ExtFilterDefine fixtext mode=output intype=text/html \
    cmd="/usr/bin/awk -f /var/www/filter.awk"

<Location "/">
    # core directive to cause the fixtext filter to
    # be run on output
    SetOutputFilter fixtext
</Location>

working awk script to filter links

# WF 2020-06-03
#
# filter HTML output thru this awk script to fix global links to local ones
#
# you might want to try out this filter from the command line with
# cat /var/www/html/index.html | awk -f filter.awk
#
# setup the  replacement
BEGIN {
  port=8880
  host="capri"
  sourceServer="http://ceur-ws.org"
  targetServer=sprintf("http://%s:%s",host,port)
}
# for each line
{
  # get the line
  line=$0
  # replace any sourceServer reference with the targetServer reference
  gsub(sourceServer,targetServer,line)
  # output the modified line
  print line
}

/root/bin/filters.sh

#!/bin/bash
# WF 2020-06-02
# filter all html output thru this script
port=8880
host=capri
# substitute all hard links in CEUR-WS with a local link
/bin/sed s#http://ceur.ws.org#http://$host:$port#g
# try out this filter with
# cat /var/www/html/index.html | /root/bin/filter.sh | grep capri


问:
HttpException: Connection closed before full header was received
I am trying to make post call as the code bellow shows.

```<code>  Map<String, String> header = {"Content-Type": "application/json"};
  Map<String, String> body = {
    "client_id": "xxxx",
    "client_secret": "XXXX",
    "password": "password",
    "username": "username",
  };

  Future<Post> callForFirstToken() async {
    final response = await http.post(url, headers: header, body: body);
    return response.statusCode == 200
      ? Post.fromJson(json.decode(response.body))
      : throw Exception('Failed to load ...');}
</code>```

But, I have got this error:

```<code>Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:60556/sK_cPlYMcGQ=/ws
</code>```

答:
This might be an issue with setting up Skia Gr context.
Try using flutter run --enable-software-rendering instead of just run.

Body:
I am trying to make post call as the code bellow shows.

  Map<String, String> header = {"Content-Type": "application/json"};
  Map<String, String> body = {
    "client_id": "xxxx",
    "client_secret": "XXXX",
    "password": "password",
    "username": "username",
  };

  Future<Post> callForFirstToken() async {
    final response = await http.post(url, headers: header, body: body);
    return response.statusCode == 200
      ? Post.fromJson(json.decode(response.body))
      : throw Exception('Failed to load ...');}

But, I have got this error:

Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:60556/sK_cPlYMcGQ=/ws


问:
Insert object to specific list index
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

```<code>list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)
</code>```

Output:

```<code>['String1', None, None, 'String2']
</code>```

答:
Create your list like this:

```<code>initial_size = 4
list = [None] * initial_size
list[0] = 'String1'
list[3] = 'String2'
print(list)           # ['String1', None, None, 'String2']
</code>```

To increase size of list / add more spaces:

```<code>spaces_to_add = 5
list += [None] * spaces_to_add
print(list)           # ['String1', None, None, 'String2', None, None, None, None]
</code>```

Title: Insert object to specific list index

Body:
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

Output:

['String1', None, None, 'String2']

Body:
Create your list like this:

initial_size = 4
list = [None] * initial_size
list[0] = 'String1'
list[3] = 'String2'
print(list)           # ['String1', None, None, 'String2']

To increase size of list / add more spaces:

spaces_to_add = 5
list += [None] * spaces_to_add
print(list)           # ['String1', None, None, 'String2', None, None, None, None]


问:
Unable to consume messages with Camel 3.3 and Google Pubsub
I have a small groovy script with Apache camel that is attempting to pull messages from Google Pubsub. This works well on Camel 2.25.1, but camel 3.3.0 does not. Here is the script. I also looked at the Camel 2.x to 3.0 migration guide, but I am unable to find anything relevant to this issue, but perhaps I am mistaken and I would need some help.

My groovy version is 3.0.4 and I am using JDK 11.0.6

```<code>@Grapes([
    @Grab(group='org.apache.camel', module='camel-core', version='3.3.0'),
    @Grab(group='org.apache.camel', module='camel-google-pubsub', version='3.3.0'),
    @Grab(group='org.slf4j', module='slf4j-api', version='1.7.30'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='1.2.3'),
])

import org.apache.camel.CamelContext
import org.apache.camel.impl.DefaultCamelContext
import org.apache.camel.builder.RouteBuilder

main()

def main() {
    println "downloaded camel dependencies"
    CamelContext context = new DefaultCamelContext()

    context.addRoutes(new ReadFromQueueWithPubsub())
    context.start()
    addShutdownHook { context.stop() }
    synchronized(this){ this.wait() }
}

class ReadFromQueueWithPubsub extends RouteBuilder {

    @Override
    void configure() {
        from("google-pubsub://my_gcp_project:transaction-test-subscriber")
        .to("log:input?showAll=true")

    }
}
</code>```

Here is the snippet of logs in debug mode. I can't see anything that's relevant here, but I may be mistaken.

```<code>2020-05-28 07:14:51 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Apache Camel 3.3.0 (CamelContext: camel-1) is starting
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using ClassResolver=org.apache.camel.impl.engine.DefaultClassResolver@25478603, PackageScanClassResolver=org.apache.camel.impl.engine.DefaultPackageScanClassResolver@3c7dbf1f, ApplicationContextClassLoader=null, RouteController=org.apache.camel.impl.engine.DefaultRouteController@2efbe938
2020-05-28 07:14:51 INFO  [o.a.c.i.e.AbstractCamelContext          ] - StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using HeadersMapFactory: org.apache.camel.impl.engine.DefaultHeadersMapFactory@12459991
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using ReactiveExecutor: org.apache.camel.impl.engine.DefaultReactiveExecutor@43114981
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Warming up route id: route1 having autoStartup=true
2020-05-28 07:14:51 DEBUG [o.a.c.s.DefaultProducer                 ] - Starting producer: Producer[log://input?showAll=true]
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Route: route1 >>> Route[google-pubsub://my_gcp_project:transaction-test-subscriber -> null]
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Starting consumer (order: 1000) on route: route1
2020-05-28 07:14:52 DEBUG [o.a.c.s.DefaultConsumer                 ] - Init consumer: Consumer[google-pubsub://my_gcp_project:transaction-test-subscriber]
2020-05-28 07:14:52 DEBUG [o.a.c.s.DefaultConsumer                 ] - Starting consumer: Consumer[google-pubsub://my_gcp_project:transaction-test-subscriber]
2020-05-28 07:14:52 INFO  [o.a.c.c.g.p.GooglePubsubConsumer        ] - Starting Google PubSub consumer for my_gcp_project/transaction-test-subscriber
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.BaseExecutorServiceManager    ] - Created new ThreadPool for source: google-pubsub://my_gcp_project:transaction-test-subscriber with name: GooglePubsubConsumer[transaction-test-subscriber]. -> org.apache.camel.util.concurrent.RejectableThreadPoolExecutor@7d726fa1[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0][GooglePubsubConsumer[transaction-test-subscriber]]
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Route: route1 started and consuming from: google-pubsub://my_gcp_project:transaction-test-subscriber
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Total 1 routes, of which 1 are started
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Apache Camel 3.3.0 (CamelContext: camel-1) started in 0.078 seconds
2020-05-28 07:14:52 DEBUG [o.a.c.c.g.p.GooglePubsubConsumer        ] - Subscribing to projects/my_gcp_project/subscriptions/transaction-test-subscriber
</code>```

答: Closing this out: It looks like there's a bug open in JIRA for this CAMEL-15064 that affects versions >= 3.2 </p>

Body:
I have a small groovy script with Apache camel that is attempting to pull messages from Google Pubsub. This works well on Camel 2.25.1, but camel 3.3.0 does not. Here is the script. I also looked at the Camel 2.x to 3.0 migration guide, but I am unable to find anything relevant to this issue, but perhaps I am mistaken and I would need some help.

My groovy version is 3.0.4 and I am using JDK 11.0.6

@Grapes([
    @Grab(group='org.apache.camel', module='camel-core', version='3.3.0'),
    @Grab(group='org.apache.camel', module='camel-google-pubsub', version='3.3.0'),
    @Grab(group='org.slf4j', module='slf4j-api', version='1.7.30'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='1.2.3'),
])

import org.apache.camel.CamelContext
import org.apache.camel.impl.DefaultCamelContext
import org.apache.camel.builder.RouteBuilder

main()

def main() {
    println "downloaded camel dependencies"
    CamelContext context = new DefaultCamelContext()

    context.addRoutes(new ReadFromQueueWithPubsub())
    context.start()
    addShutdownHook { context.stop() }
    synchronized(this){ this.wait() }
}

class ReadFromQueueWithPubsub extends RouteBuilder {

    @Override
    void configure() {
        from("google-pubsub://my_gcp_project:transaction-test-subscriber")
        .to("log:input?showAll=true")

    }
}

Here is the snippet of logs in debug mode. I can't see anything that's relevant here, but I may be mistaken.

2020-05-28 07:14:51 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Apache Camel 3.3.0 (CamelContext: camel-1) is starting
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using ClassResolver=org.apache.camel.impl.engine.DefaultClassResolver@25478603, PackageScanClassResolver=org.apache.camel.impl.engine.DefaultPackageScanClassResolver@3c7dbf1f, ApplicationContextClassLoader=null, RouteController=org.apache.camel.impl.engine.DefaultRouteController@2efbe938
2020-05-28 07:14:51 INFO  [o.a.c.i.e.AbstractCamelContext          ] - StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using HeadersMapFactory: org.apache.camel.impl.engine.DefaultHeadersMapFactory@12459991
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Using ReactiveExecutor: org.apache.camel.impl.engine.DefaultReactiveExecutor@43114981
2020-05-28 07:14:51 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Warming up route id: route1 having autoStartup=true
2020-05-28 07:14:51 DEBUG [o.a.c.s.DefaultProducer                 ] - Starting producer: Producer[log://input?showAll=true]
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Route: route1 >>> Route[google-pubsub://my_gcp_project:transaction-test-subscriber -> null]
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.AbstractCamelContext          ] - Starting consumer (order: 1000) on route: route1
2020-05-28 07:14:52 DEBUG [o.a.c.s.DefaultConsumer                 ] - Init consumer: Consumer[google-pubsub://my_gcp_project:transaction-test-subscriber]
2020-05-28 07:14:52 DEBUG [o.a.c.s.DefaultConsumer                 ] - Starting consumer: Consumer[google-pubsub://my_gcp_project:transaction-test-subscriber]
2020-05-28 07:14:52 INFO  [o.a.c.c.g.p.GooglePubsubConsumer        ] - Starting Google PubSub consumer for my_gcp_project/transaction-test-subscriber
2020-05-28 07:14:52 DEBUG [o.a.c.i.e.BaseExecutorServiceManager    ] - Created new ThreadPool for source: google-pubsub://my_gcp_project:transaction-test-subscriber with name: GooglePubsubConsumer[transaction-test-subscriber]. -> org.apache.camel.util.concurrent.RejectableThreadPoolExecutor@7d726fa1[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0][GooglePubsubConsumer[transaction-test-subscriber]]
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Route: route1 started and consuming from: google-pubsub://my_gcp_project:transaction-test-subscriber
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Total 1 routes, of which 1 are started
2020-05-28 07:14:52 INFO  [o.a.c.i.e.AbstractCamelContext          ] - Apache Camel 3.3.0 (CamelContext: camel-1) started in 0.078 seconds
2020-05-28 07:14:52 DEBUG [o.a.c.c.g.p.GooglePubsubConsumer        ] - Subscribing to projects/my_gcp_project/subscriptions/transaction-test-subscriber


问:
How to find the first and last of one of several characters in a list of strings?
So I have a list of strings such as this:

```<code>my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
</code>```

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

```<code>first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]
</code>```

Thanks in advance for any answer

答:
There is possibly a nicer way to do this, but one way to get it is to match all non-hyphen characters and get the start index of that match, and then to match all non-hyphen characters which are followed by 0 or more hyphens and then the end of the line, and get the start index of that match, and compile them into li</p>

```<code>>>> import re
>>> [re.search(r'[^-]+', string).start() for string in my_list]
[3, 2, 10, 1, 4]
>>> [re.search(r'[^-]-*$', string).start() for string in my_list]
[17, 7, 25, 10, 23]
</code>```

Body:
So I have a list of strings such as this:

my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]

Thanks in advance for any answer

Body:
There is possibly a nicer way to do this, but one way to get it is to match all non-hyphen characters and get the start index of that match, and then to match all non-hyphen characters which are followed by 0 or more hyphens and then the end of the line, and get the start index of that match, and compile them into li

>>> import re
>>> [re.search(r'[^-]+', string).start() for string in my_list]
[3, 2, 10, 1, 4]
>>> [re.search(r'[^-]-*$', string).start() for string in my_list]
[17, 7, 25, 10, 23]


问:
Pandas: how to treat strange time format
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

```<code>Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11
</code>```

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

```<code>In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object
</code>```

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

```<code>Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183
</code>```

答:
You can go with the datetime module for time conversion</p>

```<code>from datetime import datetime
def durationInDecimal(string):
    day, time = string.split(" ")
    t = datetime.strptime(time, "%H:%M").time()
    return int(day)*24 + (t.hour+t.minute/60.0)

df = pd.DataFrame({'Person': list("ABCD"), "Activity": list('ABCD') ,"duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})
df["duration"] = df.duration.apply(durationInDecimal)

# Person    Activity    duration
# 0 A   A   24.000000
# 1 B   B   24.000000
# 2 C   C   21.283333
# 3 D   D   17.183333
</code>```

Body:
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183

Body:
You can go with the datetime module for time conversion

from datetime import datetime
def durationInDecimal(string):
    day, time = string.split(" ")
    t = datetime.strptime(time, "%H:%M").time()
    return int(day)*24 + (t.hour+t.minute/60.0)

df = pd.DataFrame({'Person': list("ABCD"), "Activity": list('ABCD') ,"duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})
df["duration"] = df.duration.apply(durationInDecimal)

# Person    Activity    duration
# 0 A   A   24.000000
# 1 B   B   24.000000
# 2 C   C   21.283333
# 3 D   D   17.183333


问:
Bootstrap 3 to 4 update issues - site styles not rendering
I recently installed bootstrap 4.5.0 on a development project using bootstrap 3.4 initially.

The site style does not work again. I have rebuilt the project and solution. Still same.

The Bootstrap 3 was successfully changed to 4 and it reflects in packages.cs file as well.

What do I need to do to make the styles work well?

Note that it is an MVC application

答:
With MVC i always prefer to use CDN links, it will cause a little bit of a delay but it's doing the trick pretty well.

CSS :

```<code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</code>```

JS, Popper.js, and jQuery :

```<code><script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</code>```

Body:
With MVC i always prefer to use CDN links, it will cause a little bit of a delay but it's doing the trick pretty well.

CSS :

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

JS, Popper.js, and jQuery :

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


问:
Replace all occurrences of multiple curly brackets
I have a situation where there will be multiple instances where strings contain {{}} or {{{}}} or more combinations of curly brackets.

I'm using this currently string.replace(/\{\{/g , '').replace(/\}\}/g , '') but this only removes strings with double brackets. I need a regex to be able to replace all occurrences of two or more enclosed curly brackets and to remove them and everything in between.

Thanks!

答:
You can use 1 replace statement using an alternation | which matches either 2 or more times an opening curly brace {{2,} or 2 or more times a closing curly brace }{2,}

```<code>{{2,}|}{2,}
</code>```

Regex demo

[
  "{{{{{test1}}}}}}}}{}",
  "{{{{{test2}}}}}}}}",
].forEach(s => console.log(s.replace(/{{2,}|}{2,}/g, '')))```

Body:
You can use 1 replace statement using an alternation | which matches either 2 or more times an opening curly brace {{2,} or 2 or more times a closing curly brace }{2,}

{{2,}|}{2,}

Regex demo

[
  "{{{{{test1}}}}}}}}{}",
  "{{{{{test2}}}}}}}}",
].forEach(s => console.log(s.replace(/{{2,}|}{2,}/g, '')))


答:
So this

```<code>'aaa {{bb}} ccc {ddd} eee {{{ffff}}}'.replace(/\{{2,}/g, '{').replace(/\}{2,}/g, '}');
</code>```

gives me the following string: "aaa {bb} ccc {ddd} eee {ffff}".

I hope this helps

Title: Replace all occurrences of multiple curly brackets

Body:
I have a situation where there will be multiple instances where strings contain {{}} or {{{}}} or more combinations of curly brackets.

I'm using this currently string.replace(/\{\{/g , '').replace(/\}\}/g , '') but this only removes strings with double brackets. I need a regex to be able to replace all occurrences of two or more enclosed curly brackets and to remove them and everything in between.

Thanks!

Body:
So this

'aaa {{bb}} ccc {ddd} eee {{{ffff}}}'.replace(/\{{2,}/g, '{').replace(/\}{2,}/g, '}');

gives me the following string: "aaa {bb} ccc {ddd} eee {ffff}".

I hope this helps


问:
html button on .cs page
i am using html button in .aspx page. but i want to use the button_click event on .cs page..

i am adding html button as:

```<code><button id="button1" runat="server" onclick="Submit_Click">
    Send
    </button>
</code>```

and on .cs page i am usng:

```<code> protected void Submit_Click(object source, EventArgs e)
        {
            MessageBox.Show("ggg");
        }
</code>```

i don't want to use asp button ..
and this is not calling the event from .cs page..

how this can be done..

答:
You have to use onserverclick instead of the onclick method as this is a client side event of the HTML button control.

```<code><button id="button1" runat="server" onserverclick="Submit_Click">
Send
</button>
</code>```

Title: html button on .cs page

Body:
i am using html button in .aspx page. but i want to use the button_click event on .cs page..

i am adding html button as:

<button id="button1" runat="server" onclick="Submit_Click">
    Send
    </button>

and on .cs page i am usng:

 protected void Submit_Click(object source, EventArgs e)
        {
            MessageBox.Show("ggg");
        }

i don't want to use asp button ..
and this is not calling the event from .cs page..

how this can be done..

Body:
You have to use onserverclick instead of the onclick method as this is a client side event of the HTML button control.

<button id="button1" runat="server" onserverclick="Submit_Click">
Send
</button>


问:
How to load an initial value for a ClearableFileInput / FileField (before form is bound)
How do I set an initial value for a FileField that will display in a ClearableFileInput widget when creating a new object (unbound form)?

I have tried the following but widget.value does not return a FeildFile instance if it is the first time the user is creating the object:

models.py

```<code>class MyModel(models.Model):
    myfile=models.FileField()
</code>```

forms.py

```<code>class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfile'].initial= 'myfile.pdf'

    class Meta:
        model = Issuer
        fields = ['myfile']
</code>```

This results in :

Similarly, setting a default value in the modelfield does not work:

```<code>class MyModel(models.Model):
    myfile=models.FileField(default='myfile.pdf')
</code>```

The widget initial value is still None, but if it is left empty and saved the file object myfile.pdf will be created. The settings.MEDIA_URL and urls.py is definitely correct and the file is on the system because it is loaded after form save.

What I am missing is showing it as an initial value before a form is saved and an object created.

This answer suggests you can't provide initial data but you can provide an initial value with a url attribute to fake the appearance of a file. It's not clear how you would do this though.

Trying to create an initial file object in the form also returns widget.value = None

```<code>class MyForm(forms.ModelForm):

    f_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'myfile.pdf')

    f = open(f_path)
    myfile = File(f)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['privacy_policy'].initial = self.myfile
</code>```

答:
Your last block of code is quite close.

You are actually telling the user through the ClearableFileInput widget that if the user does not input anything in the file input, the initial value will be your pdf file.

But, this is only for display, you have to actually put the logic when you save the instance! (FileField won't do it for you) So the right thing is to override the save() method of your form, and in the case of a creation, put the actual file as the value. Like this:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        path = os.path.join(settings.MEDIA_ROOT, 'myfile.pdf')

        self.default_file = open(path)

        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['privacy_policy'].initial = File(self.default_file)
        self.fields['privacy_policy'].initial.url = default_storage.url('myfile.pdf')

    def save(self, commit=True):
        # Actually put the default file as a value if no input for creation
        if not self.instance.pk and not self.cleaned_data.get('privacy_policy'):
            self.instance.privacy_policy = self.default_file
            self.instance.privacy_policy._committed = True
        super().save(commit)
```

Body:
How do I set an initial value for a FileField that will display in a ClearableFileInput widget when creating a new object (unbound form)?

I have tried the following but widget.value does not return a FeildFile instance if it is the first time the user is creating the object:

models.py

class MyModel(models.Model):
    myfile=models.FileField()

forms.py

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfile'].initial= 'myfile.pdf'

    class Meta:
        model = Issuer
        fields = ['myfile']

This results in :

Similarly, setting a default value in the modelfield does not work:

class MyModel(models.Model):
    myfile=models.FileField(default='myfile.pdf')

The widget initial value is still None, but if it is left empty and saved the file object myfile.pdf will be created. The settings.MEDIA_URL and urls.py is definitely correct and the file is on the system because it is loaded after form save.

What I am missing is showing it as an initial value before a form is saved and an object created.

This answer suggests you can't provide initial data but you can provide an initial value with a url attribute to fake the appearance of a file. It's not clear how you would do this though.

Trying to create an initial file object in the form also returns widget.value = None

class MyForm(forms.ModelForm):

    f_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'myfile.pdf')

    f = open(f_path)
    myfile = File(f)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['privacy_policy'].initial = self.myfile


问:
How to add border to label when radio button is selected
```<code><label for="seeker" class="checkbox">
    I am a Job Seeker
    <input type="radio" id="seeker" name="designation">
</label>

<label for="employer" class="checkbox">
    I am an Employer
    <input type="radio" id="employer" name="designation">
</label>
</code>```

I have multiple HTML radio inputs which are wrapped around labels (https://i.imgur.com/GLdqodq.png) when a radio is selected for say input name "designation" I'd like to add a border color to the label of the radio button that was selected and remove the border from the other labels (https://i.imgur.com/LOMlBUP.png), here's the the JS code I tried using but for some reason when a radio button is unchecked JS can't seem to detect the event.

```<code>const radios = document.querySelectorAll('.checkbox input')

radios.forEach((radio) => {
    radio.addEventListener('change', e => {

        if (e.target.checked) {
            // logic to add label border
        } else {
            // logic to remove label border
        }

    })
})
</code>```

I know this can be done using the CSS plus (+) operator but seems like that would require the label to preceded the input, something I wouldn't want to do. However I'm open to using a CSS method as long as the markup wouldn't have to be changed.

答:
You can simply do it css using input:checked selector

Take an example from below code and codepen link https://codepen.io/naren-irain/pen/XWXWWqq

.radiobox {
  display: inline-block;
  cursor: pointer;
  user-select: none;
}
.radiobox input {
  position: absolute;
  opacity: 0;
}
.radiobox .check {
  background: #fff;
  border: 1px solid #979797;
  border-radius: 50%;
  display: inline-block;
  width: 16px;
  height: 16px;
  position: relative;
  top: 1px;
  margin-right: 5px;
  vertical-align: top;
}
.radiobox span, .radioTab span, .checkbox span {
  display: inline-block;
  vertical-align: top;
}
.radiobox .check i,
.radioTab .check i {
  background: #0db837;
  border-radius: 50%;
  display: block;
  width: 10px;
  height: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -5px 0 0 -5px;
  opacity: 0;
  transform: scale(0.75);
  transition: all 0.3s;
}
.radiobox input:checked+.check,
.radioTab input:checked+ span .check {
  border-color: #5cb85c;
}
.radiobox input:checked+.check i,
.radioTab input:checked+ span .check i {
  opacity: 1;
  transform: scale(1);
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Select any one option</h4>
<label class="radiobox" for="one">
    <input type="radio" id="one" name="designation" value="one" />
    <span class="check"><i></i></span>
    <span>This is one option</span>
</label>
<br/>
<br/>
<label class="radiobox" for="two">
    <input type="radio" id="two" name="designation" value="two" />
    <span class="check"><i></i></span>
    <span>Never think this is an option</span>
</label></code>```

Body:
    I am a Job Seeker
    <input type="radio" id="seeker" name="designation">

    I am an Employer
    <input type="radio" id="employer" name="designation">

I have multiple HTML radio inputs which are wrapped around labels (https://i.imgur.com/GLdqodq.png) when a radio is selected for say input name "designation" I'd like to add a border color to the label of the radio button that was selected and remove the border from the other labels (https://i.imgur.com/LOMlBUP.png), here's the the JS code I tried using but for some reason when a radio button is unchecked JS can't seem to detect the event.

const radios = document.querySelectorAll('.checkbox input')

radios.forEach((radio) => {
    radio.addEventListener('change', e => {

        if (e.target.checked) {
            // logic to add label border
        } else {
            // logic to remove label border
        }

    })
})

I know this can be done using the CSS plus (+) operator but seems like that would require the label to preceded the input, something I wouldn't want to do. However I'm open to using a CSS method as long as the markup wouldn't have to be changed.

Body:
You can simply do it css using input:checked selector

Take an example from below code and codepen link https://codepen.io/naren-irain/pen/XWXWWqq

.radiobox {
  display: inline-block;
  cursor: pointer;
  user-select: none;
}
.radiobox input {
  position: absolute;
  opacity: 0;
}
.radiobox .check {
  background: #fff;
  border: 1px solid #979797;
  border-radius: 50%;
  display: inline-block;
  width: 16px;
  height: 16px;
  position: relative;
  top: 1px;
  margin-right: 5px;
  vertical-align: top;
}
.radiobox span, .radioTab span, .checkbox span {
  display: inline-block;
  vertical-align: top;
}
.radiobox .check i,
.radioTab .check i {
  background: #0db837;
  border-radius: 50%;
  display: block;
  width: 10px;
  height: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -5px 0 0 -5px;
  opacity: 0;
  transform: scale(0.75);
  transition: all 0.3s;
}
.radiobox input:checked+.check,
.radioTab input:checked+ span .check {
  border-color: #5cb85c;
}
.radiobox input:checked+.check i,
.radioTab input:checked+ span .check i {
  opacity: 1;
  transform: scale(1);
}

<h4>Select any one option</h4>
<label class="radiobox" for="one">
    <input type="radio" id="one" name="designation" value="one" />
    <span class="check"><i></i></span>
    <span>This is one option</span>
</label>
<br/>
<br/>
<label class="radiobox" for="two">
    <input type="radio" id="two" name="designation" value="two" />
    <span class="check"><i></i></span>
    <span>Never think this is an option</span>
</label>


问:
How to avoid SQL injection with "SELECT * FROM {table_name}"?
In Python using Psycopg2 with the following code:

```<code>import psycopg2

import getpass

conn = psycopg2.connect("dbname=mydb user=%s" % getpass.getuser())
cursor = conn.cursor()

tables = ["user", "group", "partner", "product"]
for table in tables:

    # with sql injection
    cursor.execute("SELECT name FROM %s LIMIT 1" % (table,))
    print "table", table, "result", len(cursor.fetchone())

    # without sql injection
    cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
    print "table", table, "result", len(cursor.fetchone())
</code>```

The output was:

```<code>table res_partner result 1
Traceback (most recent call last):
  File "my_psycopg2_example.py", line 16, in <module>
    cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
psycopg2.ProgrammingError: syntax error at or near "'res_partner'"
LINE 1: SELECT name FROM 'res_partner' LIMIT 1
</code>```

With SQL injection it works fine.

But we don't want to create a security issue.

We read this documentation and in it found the following comment:

Only variable values should be bound via this method: it shouldn’t be used to set table or field names. For these elements, ordinary string formatting should be used before running execute().

But if we use "ordinary string formatting", we'll have SQL injection too.

What's a good way to manage this special case, and avoid SQL injection?

答:
Here is nice article about injections and python code
https://realpython.com/prevent-python-sql-injection/

you can transform

```<code>tables = ["user", "group", "partner", "product"]
for table in tables:
    cursor.execute("SELECT name FROM %s LIMIT 1" % (table,))
</code>```

to

```<code>from psycopg2 import sql

tables = ["user", "group", "partner", "product"]
for table_name in tables:
    stmt = sql.SQL("SELECT name FROM {table_name} LIMIT 1").format(
        table_name = sql.Identifier(table_name),
    )
    cursor.execute(stmt)
</code>```

Body:
In Python using Psycopg2 with the following code:

import psycopg2

import getpass

conn = psycopg2.connect("dbname=mydb user=%s" % getpass.getuser())
cursor = conn.cursor()

tables = ["user", "group", "partner", "product"]
for table in tables:

    # with sql injection
    cursor.execute("SELECT name FROM %s LIMIT 1" % (table,))
    print "table", table, "result", len(cursor.fetchone())

    # without sql injection
    cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
    print "table", table, "result", len(cursor.fetchone())

The output was:

table res_partner result 1
Traceback (most recent call last):
  File "my_psycopg2_example.py", line 16, in <module>
    cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
psycopg2.ProgrammingError: syntax error at or near "'res_partner'"
LINE 1: SELECT name FROM 'res_partner' LIMIT 1

With SQL injection it works fine.

But we don't want to create a security issue.

We read this documentation and in it found the following comment:

Only variable values should be bound via this method: it shouldn’t be used to set table or field names. For these elements, ordinary string formatting should be used before running execute().

But if we use "ordinary string formatting", we'll have SQL injection too.

What's a good way to manage this special case, and avoid SQL injection?

Body:
Here is nice article about injections and python code
https://realpython.com/prevent-python-sql-injection/

you can transform

tables = ["user", "group", "partner", "product"]
for table in tables:
    cursor.execute("SELECT name FROM %s LIMIT 1" % (table,))

to

from psycopg2 import sql

tables = ["user", "group", "partner", "product"]
for table_name in tables:
    stmt = sql.SQL("SELECT name FROM {table_name} LIMIT 1").format(
        table_name = sql.Identifier(table_name),
    )
    cursor.execute(stmt)


问:
Making a new line in js string
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?</p>

```<code>var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();
</code>```

答:
I believe /n isn't a good practice here, if you're receiving those data from a 3rd-party API for example, you won't be able to get /n in the text. So, your best bet is checking for the exact word you're looking for, and add break line after it.

Solution Explanation

The wordCheck boolean value is set to true by default, so our condition below keep running, until we found the word Editing in the printed text. In that case, we add a line break, set false value to wordCheck to prevent adding line breaks later.

I cached the element txtElement for better code readability.

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";
var wordCheck = true;

function typeWriter(){
  var txtElement = document.getElementById("text");

  if(i < text.length){
    txtElement.innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);

    // Here's we detect if the value reached the word "Editing", if so, we do break line
    var currentVal = txtElement.innerHTML;
    if(wordCheck && currentVal.indexOf('Editing') >= 1) {
      txtElement.innerHTML += "
";
      wordCheck = false;
    }
  }
}
typeWriter();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="text"></p></code>```

Title: Making a new line in js string

Body:
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();

Body:
I believe /n isn't a good practice here, if you're receiving those data from a 3rd-party API for example, you won't be able to get /n in the text. So, your best bet is checking for the exact word you're looking for, and add break line after it.

Solution Explanation

The wordCheck boolean value is set to true by default, so our condition below keep running, until we found the word Editing in the printed text. In that case, we add a line break, set false value to wordCheck to prevent adding line breaks later.

I cached the element txtElement for better code readability.

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";
var wordCheck = true;

function typeWriter(){
  var txtElement = document.getElementById("text");

  if(i < text.length){
    txtElement.innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);

    // Here's we detect if the value reached the word "Editing", if so, we do break line
    var currentVal = txtElement.innerHTML;
    if(wordCheck && currentVal.indexOf('Editing') >= 1) {
      txtElement.innerHTML += "<br>";
      wordCheck = false;
    }
  }
}
typeWriter();

<p id="text"></p>


问:
pass empty string as variable value from ansible playbook to powershell?
I want to pass an empty string as a variable value from ansible-playbook to PowerShell file.

Ansible Code:

```<code>vars:
 name: {{file_name}}

tasks:
  - name: run ps1
    win_shell: "script.ps1 -database_name {{ name }}"
    no_log: false

Powershell code

param(

[Parameter(Mandatory = $true)][AllowEmptyString()][string]$database_name

)
</code>```

So if there is no name in file_name then I want to send an empty string to PowerShell file! How can I do that?

答: Likely you need | quote as in {{ name | default("") | quote }} in order to wrap the result in shell quote variables. Without that, jinja2 does not know that you want the empty string to render as "" instead of blank; you can also side-step that with {{ name | default('""') }} but that's highly unlikely to be what you want since if name is "hello world" then {{ name | default("") }} will render in your command as -database_name hello world which will almost certainly fail

Body:
I want to pass an empty string as a variable value from ansible-playbook to PowerShell file.

Ansible Code:

vars:
 name: {{file_name}}

tasks:
  - name: run ps1
    win_shell: "script.ps1 -database_name {{ name }}"
    no_log: false

Powershell code

param(

[Parameter(Mandatory = $true)][AllowEmptyString()][string]$database_name

)

So if there is no name in file_name then I want to send an empty string to PowerShell file! How can I do that?


问:
Form Based Arrays
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

```<code>$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)
</code>```

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

答:
From what you wrote, I'm assuming that the form field is called collect[] seeing you're trying to access its indexes.

However,  you're using wrong method here - $_POST is an array, yet you tried to use it as a function (not that it's impossible, but for this purpose - it's really not the way to do it).

```<code>$dd = $_POST['collect'][0];
$mm = $_POST['collect'][1];
</code>```

And so on until you reach the last element of your array.

If you are storing some user-submitted date to the MySQL - yes, there are better ways to do it. If you wish to know what they are, feel free to comment so I'll post my views on what better ways exist.

Title: Form Based Arrays

Body:
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

Body:
From what you wrote, I'm assuming that the form field is called collect[] seeing you're trying to access its indexes.

However,  you're using wrong method here - $_POST is an array, yet you tried to use it as a function (not that it's impossible, but for this purpose - it's really not the way to do it).

$dd = $_POST['collect'][0];
$mm = $_POST['collect'][1];

And so on until you reach the last element of your array.

If you are storing some user-submitted date to the MySQL - yes, there are better ways to do it. If you wish to know what they are, feel free to comment so I'll post my views on what better ways exist.