问:
How to run multiple threads created by loop simultaneous using boost.thread?
I'm using learning the basic of boost.thread. So far, I can create each thread one by one manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore.</p>

```<code>#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
  boost::posix_time::seconds workTime(3);
  std::cout << "Worker: Running" << '\n';
  boost::this_thread::sleep(workTime);
  std::cout<< "Worker: Finished" << '\n';
}

int main()
{
  std::cout << "main: startup" << '\n';
  boost::thread workerThread(workerFunc);
  std::cout << "main: waiting for thread" << '\n';
  //these are ok
  boost::thread t(workerFunc), t2(workerFunc), t3(workerFunc), t4(workerFunc);
  t.join();
  t2.join();
  t3.join();
  t4.join();
  //these are not
  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }
  std::cout << "main:done" << '\n';
  return 0;
}
</code>```

答:
```<code>  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }
</code>```

You are starting your thread and then immediately waiting for it to complete!

EDIT

One of several alternative hacks besides thread groups.

```<code>  std::vector<boost::thread *> z;

  for (int i = 0; i < 2; ++i)
    z.push_back(new boost::thread(workerFunc));

  for (int i = 0; i < 2; ++i)
  {
      z[i]->join();
      delete z[i];
  }
</code>```

Body:
I'm using learning the basic of boost.thread. So far, I can create each thread one by one manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore.

#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
  boost::posix_time::seconds workTime(3);
  std::cout << "Worker: Running" << '\n';
  boost::this_thread::sleep(workTime);
  std::cout<< "Worker: Finished" << '\n';
}

int main()
{
  std::cout << "main: startup" << '\n';
  boost::thread workerThread(workerFunc);
  std::cout << "main: waiting for thread" << '\n';
  //these are ok
  boost::thread t(workerFunc), t2(workerFunc), t3(workerFunc), t4(workerFunc);
  t.join();
  t2.join();
  t3.join();
  t4.join();
  //these are not
  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }
  std::cout << "main:done" << '\n';
  return 0;
}

Body:
  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }

You are starting your thread and then immediately waiting for it to complete!

EDIT

One of several alternative hacks besides thread groups.

  std::vector<boost::thread *> z;

  for (int i = 0; i < 2; ++i)
    z.push_back(new boost::thread(workerFunc));

  for (int i = 0; i < 2; ++i)
  {
      z[i]->join();
      delete z[i];
  }


来源: stackexchange

问:
How do I remove a character from strings of different lengths with sql? Intersystems cache sql
I have a column of strings that have an '&' at the beginning and end of each one that I need to remove for a Crystal report I'm creating. I'm writing the SQL code outside of Crystal I am using Intersystems Cache SQL. Below is an example:

```<code>&This&         This
&is&           is
&What&         what
&it&           I
&looks&        need
&like&         it
&now&          to
               look
               like
</code>```

Any suggestions would be greatly appreciated!!!

答:
Here's a Crystal formula that does the same:</p>

```<code>ExtractString({YourData},"&","&")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column of strings that have an '&' at the beginning and end of each one that I need to remove for a Crystal report I'm creating. I'm writing the SQL code outside of Crystal I am using Intersystems Cache SQL. Below is an example:

&This&         This
&is&           is
&What&         what
&it&           I
&looks&        need
&like&         it
&now&          to
               look
               like

Any suggestions would be greatly appreciated!!!

Body:
Here's a Crystal formula that does the same:

ExtractString({YourData},"&","&")


答:
Here is an idea with plt.imshow, and plt.annotate:

```<code># function to make risk matrix
def make_risk_matrix(shape=3,levels=3):
    matrix = np.zeros((shape, shape))
    for level in range(levels):
        matrix[np.triu_indices(shape, level)] += 1
    return matrix

# specify bin borders and respective positions
likelihood_bins = [100,86,60]
positions = [0,1,2]

for position, likelihood in zip(positions, likelihood_bins):
    df.loc[df['KPI']<=likelihood, 'y'] = position

# generate x-positions from classification column
df['x'] = df['Classification'].replace({'High':2, 'Medium':1, 'Low':0})

# default offset for x -position
x_offset = -.4

# generate risk matrix and display as image
risk_matrix = make_risk_matrix()
plt.imshow(risk_matrix, cmap='RdYlGn_r')

# write individual components on it
# as some components will end up in hte same bin,
# caculate y-offset on the fly
for group in df.groupby(['x', 'y']):
    y_offset = -.3
    for ix, row in group[1].iterrows():

        plt.annotate(
            row['Component'],
            xy=(
                row['x']+x_offset,
                row['y']+y_offset
                )
            )
        y_offset +=.15 # update y_offset

plt.xlabel('Consequence')
plt.ylabel('Likelihood')
</code>```

df that i used was this one:

```<code>    Component   KPI Classification
1   12          34  High
2   Start       38  High
3   Fusela      45  Low
4   Hyd         50  Medium
[...]
</code>```

Title: Risk Matrix with Pythyon

Body:
I am trying to do a risk matrix using Python that integrate severity and probability, I already tried using heatmaps, and it is maybe the closest kind of graph I have found so far, but I think it does not represent the basic structure of a risk matrix. The next image shows the kind of matrix graph I want. I would appreciate any recommendation: library, link...whatever to be able to graph a risk matrix.

This is the data I am trying to locate inside the risk matrix:

|---------------------|------------------|----------------------|
|      Component      |        KPI       |     Classification
|---------------------|------------------|----------------------|
|          12         |         34       |    High Criticality
|---------------------|------------------|----------------------|
          Start                 38            High Criticality
|---------------------|------------------|----------------------|
         Fusela                 45            Low Criticality
|---------------------|------------------|----------------------|
          Hyd                   50           Medium Criticality
|---------------------|------------------|----------------------|
          Damp                  51           Medium Criticality
|---------------------|------------------|----------------------|
         Turbine                62           High Criticality
|---------------------|------------------|----------------------|
        Intercon                65          Medium Criticality
|---------------------|------------------|----------------------|
       Main Rotor               90           High Criticality
|---------------------|------------------|----------------------|
         AM-19                  93            High Criticality
|---------------------|------------------|----------------------|
      Main Trans                98            High Criticality
|---------------------|------------------|----------------------|

And this is the code I already implemented using heatmap:

import matplotlib.pyplot as plt

data = data.sort_values(by = 'KPI', ascending = False)
x = 1
for element in list(data['Componente']):
    data['Componente'] = data['Componente'].str.replace(str(element),'{}.
{}'.format(str(x),element))
    x = x + 1
data['Clasificación'] = data['Clasificación'].str.replace('Criticidad
Alta','1. Criticidad Alta').str.replace('Criticidad Media','2. Criticidad
Media').str.replace('Criticidad Baja', '3. Criticidad Baja')
result = data.pivot(index='Componente',columns= 'Clasificacion', values =
'KPI')
sb.heatmap(result, annot= True ,cmap='RdYlGn' ,fmt=".1f", vmax=100)
plt.figtext(.5,.9,'RESULTADO MATRIZ RIESGO', fontsize=14, ha='center')
plt.show()

The output I woudl like is something like the next imager:

Body:
Here is an idea with plt.imshow, and plt.annotate:

# function to make risk matrix
def make_risk_matrix(shape=3,levels=3):
    matrix = np.zeros((shape, shape))
    for level in range(levels):
        matrix[np.triu_indices(shape, level)] += 1
    return matrix

# specify bin borders and respective positions
likelihood_bins = [100,86,60]
positions = [0,1,2]

for position, likelihood in zip(positions, likelihood_bins):
    df.loc[df['KPI']<=likelihood, 'y'] = position

# generate x-positions from classification column
df['x'] = df['Classification'].replace({'High':2, 'Medium':1, 'Low':0})

# default offset for x -position
x_offset = -.4

# generate risk matrix and display as image
risk_matrix = make_risk_matrix()
plt.imshow(risk_matrix, cmap='RdYlGn_r')

# write individual components on it
# as some components will end up in hte same bin,
# caculate y-offset on the fly
for group in df.groupby(['x', 'y']):
    y_offset = -.3
    for ix, row in group[1].iterrows():

        plt.annotate(
            row['Component'],
            xy=(
                row['x']+x_offset,
                row['y']+y_offset
                )
            )
        y_offset +=.15 # update y_offset

plt.xlabel('Consequence')
plt.ylabel('Likelihood')

df that i used was this one:

    Component   KPI Classification
1   12          34  High
2   Start       38  High
3   Fusela      45  Low
4   Hyd         50  Medium
[...]


问:
@ViewChildren does not get updated with dynamically added DOM elements
I have the following DOM structure

```<code><div #carousalElement>
    <div  class="singleCaousalElement">
        <a>
            <img [src]="carousalURL1" class="carousalImage">
        </a>
    </div>
    <div  class="singleCaousalElement">
        <a>
            <img [src]="carousalURL2" class="carousalImage">
        </a>
    </div>
</div>
</code>```

I can get the all divs with carousalElements class using the ViewChildren

```<code>@ViewChildren('carousalElement') carousalElements;
</code>```

PROBLEM: When I dynamically add a new div under the #carousalElement div, it does not show up under the carousalElements array.

Am I missing something obvious?

答:
In JavaScript there are two data types: primitive and object.

In Angular there are basically 3 data types (glossing over plenty here): primitive, object, and reactive. Without going into details

```<code>@ViewChildren('carousalElement') carousalElements;
</code>```

Is of the data type reactive. In Angular, this means there is an observer in this case the amount of elements with the caoursalElement templateVariable, your variable carousalElements is an advanced form of subscription to @ViewChildren, which is an observer to access the updated array you simply need

```<code>()=>{return this.carousalElements}
</code>```

Make sure your HTML template is using your template vars correctly and this should work

ContentLicense: CC BY-SA 3.0

Body:
I have the following DOM structure

I can get the all divs with carousalElements class using the ViewChildren

@ViewChildren('carousalElement') carousalElements;

PROBLEM: When I dynamically add a new div under the #carousalElement div, it does not show up under the carousalElements array.

Am I missing something obvious?

Body:
In JavaScript there are two data types: primitive and object.

In Angular there are basically 3 data types (glossing over plenty here): primitive, object, and reactive. Without going into details

@ViewChildren('carousalElement') carousalElements;

Is of the data type reactive. In Angular, this means there is an observer in this case the amount of elements with the caoursalElement templateVariable, your variable carousalElements is an advanced form of subscription to @ViewChildren, which is an observer to access the updated array you simply need

()=>{return this.carousalElements}

Make sure your HTML template is using your template vars correctly and this should work


问:
Python cx_Oracle Insert Into table with multiple columns automating the values (1:,2: ... 100:)
I am working on a script to read from an oracle table with about 75 columns in one environment and load it into same table definition in a different environment. Till now I have been using cx_Oracle cur.execute() method to 'INSERT INTO TABLENAME VALUES(:1,:2,:3..:8);' and then load the data using 'cur.execute(sql, conn)' method.

However,this table that I'm trying to load has about 75+ columns and writing (:1, :2 ... :75) would be tedious and I'm guessing not part of best practice.

Is there an automated way to loop over the number of columns and automatically fill the values() portion of the SQL query.

```<code>user = 'username'
pass = getpass.getpass()
connection_prod = cx_Oracle.makedsn(host, port, service_name = '')
cursor_prod = connection_prod.cursor()

connection_dev = cx_Oracle.makedsn(host, port, service_name = '')
cursor_dev = connection_dev.cursor()

SQL_Read = """Select * from Table_name_Prod"""
Data = cur.execute(SQL_Read, connection_prod)
for row in Data:
    SQL_Load = "INSERT INTO TABLE_NAME_DEV VALUES(:1, :2,:3, :4 ...:75);" --This part is ugly and tedious.
    cursor_dev.execute(SQL_LOAD, row)
</code>```

This is where I need Help

```<code>connection_Prod.commit()
cursor_Prod.close()
connection_Prod.close()
</code>```

答:
You can do the following which should help not only in reducing code but also in improving performance:

```<code>connection_prod = cx_Oracle.connect(...)
cursor_prod = connection_prod.cursor()

# set array size for source cursor to some reasonable value
# increasing this value reduces round-trips but increases memory usage
cursor_prod.arraysize = 500

connection_dev = cx_Oracle.connect(...)
cursor_dev = connection_dev.cursor()

cursor_prod.execute("select * from table_name_prod")
bind_names = ",".join(":" + str(i + 1) \
        for i in range(len(cursor_prod.description)))
sql_load = "insert into table_name_dev values (" + bind_names + ")"
while True:
    rows = cursor_prod.fetchmany()
    if not rows:
        break
    cursor_dev.executemany(sql_load, rows)
    # can call connection_dev.commit() here if you want to commit each batch
</code>```

The use of cursor.executemany() will significantly help in terms of performance. Hope this helps you out!

Body:
I am working on a script to read from an oracle table with about 75 columns in one environment and load it into same table definition in a different environment. Till now I have been using cx_Oracle cur.execute() method to 'INSERT INTO TABLENAME VALUES(:1,:2,:3..:8);' and then load the data using 'cur.execute(sql, conn)' method.

However,this table that I'm trying to load has about 75+ columns and writing (:1, :2 ... :75) would be tedious and I'm guessing not part of best practice.

Is there an automated way to loop over the number of columns and automatically fill the values() portion of the SQL query.

user = 'username'
pass = getpass.getpass()
connection_prod = cx_Oracle.makedsn(host, port, service_name = '')
cursor_prod = connection_prod.cursor()

connection_dev = cx_Oracle.makedsn(host, port, service_name = '')
cursor_dev = connection_dev.cursor()

SQL_Read = """Select * from Table_name_Prod"""
Data = cur.execute(SQL_Read, connection_prod)
for row in Data:
    SQL_Load = "INSERT INTO TABLE_NAME_DEV VALUES(:1, :2,:3, :4 ...:75);" --This part is ugly and tedious.
    cursor_dev.execute(SQL_LOAD, row)

This is where I need Help

connection_Prod.commit()
cursor_Prod.close()
connection_Prod.close()

Body:
You can do the following which should help not only in reducing code but also in improving performance:

connection_prod = cx_Oracle.connect(...)
cursor_prod = connection_prod.cursor()

# set array size for source cursor to some reasonable value
# increasing this value reduces round-trips but increases memory usage
cursor_prod.arraysize = 500

connection_dev = cx_Oracle.connect(...)
cursor_dev = connection_dev.cursor()

cursor_prod.execute("select * from table_name_prod")
bind_names = ",".join(":" + str(i + 1) \
        for i in range(len(cursor_prod.description)))
sql_load = "insert into table_name_dev values (" + bind_names + ")"
while True:
    rows = cursor_prod.fetchmany()
    if not rows:
        break
    cursor_dev.executemany(sql_load, rows)
    # can call connection_dev.commit() here if you want to commit each batch

The use of cursor.executemany() will significantly help in terms of performance. Hope this helps you out!


问:
Get values from nested forms using final form in react/typescript
I wasn't able to get the values from my nested forms using final form.

here is my index.tsx

```<code>import React, { useState, ChangeEvent } from 'react';
import { Form } from 'react-final-form';
import {
  Box, Typography, Button, IconButton, Grid, FormControl, InputLabel, Select,
} from '@material-ui/core';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import FieldInput from 'forms/shared/fields/input';
import FieldFileUploader from 'forms/shared/fields/file-uploader';
import FieldCheckbox from 'forms/shared/fields/checkbox';
import FormRadioQuestions from './partials/form-radio';
import FormExperience from './partials/form-experience';
import FormEducation from './partials/form-education';
import FormPersonalInfo from './partials/form-personal-info';
import FormGovernmentIds from './partials/form-government-id';
import ItemExperience from './partials/experience-item';
import ItemEducation from './partials/education-item';
import useStyles from './styles';

const PublicApplicationForm = () => {
  const [state, setState] = useState<{ client: string | number; name: string }>({ client: '', name: 'hai' });
  const [showExp, setOpenExp] = useState(false);
  const [showEdu, setOpenEdu] = useState(false);
  const [data, setData] = useState({
    experience: [{}],
  });
  const [educations, setEducations] = useState([]);
  const [experiences, setExperiences] = useState([]);
  const classes = useStyles();
  const radioValues = [{ value: 'yes', label: 'Yes' }, { value: 'no', label: 'No' }];
  const variables = { title: 'How did you hear about us?*', typeOfService: 'Type of Service*' };
  const relationOptions = ['Walk-In', 'Employee Referral', 'Job Boards', 'Job Fair', 'Social Media'];
  const checkBoxLabel = 'Please be informed that your application to this job offer will trigger some processing of your personal data by the  company. For more information on data processing, please refer to the company’s talent acquisition privacy policy.';

  const handleChange = ({ target }: ChangeEvent<{ name?: string; value: unknown }>) => {
    setState({ ...state, [target.name as keyof typeof state]: target.value });
  };

  const handleBlur = (event: any) => {
    data.experience[0] = { ...data.experience[0], [event.target.name]: event.target.value };
    setData({ ...data });
  };

  const onAddEdu = (edu: any) => { setEducations([...educations, edu]); setOpenEdu(false); };
  const onAddExp = (exp: any) => { setExperiences([...experiences, exp]); setOpenExp(false); };

  return (
    <Grid className={classes.pageContainer} container>
      <Grid className={classes.formContainer} item xs={12}>
        <Form
          onSubmit={(values) => { console.log(values); }} // eslint-disable-line no-console
          render={({ handleSubmit }) => (
            <form onSubmit={handleSubmit}>
              <Typography className={classes.formHeading} variant="h5">Personal Information</Typography>
              <Box className={classes.marginedBottom}>
                <FieldFileUploader
                  required
                  fileType="avatars"
                  accept={['image/*']}
                  name="resume"
                />
              </Box>
              <FormPersonalInfo setData={setData} data={data} />
              <Box className={classes.spaced}>
                <Box className={classes.fieldContainer}>
                  <Typography className={classes.noMarginBottom} variant="h6">Experience</Typography>
                  <IconButton color="primary" onClick={() => { setOpenExp(!showExp); }}><AddCircleIcon /></IconButton>
                </Box>
                {
                  showExp && (
                    <FormExperience
                      onCancel={() => setOpenExp(false)}
                      onSave={onAddExp}
                      handleBlur={handleBlur}
                    />
                  )
                }
                {experiences.map((exp, index) => <ItemExperience key={index} exp={exp} />)}
              </Box>
              <Box className={classes.spaced}>
                <Box className={classes.fieldContainer}>
                  <Typography className={classes.noMarginBottom} variant="h6">Education</Typography>
                  <IconButton color="primary" onClick={() => { setOpenEdu(!showEdu); }}><AddCircleIcon /></IconButton>
                </Box>
                {
                  showEdu && (
                    <FormEducation
                      onCancel={() => setOpenEdu(false)}
                      onSave={onAddEdu}
                      setData={setData}
                      data={data}
                    />
                  )
                }
                {educations.map((edu, index) => <ItemEducation key={index} edu={edu} />)}
              </Box>
              <Typography className={classes.formText} variant="h6">On the web</Typography>
              <Box className={classes.fieldContainer}>
                <FieldInput className={classes.textField} type="text" required name="applicant-linkedin" label="Linkedin" onChange={(event: React.ChangeEvent<HTMLInputElement>) => setData({ ...data, [event.target.name]: event.target.value })} />
              </Box>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <FieldInput className={classes.textField} type="text" required name="applicant-facebook" label="Facebook" onChange={(event: React.ChangeEvent<HTMLInputElement>) => setData({ ...data, [event.target.name]: event.target.value })} />
              </Box>
              <Typography className={classes.formText} variant="h6">Resume</Typography>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <Box className={classes.dropZone}>
                  <FieldFileUploader
                    required
                    fileType="resumes"
                    fieldLabel="Click or Drag file here to upload resume"
                    accept={['application/pdf']}
                    name="resume"
                  />
                </Box>
              </Box>
              <Typography className={classes.formText} variant="h6">Check the box of the ones you don't have.</Typography>
              <Box className={classes.marginedBottom}>
                <FormGovernmentIds setData={setData} data={data} />
              </Box>
              <Typography className={classes.formText} variant="h6">Preliminary Questions</Typography>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <FormControl variant="outlined" className={classes.textField}>
                  <InputLabel htmlFor="outlined-age-native-simple">{variables.title}</InputLabel>
                  <Select
                    native
                    value={state.client}
                    onChange={handleChange}
                    label="How did you hear about us?"
                    inputProps={{ name: 'client', id: 'outlined-age-native-simple' }}
                    onClick={
                      (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => setData({
                        ...data,
                        [event.target.name]: event.target.value,
                      })
                    }
                  >
                    <option aria-label="None" value="" />
                    {relationOptions.map((item, index) => (
                      <option key={index} value={item.replace(' ', '-').toLowerCase()}>{item}</option>))}
                  </Select>
                </FormControl>
              </Box>
              <FormRadioQuestions
                fieldClassName={classes.fieldContainer}
                textClassName={classes.textField}
                values={radioValues}
                setData={setData}
                data={data}
              />
              <Box className={classes.fieldContainer}>
                <FieldCheckbox className={classes.textField} name="confirm-registration" label={checkBoxLabel} />
              </Box>
              <Box className={classes.fieldContainer}>
                <Button component="button" type="submit" className={classes.spaced} variant="contained" color="primary">
                  Submit
                </Button>
              </Box>
            </form>
          )}
        />
      </Grid>
    </Grid>
  );
};

export default PublicApplicationForm;
</code>```

The FormPersonalInfo component consists of fields such as applicant-first-name, last name, email, location, mobile, etc.

When I click on the AddCircleIcon button to show some other fields and to add experiences/education, I got this error.

When I click the submit button I only got this log.

This is the Experience forms same with Education forms

My goal is to add experince and education array to the result set just like this.

答:
The error is clear, there are <form> tags nested.

Quick example to reproduce error

const { useState, useEffect } = React;

const App = () => {

return <form>
  <form></form>
</form>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div></code>```

In your case showExp evaluates to true after click action, then FormExperience component, which apparently has form tag in it, renders and validateDOMNesting throws error.

```<code>  showExp && (
    <FormExperience
      onCancel={() => setOpenExp(false)}
      onSave={onAddExp}
      handleBlur={handleBlur}
    />)
</code>```

Body:
I wasn't able to get the values from my nested forms using final form.

here is my index.tsx

import React, { useState, ChangeEvent } from 'react';
import { Form } from 'react-final-form';
import {
  Box, Typography, Button, IconButton, Grid, FormControl, InputLabel, Select,
} from '@material-ui/core';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import FieldInput from 'forms/shared/fields/input';
import FieldFileUploader from 'forms/shared/fields/file-uploader';
import FieldCheckbox from 'forms/shared/fields/checkbox';
import FormRadioQuestions from './partials/form-radio';
import FormExperience from './partials/form-experience';
import FormEducation from './partials/form-education';
import FormPersonalInfo from './partials/form-personal-info';
import FormGovernmentIds from './partials/form-government-id';
import ItemExperience from './partials/experience-item';
import ItemEducation from './partials/education-item';
import useStyles from './styles';

const PublicApplicationForm = () => {
  const [state, setState] = useState<{ client: string | number; name: string }>({ client: '', name: 'hai' });
  const [showExp, setOpenExp] = useState(false);
  const [showEdu, setOpenEdu] = useState(false);
  const [data, setData] = useState({
    experience: [{}],
  });
  const [educations, setEducations] = useState([]);
  const [experiences, setExperiences] = useState([]);
  const classes = useStyles();
  const radioValues = [{ value: 'yes', label: 'Yes' }, { value: 'no', label: 'No' }];
  const variables = { title: 'How did you hear about us?*', typeOfService: 'Type of Service*' };
  const relationOptions = ['Walk-In', 'Employee Referral', 'Job Boards', 'Job Fair', 'Social Media'];
  const checkBoxLabel = 'Please be informed that your application to this job offer will trigger some processing of your personal data by the  company. For more information on data processing, please refer to the company’s talent acquisition privacy policy.';

  const handleChange = ({ target }: ChangeEvent<{ name?: string; value: unknown }>) => {
    setState({ ...state, [target.name as keyof typeof state]: target.value });
  };

  const handleBlur = (event: any) => {
    data.experience[0] = { ...data.experience[0], [event.target.name]: event.target.value };
    setData({ ...data });
  };

  const onAddEdu = (edu: any) => { setEducations([...educations, edu]); setOpenEdu(false); };
  const onAddExp = (exp: any) => { setExperiences([...experiences, exp]); setOpenExp(false); };

  return (
    <Grid className={classes.pageContainer} container>
      <Grid className={classes.formContainer} item xs={12}>
        <Form
          onSubmit={(values) => { console.log(values); }} // eslint-disable-line no-console
          render={({ handleSubmit }) => (
            <form onSubmit={handleSubmit}>
              <Typography className={classes.formHeading} variant="h5">Personal Information</Typography>
              <Box className={classes.marginedBottom}>
                <FieldFileUploader
                  required
                  fileType="avatars"
                  accept={['image/*']}
                  name="resume"
                />
              </Box>
              <FormPersonalInfo setData={setData} data={data} />
              <Box className={classes.spaced}>
                <Box className={classes.fieldContainer}>
                  <Typography className={classes.noMarginBottom} variant="h6">Experience</Typography>
                  <IconButton color="primary" onClick={() => { setOpenExp(!showExp); }}><AddCircleIcon /></IconButton>
                </Box>
                {
                  showExp && (
                    <FormExperience
                      onCancel={() => setOpenExp(false)}
                      onSave={onAddExp}
                      handleBlur={handleBlur}
                    />
                  )
                }
                {experiences.map((exp, index) => <ItemExperience key={index} exp={exp} />)}
              </Box>
              <Box className={classes.spaced}>
                <Box className={classes.fieldContainer}>
                  <Typography className={classes.noMarginBottom} variant="h6">Education</Typography>
                  <IconButton color="primary" onClick={() => { setOpenEdu(!showEdu); }}><AddCircleIcon /></IconButton>
                </Box>
                {
                  showEdu && (
                    <FormEducation
                      onCancel={() => setOpenEdu(false)}
                      onSave={onAddEdu}
                      setData={setData}
                      data={data}
                    />
                  )
                }
                {educations.map((edu, index) => <ItemEducation key={index} edu={edu} />)}
              </Box>
              <Typography className={classes.formText} variant="h6">On the web</Typography>
              <Box className={classes.fieldContainer}>
                <FieldInput className={classes.textField} type="text" required name="applicant-linkedin" label="Linkedin" onChange={(event: React.ChangeEvent<HTMLInputElement>) => setData({ ...data, [event.target.name]: event.target.value })} />
              </Box>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <FieldInput className={classes.textField} type="text" required name="applicant-facebook" label="Facebook" onChange={(event: React.ChangeEvent<HTMLInputElement>) => setData({ ...data, [event.target.name]: event.target.value })} />
              </Box>
              <Typography className={classes.formText} variant="h6">Resume</Typography>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <Box className={classes.dropZone}>
                  <FieldFileUploader
                    required
                    fileType="resumes"
                    fieldLabel="Click or Drag file here to upload resume"
                    accept={['application/pdf']}
                    name="resume"
                  />
                </Box>
              </Box>
              <Typography className={classes.formText} variant="h6">Check the box of the ones you don't have.</Typography>
              <Box className={classes.marginedBottom}>
                <FormGovernmentIds setData={setData} data={data} />
              </Box>
              <Typography className={classes.formText} variant="h6">Preliminary Questions</Typography>
              <Box className={`${classes.fieldContainer} ${classes.marginedBottom}`}>
                <FormControl variant="outlined" className={classes.textField}>
                  <InputLabel htmlFor="outlined-age-native-simple">{variables.title}</InputLabel>
                  <Select
                    native
                    value={state.client}
                    onChange={handleChange}
                    label="How did you hear about us?"
                    inputProps={{ name: 'client', id: 'outlined-age-native-simple' }}
                    onClick={
                      (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => setData({
                        ...data,
                        [event.target.name]: event.target.value,
                      })
                    }
                  >
                    <option aria-label="None" value="" />
                    {relationOptions.map((item, index) => (
                      <option key={index} value={item.replace(' ', '-').toLowerCase()}>{item}</option>))}
                  </Select>
                </FormControl>
              </Box>
              <FormRadioQuestions
                fieldClassName={classes.fieldContainer}
                textClassName={classes.textField}
                values={radioValues}
                setData={setData}
                data={data}
              />
              <Box className={classes.fieldContainer}>
                <FieldCheckbox className={classes.textField} name="confirm-registration" label={checkBoxLabel} />
              </Box>
              <Box className={classes.fieldContainer}>
                <Button component="button" type="submit" className={classes.spaced} variant="contained" color="primary">
                  Submit
                </Button>
              </Box>
            </form>
          )}
        />
      </Grid>
    </Grid>
  );
};

export default PublicApplicationForm;

The FormPersonalInfo component consists of fields such as applicant-first-name, last name, email, location, mobile, etc.

When I click on the AddCircleIcon button to show some other fields and to add experiences/education, I got this error.

When I click the submit button I only got this log.

This is the Experience forms same with Education forms

My goal is to add experince and education array to the result set just like this.

Body:
The error is clear, there are <form> tags nested.

Quick example to reproduce error

const { useState, useEffect } = React;

const App = () => {

return <form>
  <form></form>
</form>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>

In your case showExp evaluates to true after click action, then FormExperience component, which apparently has form tag in it, renders and validateDOMNesting throws error.

  showExp && (
    <FormExperience
      onCancel={() => setOpenExp(false)}
      onSave={onAddExp}
      handleBlur={handleBlur}
    />)


问:
Efficient way to find Frequency of a character in a String in java :  O(n)
In a recent interview I was asked to write the below program.
Find out the character whose frequency is minimum in the given String ?
So I tried by iterating through the string by using charAt and storing the character as key in a HashMap and the number of occurences as its value.
Now Again I have to iterate on the Map to find the lowest element.

Is there a more efficient way to do it as obviously the above one is too intensive i guess.

Update and Another Solution

After some thought process  and answers I think the best time that this can be is O(n).
In the first iteration we will have to iterate through the String character by character and then store their frequency in an Array at the specific position(character is an int) and same time have two temporary variables which maintain the least count and the corresponding character.So when I go to the next character and store its frequency in arr[char] = arr[char]+1;At the same time I will check if the temp varible has a value greater than this value,if yes then the temp varible will be this value and also the char will be this one.In this way i suppose we dont need a second iteration to find the smallest and also no sorting is required I guess

.... Wat say  ? Or any more solutions

答:
I think your approach is in theory the most efficient (O(n)). However in practice it needs quite a lot of memory, and is probably very slow.

It is possibly more efficient (at least it uses less memory) to convert the string to a char array, sort the array, and then calculate the frequencies using a simple loop. However, in theory it is less efficient (O(n log n)) because of sorting (unless you use a more efficient sort algorithm).

Test case:

```<code>import java.util.Arrays;

public class Test {

    public static void main(String... args) throws Exception {
        //        System.out.println(getLowFrequencyChar("x"));
        //        System.out.println(getLowFrequencyChar("bab"));
        //        System.out.println(getLowFrequencyChar("babaa"));
        for (int i = 0; i < 5; i++) {
            long start = System.currentTimeMillis();
            for (int j = 0; j < 1000000; j++) {
                getLowFrequencyChar("long start = System.currentTimeMillis();");
            }
            System.out.println(System.currentTimeMillis() - start);
        }

    }

    private static char getLowFrequencyChar(String string) {
        int len = string.length();
        if (len == 0) {
            return 0;
        } else if (len == 1) {
            return string.charAt(0);
        }
        char[] chars = string.toCharArray();
        Arrays.sort(chars);
        int low = Integer.MAX_VALUE, f = 1;
        char last = chars[0], x = 0;
        for (int i = 1; i < len; i++) {
            char c = chars[i];
            if (c != last) {
                if (f < low) {
                    if (f == 1) {
                        return last;
                    }
                    low = f;
                    x = last;
                }
                last = c;
                f = 1;
            } else {
                f++;
            }
        }
        if (f < low) {
            x = last;
        }
        return (char) x;
    }

}
</code>```

Body:
I think your approach is in theory the most efficient (O(n)). However in practice it needs quite a lot of memory, and is probably very slow.

It is possibly more efficient (at least it uses less memory) to convert the string to a char array, sort the array, and then calculate the frequencies using a simple loop. However, in theory it is less efficient (O(n log n)) because of sorting (unless you use a more efficient sort algorithm).

Test case:

import java.util.Arrays;

public class Test {

    public static void main(String... args) throws Exception {
        //        System.out.println(getLowFrequencyChar("x"));
        //        System.out.println(getLowFrequencyChar("bab"));
        //        System.out.println(getLowFrequencyChar("babaa"));
        for (int i = 0; i < 5; i++) {
            long start = System.currentTimeMillis();
            for (int j = 0; j < 1000000; j++) {
                getLowFrequencyChar("long start = System.currentTimeMillis();");
            }
            System.out.println(System.currentTimeMillis() - start);
        }

    }

    private static char getLowFrequencyChar(String string) {
        int len = string.length();
        if (len == 0) {
            return 0;
        } else if (len == 1) {
            return string.charAt(0);
        }
        char[] chars = string.toCharArray();
        Arrays.sort(chars);
        int low = Integer.MAX_VALUE, f = 1;
        char last = chars[0], x = 0;
        for (int i = 1; i < len; i++) {
            char c = chars[i];
            if (c != last) {
                if (f < low) {
                    if (f == 1) {
                        return last;
                    }
                    low = f;
                    x = last;
                }
                last = c;
                f = 1;
            } else {
                f++;
            }
        }
        if (f < low) {
            x = last;
        }
        return (char) x;
    }

}


问:
Change the background color of textInput highlight (autocomplete) on react-native
How can I change this background color of TextInput when it got highlight from the autoCompleteType that already exists on react native?
like on this image

答:
To customize this autofill bg color, you have to set this at android level.

Create a xml file with the name of your choice, for example autofill_highlight.xml in android/app/src/main/res/drawable

Put this code inside :

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
</shape>
</code>```

Here, the color set is transparent ("@android:color/transparent"), replace it with your color.

In android/app/src/main/res/values/styles.xml, add this line to your app theme (make sure to provide your own file name if you don't call it autofill_highlight like in my example)

```<code><resources>
     <!-- Base application theme. -->
     <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

         <!-- ... your other theme customization ...  -->

         <!-- ADD THE FOLLOWING LINE -->
         <item name="android:autofilledHighlight">@drawable/autofill_highlight</item>

    </style>
</resources>
</code>```

Rebuild your application :)

Body:
To customize this autofill bg color, you have to set this at android level.

Create a xml file with the name of your choice, for example autofill_highlight.xml in android/app/src/main/res/drawable

Put this code inside :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
</shape>

Here, the color set is transparent ("@android:color/transparent"), replace it with your color.

In android/app/src/main/res/values/styles.xml, add this line to your app theme (make sure to provide your own file name if you don't call it autofill_highlight like in my example)

<resources>
     <!-- Base application theme. -->
     <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

         <!-- ... your other theme customization ...  -->

         <!-- ADD THE FOLLOWING LINE -->
         <item name="android:autofilledHighlight">@drawable/autofill_highlight</item>

    </style>
</resources>

Rebuild your application :)


问:
Why is my recursive function won't work and why do I get strange results
I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).

```<code>x = 0
def solution(digits):
    global x
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        solution(digits[1:])
</code>```

My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.

So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.

My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.

So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?

Your help would be appreciated!

EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.

Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this :/

答:
```<code>def max_5_digits(digits, _max=0):
    return _max if len(digits) < 5 else max_5_digits(digits[1:], max(_max, int(digits[:5])))
</code>```

```<code>max_5_digits("9328498503734")
## 98503
</code>```

Body:
I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).

x = 0
def solution(digits):
    global x
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        solution(digits[1:])

My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.

So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.

My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.

So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?

Your help would be appreciated!

EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.

Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this :/

Body:
def max_5_digits(digits, _max=0):
    return _max if len(digits) < 5 else max_5_digits(digits[1:], max(_max, int(digits[:5])))

max_5_digits("9328498503734")
## 98503


问:
What is the fastest way to populate one pandas dataframe based on values from another pandas dataframe?
I have a pandas dataframe position

```<code>        row    column
  1      3     Brazil
  2      6     USA
  3      3     USA
  4      7     Canada
</code>```

and another x

```<code>        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     False    False   False
  4     False    False   False
  5     False    False   False
  6     False    False   False
  7     False    False   False
</code>```

I want to populate the second one based on the values from the first one, so the result is:

```<code>        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     True     False   True
  4     False    False   False
  5     False    False   False
  6     False    False   True
  7     False    True    False
</code>```

I'm doing that using iterrows()

```<code>  for i, r in positions.iterrows():
      x.at[r['row'],r['column']] = True
</code>```

Is there a faster way to do that?

答:
searchsorted and slice assignment with iloc

This assumes that index and columns in x are sorted.

We'll use iloc and tuples of positions to assign the value of True

```<code>i = tuple(x.index.searchsorted(df.row))
j = tuple(x.columns.searchsorted(df.column))

x.iloc[[i, j]] = True
x

   Brazil  Canada    USA
1   False   False  False
2   False   False  False
3    True   False   True
4   False   False  False
5   False   False  False
6   False   False   True
7   False    True  False
</code>```

Body:
I have a pandas dataframe position

        row    column
  1      3     Brazil
  2      6     USA
  3      3     USA
  4      7     Canada

and another x

        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     False    False   False
  4     False    False   False
  5     False    False   False
  6     False    False   False
  7     False    False   False

I want to populate the second one based on the values from the first one, so the result is:

        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     True     False   True
  4     False    False   False
  5     False    False   False
  6     False    False   True
  7     False    True    False

I'm doing that using iterrows()

  for i, r in positions.iterrows():
      x.at[r['row'],r['column']] = True

Is there a faster way to do that?

Body:
searchsorted and slice assignment with iloc

This assumes that index and columns in x are sorted.

We'll use iloc and tuples of positions to assign the value of True

i = tuple(x.index.searchsorted(df.row))
j = tuple(x.columns.searchsorted(df.column))

x.iloc[[i, j]] = True
x

   Brazil  Canada    USA
1   False   False  False
2   False   False  False
3    True   False   True
4   False   False  False
5   False   False  False
6   False   False   True
7   False    True  False


问:
Accessing SQL Server on Windows Server 2008 R2 from remote client
We are currently shifting from using PostgreSQL installed on remote CentOS boxes to using MS SQL Server 2008 R2 installed on remote Windows Server 2008 R2 boxes.

Our web application that uses this database is installed and running on another CentOS box where it will remain.

All of these boxes are provided by a 3rd party hosting provider and are all on the same domain network.

Our development is therefore remote from the server/database domain as our development machines are remote. In the past opening a VPN was enough to allow our development instances of our web app running locally on our PCs to connect remotely to the PostgreSQL database running on the CentOS box.

However now we are having trouble doing the same with the Windows Server 2008 R2 box. Even with the VPN open any attempt to connect (or even ping) the remote server machine times out.

Our code to get a connection to the database instance on the new database server is correct as when we upload that code onto the CentOS application box and run it, it connects fine, as the code is now running on a box in the same physical domain as the Windows Server 2008 R2 box. However we need to make a connection from remote development machines.

Does this make sense?
Are there some windows firewall settings we need to change to allow remote connections?
As I said, we can't even PING the new Windows Server 2008 R2 machine from remote boxes.

答: Combined with tips from the other answers and help from our hosting provider we managed to sort this out. It was mostly an issue of those ports being blocked by our provider.</p>


问:
Do a search on more than one table in laravel method request
In my project I managed to do a search via request and I wanted to do a search filtered by name (in this case already) and also by reference.
I looked on the internet and nothing that helps me up so far.
I appreciate your help:\</p>

```<code>else {
            $valida=2;
            $produtc = Produtos::where('nome' & 'refencia', 'like', "%{$tpesquisa}%")->paginate();
            $nrr = count($produtos);
            $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

            return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));
</code>```

答:
Give this a try I use this when ever i need to do a search</p>

```<code>Produtos::where(function ($query){
       $query->orWhere('nome', 'LIKE', "%". $tpesquisa. "%")
       ->orWhere('refencia', 'LIKE', "%". $tpesquisa. "%");
})
->paginate();
</code>```

Body:
In my project I managed to do a search via request and I wanted to do a search filtered by name (in this case already) and also by reference.
I looked on the internet and nothing that helps me up so far.
I appreciate your help:\

else {
            $valida=2;
            $produtc = Produtos::where('nome' & 'refencia', 'like', "%{$tpesquisa}%")->paginate();
            $nrr = count($produtos);
            $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

            return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));

Body:
Give this a try I use this when ever i need to do a search

Produtos::where(function ($query){
       $query->orWhere('nome', 'LIKE', "%". $tpesquisa. "%")
       ->orWhere('refencia', 'LIKE', "%". $tpesquisa. "%");
})
->paginate();


问:
Android application deployment error in buildozer Python kivy
I am trying to debug and deploy a kivy android app using:

buildoser v=1.2.0,

python version 3.6,

pip3 version 9.0.1,

VMware 15,

ubuntu version 18.04

I have also installed all packages dependency for buildozer as below:

```<code>sudo apt update
sudo apt install -y git zip unzip openjdk-8-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev
pip3 install --user --upgrade cython virtualenv
sudo apt install cython
**also I install these following packages**
sudo apt install cython3
sudo apt-get install autoconf
sudo apt-get install automake
sudo apt-get install g++
sudo apt-get install libtool m4 automake
sudo apt-get install lld
then I type this command
**buildozer -v android debug**
</code>```

after 15-20 minutes deployment it is showing following errors in the console and deployment stopped:

```<code>[INFO]: The requirements (certifi) don't have recipes, attempting to install them with pip
[INFO]: If this fails, it may mean that the module has compiled components and needs a recipe.
[INFO]: -> directory context /home/am-ubuntu/kiv/.buildozer/android/platform/build-armeabi-v7a/build
[INFO]: -> running python3 -m venv venv
[INFO]: Upgrade pip to latest version
[INFO]: -> running bash -c source venv/bin/activate && pip install -U pip
[INFO]: Install Cython in case one of the modules needs it to build
[INFO]: -> running bash -c venv/bin/pip install Cython
Exception in thread background thread for pid 124834:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 1662, in wrap
fn(*args, **kwargs)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 2606, in background_thread
handle_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 2304, in fn
return self.command.handle_command_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 877, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:

RAN: /bin/bash -c 'venv/bin/pip install Cython'

STDOUT:
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting Cython
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
Could not fetch URL https://pypi.org/simple/cython/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/cython/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement Cython (from versions: none)
ERROR: No matching distribution found for Cython
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

STDERR:

Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1231, in
main()
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
ToolchainCL()
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 688, in init
getattr(self, command)(args)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 154, in wrapper_func
build_dist_from_args(ctx, dist, args)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 208, in build_dist_from_args
args, "ignore_setup_py", False
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 598, in build_recipes
ignore_setup_py=ignore_project_setup_py
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 778, in run_pymodules_install
), _env=copy.copy(base_env))
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 167, in shprint
for line in output:
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 925, in next
self.wait()
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 849, in wait
self.handle_command_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 877, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:

RAN: /bin/bash -c 'venv/bin/pip install Cython'

STDOUT:
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting Cython
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
Could not fetch URL https://pypi.org/simple/cython/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/cython/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement Cython (from versions: none)
ERROR: No matching distribution found for Cython
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
</code>```

答:
Looks like a missing dependency issue. You can check the following youtube link: https://www.youtube.com/watch?v=g-V-iH4MQI8&t=320s

It provides a good complete step-by-step procedure to install buildozer correctly.

Body:
I am trying to debug and deploy a kivy android app using:

buildoser v=1.2.0,

python version 3.6,

pip3 version 9.0.1,

VMware 15,

ubuntu version 18.04

I have also installed all packages dependency for buildozer as below:

sudo apt update
sudo apt install -y git zip unzip openjdk-8-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev
pip3 install --user --upgrade cython virtualenv
sudo apt install cython
**also I install these following packages**
sudo apt install cython3
sudo apt-get install autoconf
sudo apt-get install automake
sudo apt-get install g++
sudo apt-get install libtool m4 automake
sudo apt-get install lld
then I type this command
**buildozer -v android debug**

after 15-20 minutes deployment it is showing following errors in the console and deployment stopped:

[INFO]: The requirements (certifi) don't have recipes, attempting to install them with pip
[INFO]: If this fails, it may mean that the module has compiled components and needs a recipe.
[INFO]: -> directory context /home/am-ubuntu/kiv/.buildozer/android/platform/build-armeabi-v7a/build
[INFO]: -> running python3 -m venv venv
[INFO]: Upgrade pip to latest version
[INFO]: -> running bash -c source venv/bin/activate && pip install -U pip
[INFO]: Install Cython in case one of the modules needs it to build
[INFO]: -> running bash -c venv/bin/pip install Cython
Exception in thread background thread for pid 124834:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 1662, in wrap
fn(*args, **kwargs)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 2606, in background_thread
handle_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 2304, in fn
return self.command.handle_command_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 877, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:

RAN: /bin/bash -c 'venv/bin/pip install Cython'

STDOUT:
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting Cython
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
Could not fetch URL https://pypi.org/simple/cython/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/cython/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement Cython (from versions: none)
ERROR: No matching distribution found for Cython
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

STDERR:

Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1231, in
main()
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
ToolchainCL()
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 688, in init
getattr(self, command)(args)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 154, in wrapper_func
build_dist_from_args(ctx, dist, args)
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 208, in build_dist_from_args
args, "ignore_setup_py", False
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 598, in build_recipes
ignore_setup_py=ignore_project_setup_py
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 778, in run_pymodules_install
), _env=copy.copy(base_env))
File "/home/am-ubuntu/kiv/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 167, in shprint
for line in output:
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 925, in next
self.wait()
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 849, in wait
self.handle_command_exit_code(exit_code)
File "/home/am-ubuntu/.local/lib/python3.6/site-packages/sh.py", line 877, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:

RAN: /bin/bash -c 'venv/bin/pip install Cython'

STDOUT:
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting Cython
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/cython/
Could not fetch URL https://pypi.org/simple/cython/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/cython/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement Cython (from versions: none)
ERROR: No matching distribution found for Cython
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping


问:
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.

答:
```<code>const inputs= document.body.querySelectorAll("input")
    document.addEventListener("change", (e)=>{
        inputs.forEach(input=>{
            if(input.checked){
                input.labels[0].style="border-style: solid; padding: 10px;"
            }
            if(!input.checked){
                input.labels[0].style=""
            }
        })
    })
</code>```

here is the js logic

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:
const inputs= document.body.querySelectorAll("input")
    document.addEventListener("change", (e)=>{
        inputs.forEach(input=>{
            if(input.checked){
                input.labels[0].style="border-style: solid; padding: 10px;"
            }
            if(!input.checked){
                input.labels[0].style=""
            }
        })
    })

here is the js logic


问:
pygame vector checking if vector2 length == 0 not working?
So I am trying to check if a vector2 in pygame has a length of 0, and if that is not the case I want to normalise and multiply it by a number.

Here is the relevant code:

```<code>if direction.length() != 0:
    velocity = direction.normalize()
    rect.center += velocity * speed
</code>```

Both velocity and direction are Vector2s.

However, this code always triggers and gives an error that it cannot normalise a Vector with the length of 0.

However, when I change it slightly to:

```<code>if direction != pygame.math.Vector2(0,0):
    velocity = direction.normalize()
    rect.center += velocity * speed
</code>```

then it works.

Am I doing something wrong in the first example? When I print Vector2.length() it gives me a float with the value 0, but somehow this still gets through the if condition. Hence, I am confused.

答:
Normalizing a vector is nothing else than dividing the components of a vector by is length. Compute the length of the vector and divide the vector by the length if it is not 0:

dir_len = direction.length()
if direction.length() != 0:
    velocity = direction / dir_len
```

Body:
So I am trying to check if a vector2 in pygame has a length of 0, and if that is not the case I want to normalise and multiply it by a number.

Here is the relevant code:

if direction.length() != 0:
    velocity = direction.normalize()
    rect.center += velocity * speed

Both velocity and direction are Vector2s.

However, this code always triggers and gives an error that it cannot normalise a Vector with the length of 0.

However, when I change it slightly to:

if direction != pygame.math.Vector2(0,0):
    velocity = direction.normalize()
    rect.center += velocity * speed

then it works.

Am I doing something wrong in the first example? When I print Vector2.length() it gives me a float with the value 0, but somehow this still gets through the if condition. Hence, I am confused.


问:
Doing while with html and php
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

```<code><p>

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "<div class=\"pagination\">";         //previous button
            if ($page > 1)
                $pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
            else
                $pagination.= "<span class=\"disabled\">« previous</span>";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
            else
                $pagination.= "<span class=\"disabled\">next »</span>";
            $pagination.= "</div>\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '<a href="http://geatzo.com/do123.php?uid='.$row['id'].'"><img src="http://www.geatzo.com/images/coins.jpg" height="100px" width="100px"/>';
            echo '"<p> </p>';
            echo '"You will earn<b>"'.$row['coins'].'"</b>Coins"<p> </p>';
            echo '"Posted By "'.$row['username'].'<p> </p>';
            echo '"Site you will be viewing "'.$row['url'].'<p> </p>';
        }
    ?>

    <?=$pagination?>

</p>
</code>```

I want to put that php in a a html div
here is the html

```<code><div class="ptcbox-link"><a href="http://www.mysite.com/gpt.php?v=entry&type=ptc&id=6960&sid=TWk0Mk1Ea3hORGc1TVRB&sid2=TWk0M&siduid=186998&"></a></div>
                <div class="ptcbox-value-w1">
                    <div class="ptcbox-value">$2</div>
                    <div class="ptcbox-seconds">30 seconds</div>
                </div>
</code>```

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while

答:
T think you want something like this:

while($row =
  mysql_fetch_array($result))       {
      echo ';

echo '

';  echo '"  You will
  earn"'.$row['coins'].'"Coins"

';
  echo '"Posted By
  "'.$row['username'].'

';
  echo '"Site you will
  be viewing"'.$row['url'].'

  ';   }

Title: Doing while with html and php

Body:
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "
";         //previous button
            if ($page > 1)
                $pagination.= "« previous";
            else
                $pagination.= "« previous";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "next »";
            else
                $pagination.= "next »";
            $pagination.= "
\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '';
            echo '"

';
            echo '"You will earn"'.$row['coins'].'"Coins"

';
            echo '"Posted By "'.$row['username'].'

';
            echo '"Site you will be viewing "'.$row['url'].'

';
        }
    ?>

    <?=$pagination?>

I want to put that php in a a html div
here is the html

$2

30 seconds

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while


问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
We had the same issue, after some troubleshooting we found that the root certificates of COMODO where expired.

Valid until    Sat, 30 May 2020 10:48:38 UTC (expired 3 days, 5 hours ago)   EXPIRED

We tested this via: https://www.ssllabs.com/ssltest/index.html.
And we resolved it by downloading the certificates freshly from our reseller.

This is the result we received about the COMODO certificates

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


问:
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

答: The Issue is a a result of some classes used in the template i was using which is based on BS3 but not existent in BS4 </p>


问:
Difference between targetPort and port in Kubernetes Service definition
A Kubernetes Service can have a targetPort and port in the service definition:

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9376
```

What is the difference between the port and targetPort?

答:
This answer is to reference Kubernetes' documentation in addition to the other answers:

https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/:

targetPort: is the port the container accepts traffic on,

port: is the abstracted Service port, which can be any port other pods use to access the Service

https://kubernetes.io/docs/concepts/services-networking/service/:

Port definitions in Pods have names, and you can reference these names in the targetPort attribute of a Service. This works even if there is a mixture of Pods in the Service using a single configured name, with the same network protocol available via different port numbers.

Body:
A Kubernetes Service can have a targetPort and port in the service definition:

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9376

What is the difference between the port and targetPort?


问:
How to integrate stripe with react-native expo sdk36 without ejecting?
I am reading:

https://docs.expo.io/versions/latest/sdk/payments/

https://tipsi.github.io/tipsi-stripe/docs/running-apple-pay-on-a-real-device.html

https://github.com/stripe/react-stripe-elements/issues/21

https://pusher.com/tutorials/react-native-payments

https://medium.com/@lyzhovnik/using-stripe-payment-service-with-react-native-and-fetch-4177c8d992cb

https://github.com/expo/stripe-expo

I want to integrate stripe payment within a react-native app build with expo sdk 36.

My project is not ejected and I would like to keep it so I can still run and debug iOS app without needing apple hardware. (it's for developer experience, but I want to see if there's a way before squeezing that.)

To me, it seems that stripe just need an HTTP client to communicate, while I have fetch, am I correct?

Why exactly do I need to eject, what native library do I need to plug and why the http client is not sufficient?

How can I integrate stripe to target all of the platforms (web/ios/native) with the less effort (what library should I get started with to resolve my goal.)

答:
Expo really doesn't support the expo-payments-stripe module for React Native in managed workflow. Although there is a little trick. You can implement it by using a WebView, as (for example) this npm-module does: expo-stripe-checkout. This module uses Stripe Checkout.

Regarding your question about using a normal HTTP-Client, maybe this article helps: Using Stripe API in React Native with fetch

I hope this helps!

EDIT:
Stripe just released the official Stripe client library for React Native as public beta: stripe-react-native. I would suggest looking into that.