问:
Using a for loop to create a new list
I have a list of strings and would like to use a for loop to change the strings and create a new list.

```<code>oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
</code>```

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

答:
Use list comp:</p>

```<code>oldList = ['AAA','BBB','CCC']
newList = ['a_' + i + '_z' for i in oldList]
</code>```

Title: Using a for loop to create a new list

Body:
I have a list of strings and would like to use a for loop to change the strings and create a new list.

oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

Body:
Use list comp:

oldList = ['AAA','BBB','CCC']
newList = ['a_' + i + '_z' for i in oldList]


来源: stackexchange

问:
makeStyles show a div when hovering over nested a link
So I am trying to show a div box when a user hovers over the link.

For example:
Say I have an image inside the a href I want a div to float above that and say click here.

React Style code.

```<code>a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
</code>```

React code

                  Stuff shown on hover

Full code

```<code>import React from 'react';
import clsx from 'clsx';
import { makeStyles,styled } from '@material-ui/core/styles';
//import Typography from '@material-ui/core/Typography';
import { Container, Button, Grid } from '@material-ui/core';
import comedynight from '../images/shows/PrideInjulyFridaynightcomedy2020.png';
import dragnight from '../images/shows/PrideInjulySaturdaynightDrag2020.png';

const drawerWidth = 240;
const DonateButton = styled(Button)({
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
  border: 0,
  borderRadius: 3,
  boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  color: 'white',
  height: 48,
  width: '100%',
  fontWeight: 'Bold',
  padding: '0 30px',
});

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
  },
  appBar: {
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  hide: {
    display: 'none',
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
  },
  drawerPaper: {
    width: drawerWidth,
  },
  drawerHeader: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: 0,
  },
  contentShift: {
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginLeft: 0,
  },
  a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
}));

export default function Home() {

    const classes = useStyles();
    const [open] = React.useState(false);

    return(
        <Container>
        <main
        className={clsx(classes.content, {
          [classes.contentShift]: open,
        })}
      >
          <Grid container spacing={3}>
            <Grid item lg={12}>
              <DonateButton>Click here to donate now to support WAAids Council</DonateButton>
            </Grid>
            <Grid item md={6}>
              <a href="/shows/comedy" alt="Friday Comedy Night" className={classes.a}>
              <img src={comedynight} alt="Friday Night Comedy" style={{width:"100%"}}/>
              </a>
              <div id="show" style={{display:'none'}}>Stuff shown on hover</div>
            </Grid>
            <Grid item md={6}>
            <img src={dragnight} alt="Saturday Night Drag" style={{width:"100%"}}/>
            </Grid>
          </Grid>
      </main>
      </Container>
    )
}
</code>```

答:
The code in your question ('& div#show') doesn't work because you are using a descendant selector instead of a sibling selector and the div is not a descendant of the link. Also, display: "none" needs to be in the JSS (within the styles passed to makeStyles). If you instead do it in inline styles (as you currently have it), the inline styles will win over the CSS classes generated by JSS because inline styles have higher specificity.

Below is an example of using an adjacent sibling selector in JSS. This is using another class for the toggled element rather than using an id, see my second example if you want to continue using an id.

```<code>import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  triggerElement: {
    "&:hover + $toggledElement": {
      backgroundColor: "#ccc",
      display: "block"
    }
  },
  toggledElement: {
    display: "none"
  }
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <div className={classes.triggerElement}>
        This is the trigger element. Hover over this to see the toggled element.
      </div>
      <div className={classes.toggledElement}>This is the toggled element</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Here is another example based more closely on your existing code:

```<code>import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  a: {
    "& + #show": {
      display: "none"
    },
    "&:hover + #show": {
      backgroundColor: "#ccc",
      display: "block"
    }
  }
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <a href="/shows/comedy" className={classes.a}>
        Friday Night Comedy
      </a>
      <div id="show">Stuff shown on hover</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I am trying to show a div box when a user hovers over the link.

For example:
Say I have an image inside the a href I want a div to float above that and say click here.

React Style code.

a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },

React code

                  Stuff shown on hover

Full code

import React from 'react';
import clsx from 'clsx';
import { makeStyles,styled } from '@material-ui/core/styles';
//import Typography from '@material-ui/core/Typography';
import { Container, Button, Grid } from '@material-ui/core';
import comedynight from '../images/shows/PrideInjulyFridaynightcomedy2020.png';
import dragnight from '../images/shows/PrideInjulySaturdaynightDrag2020.png';

const drawerWidth = 240;
const DonateButton = styled(Button)({
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
  border: 0,
  borderRadius: 3,
  boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  color: 'white',
  height: 48,
  width: '100%',
  fontWeight: 'Bold',
  padding: '0 30px',
});

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
  },
  appBar: {
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  hide: {
    display: 'none',
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
  },
  drawerPaper: {
    width: drawerWidth,
  },
  drawerHeader: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: 0,
  },
  contentShift: {
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginLeft: 0,
  },
  a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
}));

export default function Home() {

    const classes = useStyles();
    const [open] = React.useState(false);

    return(
        <Container>

          <Grid container spacing={3}>
            <Grid item lg={12}>
              <DonateButton>Click here to donate now to support WAAids Council</DonateButton>
            </Grid>
            <Grid item md={6}>

Stuff shown on hover

            </Grid>
            <Grid item md={6}>

            </Grid>
          </Grid>

      </Container>
    )
}

Body:
The code in your question ('& div#show') doesn't work because you are using a descendant selector instead of a sibling selector and the div is not a descendant of the link. Also, display: "none" needs to be in the JSS (within the styles passed to makeStyles). If you instead do it in inline styles (as you currently have it), the inline styles will win over the CSS classes generated by JSS because inline styles have higher specificity.

Below is an example of using an adjacent sibling selector in JSS. This is using another class for the toggled element rather than using an id, see my second example if you want to continue using an id.

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  triggerElement: {
    "&:hover + $toggledElement": {
      backgroundColor: "#ccc",
      display: "block"
    }
  },
  toggledElement: {
    display: "none"
  }
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <div className={classes.triggerElement}>
        This is the trigger element. Hover over this to see the toggled element.
      </div>
      <div className={classes.toggledElement}>This is the toggled element</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here is another example based more closely on your existing code:

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  a: {
    "& + #show": {
      display: "none"
    },
    "&:hover + #show": {
      backgroundColor: "#ccc",
      display: "block"
    }
  }
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <a href="/shows/comedy" className={classes.a}>
        Friday Night Comedy
      </a>
      <div id="show">Stuff shown on hover</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


问:
Share on LinkedIn with og
I have rails app. I added og tags for Facebook, google +, and Vkontakte. And I need to add possibility to share to LinkedIn too. But I don't understand why LinkedIn don't pick my OG tags.

My html:

```<code>= tag :meta, property: 'og:url', content: 'https://myapp.com/app'
= tag :meta, property: 'og:title', content: 'MyApp'
= tag :meta, property: 'og:description', content: 'You can always find a my app !'
= tag :meta, property: 'og:image', content: "https://myapp.com#{image_path('backgrounds/desk.jpg')}"
</code>```

And facebook, g+, vk works perfectly, but linked in don't fetch any information from my website.

Any advise?

答:
Interesting!  You made your post on March 10, 2017.  Support for og: tags at LinkedIn was only officially added and released on March 23, 2017; the feature just 13 days away!

The following formats are now all supported...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: Official LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

Works great for me:

If you want to verify that you have the tags in place correctly in your  block of HTML, try testing the page you're sharing at LinkedIn Post Inspector.

ContentLicense: CC BY-SA 3.0

Title: Share on LinkedIn with og

Body:
I have rails app. I added og tags for Facebook, google +, and Vkontakte. And I need to add possibility to share to LinkedIn too. But I don't understand why LinkedIn don't pick my OG tags.

My html:

= tag :meta, property: 'og:url', content: 'https://myapp.com/app'
= tag :meta, property: 'og:title', content: 'MyApp'
= tag :meta, property: 'og:description', content: 'You can always find a my app !'
= tag :meta, property: 'og:image', content: "https://myapp.com#{image_path('backgrounds/desk.jpg')}"

And facebook, g+, vk works perfectly, but linked in don't fetch any information from my website.

Any advise?

Body:
Interesting!  You made your post on March 10, 2017.  Support for og: tags at LinkedIn was only officially added and released on March 23, 2017; the feature just 13 days away!

The following formats are now all supported...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: Official LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

Works great for me:

If you want to verify that you have the tags in place correctly in your <head> block of HTML, try testing the page you're sharing at LinkedIn Post Inspector.


问:
discord bot adding reaction to message via python
I wanna make a bot react with the normal emojis to a message when a certain word is used in the message but I can't seem to find any solution that work for current version of discord.py. Can anyone help me with a format I can use?</p>

答: You should read the documentation of discordpy. It shows there how to add a reaction to a message and has plenty of explanations (I attached the specific link to your problem).</p>


问:
copying gridview data from one form to another form's gridview
```<code>protected void Page_Load(object sender, EventArgs e)
{
    Calendar1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("connection string");
    con.Open();
    DataTable dt = new DataTable();
    SqlCommand sqlCmd = new SqlCommand("SELECT distinct plantname,operatorname FROM datalogging1 WHERE Line='" + ddlline.SelectedItem + "'and date='"+txtdate.Text+"'and shiftname='"+ddlshift.SelectedItem+"'", con);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
    sqlDa.Fill(dt);

    if (dt.Rows.Count > 0)
    {
        //Where ColumnName is the Field from the DB that you want to display
        txtplant.Text = dt.Rows[0]["Plantname"].ToString();
        txtop.Text = dt.Rows[0]["operatorname"].ToString();

    }
}
protected void btndate_Click(object sender, EventArgs e)
{
    Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    txtdate.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd");
}
protected void btnreport_Click(object sender, EventArgs e)
{
    int var = ddlshift.SelectedIndex;
    switch (var)
    {
        case 0:
            break;
        case 1: SqlConnection con1 = new SqlConnection("connection string");
            con1.Open();
            DataTable dt = new DataTable();
            SqlCommand cmd1 = new SqlCommand("select Date=convert(varchar(12),isnull(t1.date,t2.date),101),Time=convert(varchar(8),isnull(t1.time,t2.time),8),isnull(t1.temprature,0) as Temperature,isnull(t2.pressure,0) as Pressure,isnull(t3.co2,0) as Co2,isnull(t4.do2,0) as Do2,isnull(t5.ph,0) as pH,isnull(t6.speed,0) as Speed,isnull(t7.flow,0) as Flow from temprature3 t1 full outer join pressure3 t2 on t2.date=t1.date and t1.time=t2.time full outer join co23 t3 on t1.date=t3.date and t1.time=t3.time full outer join do23 t4 on t1.date=t4.date and t1.time=t4.time full outer join ph3 t5 on t1.date=t5.date and t1.time=t5.time full outer join speed3 t6 on t1.date=t6.date and t1.time=t6.time full outer join flow3 t7 on t1.date=t7.date and t1.time=t7.time where t1.Date='"+txtdate.Text+"' and t1.time between '1900-01-01 7:00:00.000' and '1900-01-01 12:59:59.999'", con1);
            SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
            da1.Fill(dt);
            GridView1.Visible = true;
            GridView1.DataSource = dt;
            GridView1.DataBind();
            break;
        case 2:
            SqlConnection con2 = new SqlConnection("connection string");
            con2.Open();
            DataTable dt1 = new DataTable();
            SqlCommand cmd2 = new SqlCommand("select Date=convert(varchar(12),isnull(t1.date,t2.date),101),Time=convert(varchar(8),isnull(t1.time,t2.time),8),isnull(t1.temprature,0) as Temperature,isnull(t2.pressure,0) as Pressure,isnull(t3.co2,0) as Co2,isnull(t4.do2,0) as Do2,isnull(t5.ph,0) as pH,isnull(t6.speed,0) as Speed,isnull(t7.flow,0) as Flow from temprature3 t1 full outer join pressure3 t2 on t2.date=t1.date and t1.time=t2.time full outer join co23 t3 on t1.date=t3.date and t1.time=t3.time full outer join do23 t4 on t1.date=t4.date and t1.time=t4.time full outer join ph3 t5 on t1.date=t5.date and t1.time=t5.time full outer join speed3 t6 on t1.date=t6.date and t1.time=t6.time full outer join flow3 t7 on t1.date=t7.date and t1.time=t7.time where t1.Date='" + txtdate.Text + "' and t1.time between '1900-01-01 13:00:00.000' and '1900-01-01 22:59:59.999'", con2);
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(dt1);
            GridView1.Visible = true;
            GridView1.DataSource = dt1;
            GridView1.DataBind();
            break;
        case 3: SqlConnection con3 = new SqlConnection(""connection string);
            con3.Open();
            DataTable dt2 = new DataTable();
            SqlCommand cmd3 = new SqlCommand("select Date=convert(varchar(12),isnull(t1.date,t2.date),101),Time=convert(varchar(8),isnull(t1.time,t2.time),8),isnull(t1.temprature,0) as Temperature,isnull(t2.pressure,0) as Pressure,isnull(t3.co2,0) as Co2,isnull(t4.do2,0) as Do2,isnull(t5.ph,0) as pH,isnull(t6.speed,0) as Speed,isnull(t7.flow,0) as Flow from temprature3 t1 full outer join pressure3 t2 on t2.date=t1.date and t1.time=t2.time full outer join co23 t3 on t1.date=t3.date and t1.time=t3.time full outer join do23 t4 on t1.date=t4.date and t1.time=t4.time full outer join ph3 t5 on t1.date=t5.date and t1.time=t5.time full outer join speed3 t6 on t1.date=t6.date and t1.time=t6.time full outer join flow3 t7 on t1.date=t7.date and t1.time=t7.time where t1.Date='" + txtdate.Text + "' and t1.time between '1900-01-01 23:00:00.000' and '1900-01-01 6:59:59.999'", con3);
            SqlDataAdapter da3 = new SqlDataAdapter(cmd3);
            da3.Fill(dt2);
            GridView1.Visible = true;
            GridView1.DataSource = dt2;
            GridView1.DataBind();
            break;
    }
}
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
    Response.Clear();
    Response.AddHeader("content-disposition",
        string.Format("attachment;filename={0}.xls", fileName));
    Response.Charset = "";
    Response.ContentType = "application/vnd.xls";

    StringWriter stringWrite = new StringWriter();
    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    grdGridView.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that a Form control was rendered */
}

protected void Button1_Click(object sender, EventArgs e)
{
    ExportGridToExcel(GridView1, "report.xls");
}
</code>```

答:
Since you have not provided the code, we can't figure out the issue.

But the code below works perfectly to Export GridView data to Excel, you can use this code.

```<code>public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.ClearContent();
Response.AddHeader("content-disposition",
    string.Format("attachment;filename={0}.xls", fileName));
Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}
</code>```

Body:
Since you have not provided the code, we can't figure out the issue.

But the code below works perfectly to Export GridView data to Excel, you can use this code.

public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.ClearContent();
Response.AddHeader("content-disposition",
    string.Format("attachment;filename={0}.xls", fileName));
Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}


问:
What simple Scenario healthcheck message JSONdate?
I have trouble in applying Java Spring boots with some rules:
 - If parameters values do not match the specifics possible values you should return HTTP status code 400("Bad Request")
 - Responses should have Content-Type header with approriate value(application/json)
 - If you need to create multiple classes
 - You can use only the following libraries:

Spring web MVC (v.5.0.7.Release)

Faster XML Jackson, Jackson datatype JSR310

I need detailed method read healtcheck with message:
{"currentTime" : "2020-06-01T20:45:35Z,"application":"OK"}

答:
You can customise the health check endpoint by implementing HealthIndicator and providing custom logic.

For example, you can check out simple implementation here (https://www.amitph.com/custom-health-check-spring-boot-actuator/).


问:
How to include Jinja2 templating in my Sendgrid Transactional Template
Is there a way to include jinja2 templating in Sendgrid template?
Am trying to use {% for %} and {% endfor %} in Sendgrid template but it doesn't seem to work. Though email sends successfully but its empty when I open it.

HTML Code(placeorder.html):

```<code>  <body>

  <h3>From: {{name}}</h3>
  <h3>Email: {{emailFrom}}</h3>

    <table id="customers">
        <tr>
            <th>Product</th>
            <th>Quantity</th>
            <th>Sub Total</th>
        </tr>
        {% for order_item in order.items.all %}
        <tr>
            <td>{{ order_item.item.title}}</td>
            <td>{{ order_item.quantity }}</td>
            <td>₦{{ order_item.get_final_price }}</td>
        </tr>
        {% endfor %}
        <p>
            <span>Total ₦</span>
            <strong>{{ order.get_total }}</strong>
        </p>

    </table>

</body>
</code>```

Views.py(Django)

```<code>     def placeorder(request):
         form = orderform(request.POST)
         try:
            order = Order.objects.get(user=request.user, ordered=False)
            if form.is_valid():
               order = Order.objects.get(user=request.user, ordered=False)
               name = form.cleaned_data['name']
               emailFrom = form.cleaned_data['email']
               emailTo = settings.DEFAULT_FROM_EMAIL

               message = Mail(
                  from_email=emailFrom,
                  to_emails= emailTo ,
                  subject='subject',
                  html_content= settings.BASE_DIR + "/templates/placeorder.html")

               message.dynamic_template_data = {
                  'name': name,
                  'email': emailFrom ,
                  }
               message.template_id = '********************************'
               try:
                     sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                     response = sg.send(message)
                     messages.success(request, "Thanks, We received your Order message. We will get back to you!.")
                     OrderItem.delete(order)
               except Exception as e:
                       messages.warning(request, "Sorry, Order message not sent.Please Try Again!.")
         return render(request, "checkout.html", context)
</code>```

答:
You can use the Handlebars.js syntax in Dynamic Templates.

Here is the link to the documentation in Sendgrid.

Body:
Is there a way to include jinja2 templating in Sendgrid template?
Am trying to use {% for %} and {% endfor %} in Sendgrid template but it doesn't seem to work. Though email sends successfully but its empty when I open it.

HTML Code(placeorder.html):

From: {{name}}

Email: {{emailFrom}}

            Product
            Quantity
            Sub Total

        {% for order_item in order.items.all %}

            {{ order_item.item.title}}
            {{ order_item.quantity }}
            ₦{{ order_item.get_final_price }}

        {% endfor %}

            Total ₦
            {{ order.get_total }}

Views.py(Django)

     def placeorder(request):
         form = orderform(request.POST)
         try:
            order = Order.objects.get(user=request.user, ordered=False)
            if form.is_valid():
               order = Order.objects.get(user=request.user, ordered=False)
               name = form.cleaned_data['name']
               emailFrom = form.cleaned_data['email']
               emailTo = settings.DEFAULT_FROM_EMAIL

               message = Mail(
                  from_email=emailFrom,
                  to_emails= emailTo ,
                  subject='subject',
                  html_content= settings.BASE_DIR + "/templates/placeorder.html")

               message.dynamic_template_data = {
                  'name': name,
                  'email': emailFrom ,
                  }
               message.template_id = '********************************'
               try:
                     sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                     response = sg.send(message)
                     messages.success(request, "Thanks, We received your Order message. We will get back to you!.")
                     OrderItem.delete(order)
               except Exception as e:
                       messages.warning(request, "Sorry, Order message not sent.Please Try Again!.")
         return render(request, "checkout.html", context)


问:
Converting images in a folder to grayscale using python and opencv and writing it to a specific folder
```<code>import glob
import cv2
import os
import numpy as np
from PIL import Image
images=[]
images=np.array(images)
path='C:\Users\Quantum\Desktop\test'
count=0
images = [cv2.imread(file,0) for file in glob.glob("E:\homework\Computer vision\Faces\*.jpg")]
for i in range(len(images)):
#    im = Image.fromarray(images[i])
#    cv2.imwrite(str(path) + '.jpg', images[count])
    cv2.imwrite(os.path.join(path, 'pic.jpg'), images[count])
    count+=1
</code>```

Trying to select all the images from a folder and the images are getting selected and are converted to grayscale although I dont know how to write those images to a specific folder.Kindly help

答:
```<code>import os,cv2
path = r'C:\Users\me\Desktop\folder' # Source Folder
dstpath = r'C:\Users\me\Desktop\desfolder' # Destination Folder

try:
    makedirs(dstpath)
except:
    print ("Directory already exist, images will be written in asme folder")

# Folder won't used
files = os.listdir(path)

for image in files:
    img = cv2.imread(os.path.join(path,image))
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    cv2.imwrite(os.path.join(dstpath,image),gray)
</code>```

Body:
import glob
import cv2
import os
import numpy as np
from PIL import Image
images=[]
images=np.array(images)
path='C:\Users\Quantum\Desktop\test'
count=0
images = [cv2.imread(file,0) for file in glob.glob("E:\homework\Computer vision\Faces\*.jpg")]
for i in range(len(images)):
#    im = Image.fromarray(images[i])
#    cv2.imwrite(str(path) + '.jpg', images[count])
    cv2.imwrite(os.path.join(path, 'pic.jpg'), images[count])
    count+=1

Trying to select all the images from a folder and the images are getting selected and are converted to grayscale although I dont know how to write those images to a specific folder.Kindly help


问:
Getting text input from the user and print it python using kivy
I am trying to print an input given by a user but all I get is: < ObjectProperty name=input >

I can't use Text Input in my py because python quits if I try to run a program with it installed. I have tried putting the popup in the 'test' class but it just comes up with a different error.

Any help is appreciated,
Thank you.

Here is my code:

In my py:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.popup import Popup

class MyPopup(Popup):
    pass

class Test(Widget):
pass

class TestApp(App):
    def build(self):
        return Test()

    def Process(self):
        text = MyPopup.input
        print(text)

if __name__ == '__main__':
    TestApp().run()
</code>```

and in my kv:

```<code>#:import Factory kivy.factory.Factory

<MyPopup@Popup>
    input: text
    auto_dismiss: True
    size_hint: 0.4, 0.4
    TextInput:
        id: text
        hint_text: 'insert text'
        multiline: False
        on_text_validate: app.Process()

<Test>:
    canvas:
        Color:
            rgba: 0, 0, 0, 0
        Rectangle:
            pos: 0, 0
            size: self.width, self.height - self.height/6
        Color:
            rgba: 1, 1, 1, 0.1
        Rectangle:
            pos: 0, 0
            size: self.width/2 + self.width/10, self.height - self.height/6
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: 0, self.height - self.height/6
            size: self.width, self.height/6

    Button:
        id: GL
        text: 'In here'
        pos: 0 , root.height - root.height/6
        on_parent: GLdropdown.dismiss()
        on_release: GLdropdown.open(self)
        size_hint_y: None
        height: root.height/6
        width: root.width/7
    DropDown:
        id: GLdropdown
        on_select: btn.text = '{}'.format(args[1])

        Button:
            id: 'AV'
            text: 'press me'
            size_hint_y: None
            height: 50
            on_release: Factory.MyPopup().open()
</code>```

答:
If you change:

```<code>on_text_validate: app.Process()
</code>```

to:

```<code>on_text_validate: app.Process(self.text)
</code>```

And change the Process() method to:

```<code>def Process(self, text):
    print(text)
</code>```

I think it will work as you want.

The problem is that the line:

```<code>text = MyPopup.input
</code>```

makes text a reference to the ObjectProperty of the class MyPopup. What you really want is a reference to the text of the TextInput, which is simply self.text in the TextInput.

Body:
I am trying to print an input given by a user but all I get is: < ObjectProperty name=input >

I can't use Text Input in my py because python quits if I try to run a program with it installed. I have tried putting the popup in the 'test' class but it just comes up with a different error.

Any help is appreciated,
Thank you.

Here is my code:

In my py:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.popup import Popup

class MyPopup(Popup):
    pass

class Test(Widget):
pass

class TestApp(App):
    def build(self):
        return Test()

    def Process(self):
        text = MyPopup.input
        print(text)

if __name__ == '__main__':
    TestApp().run()

and in my kv:

#:import Factory kivy.factory.Factory

<MyPopup@Popup>
    input: text
    auto_dismiss: True
    size_hint: 0.4, 0.4
    TextInput:
        id: text
        hint_text: 'insert text'
        multiline: False
        on_text_validate: app.Process()

<Test>:
    canvas:
        Color:
            rgba: 0, 0, 0, 0
        Rectangle:
            pos: 0, 0
            size: self.width, self.height - self.height/6
        Color:
            rgba: 1, 1, 1, 0.1
        Rectangle:
            pos: 0, 0
            size: self.width/2 + self.width/10, self.height - self.height/6
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: 0, self.height - self.height/6
            size: self.width, self.height/6

    Button:
        id: GL
        text: 'In here'
        pos: 0 , root.height - root.height/6
        on_parent: GLdropdown.dismiss()
        on_release: GLdropdown.open(self)
        size_hint_y: None
        height: root.height/6
        width: root.width/7
    DropDown:
        id: GLdropdown
        on_select: btn.text = '{}'.format(args[1])

        Button:
            id: 'AV'
            text: 'press me'
            size_hint_y: None
            height: 50
            on_release: Factory.MyPopup().open()

Body:
If you change:

on_text_validate: app.Process()

to:

on_text_validate: app.Process(self.text)

And change the Process() method to:

def Process(self, text):
    print(text)

I think it will work as you want.

The problem is that the line:

text = MyPopup.input

makes text a reference to the ObjectProperty of the class MyPopup. What you really want is a reference to the text of the TextInput, which is simply self.text in the TextInput.


问:
,what is the use and benefit of Serialize() function in php
I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.</p>

答:
Let's say you have some post data, but your database/persistent storage can't be modified to store the new post data in separate fields.

You could serialize your $_POST array and store it in the persistent storage you've got. It's useful for generating user-based CRUD applications. I've found the necessity of storing the POST as a "payload" of sorts quite invaluable at times.

Knowing you can do something, doesn't mean you have to use it everywhere.


问:
SignalR: getting error: WebSocket closed
I am working on project of Ionic with angular and AspNet with SignalR that have chat module.
I use SignalR for Chat.It's working smoothly but some time i am getting error as per below screen shot and because of that it's get stop working at all.
I have hosted my service on IIS and creating proxy and communicating with client and server. Here is sample

```<code>    (function () {
        angular
          .module('app')
          .factory('SignalRFactory', SignalRFactory);
        SignalRFactory.$inject = ['$rootScope', 'Hub', 'ionicToast'];
        function SignalRFactory($rootScope, Hub, ionicToast) {
            var signalRLocal = this;

            var serverURL = 'https://serivcerURL.com/signalr';

            //Hub setup
            var hub = new Hub('CommunicationHub', {
                rootPath: serverURL,
                listeners: {
                    'send': function (data) {
                        console.log("send " + data);

                    }

                },

                errorHandler: function (error) {
                //Here i am getting that websocket closed error
                    console.error(error);

                }
            });

            signalRLocal.Connect = function (user) {
                console.log("SignalR Connecting as :" + user.UserName);
                hub.invoke('connect', user);
            };

            return signalRLocal;
        }
    })();
</code>```

I have hosted service on IIS. I search for the solution and find something like this link

I also try with above link solution by using "long Polling" as per below

```<code>Hub.connection.start({ transport: 'longPolling' });
</code>```

But i don't want to use "long Polling" at all.
So can someone help me to figure out this issue without use of 'long Polling'.
Can someone tell me what configuration i have to do at client side or at IIS level.

答:
I am trying same and my client is in vue.js. I have changed below in vue.config.js

```<code>module.exports = {
  devServer: {
    proxy: {
      '/hub': {
        target: 'https://localhost:5001',
        changeOrigin: false,
        secure: false,
        headers: {
          'x-forwarded-proto': 'http',
        },
      },
    },
  },
}
</code>```

Previously i am trying 'x-forwarded-proto': 'https', when I changed to http its work.
https://localhost:5001 is my .net endpoint and http://localhost:8080 is my vue enpoint

Changed in Startup.csbelow,

```<code>app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<CardsHub>("/hub/cardsHub");
            });
</code>```

Added below code in vue component

```<code>this.connection = new signalR.HubConnectionBuilder()
      .withUrl('/hub/cardsHub')
      .build()
</code>```

Body:
I am working on project of Ionic with angular and AspNet with SignalR that have chat module.
I use SignalR for Chat.It's working smoothly but some time i am getting error as per below screen shot and because of that it's get stop working at all.
I have hosted my service on IIS and creating proxy and communicating with client and server. Here is sample

    (function () {
        angular
          .module('app')
          .factory('SignalRFactory', SignalRFactory);
        SignalRFactory.$inject = ['$rootScope', 'Hub', 'ionicToast'];
        function SignalRFactory($rootScope, Hub, ionicToast) {
            var signalRLocal = this;

            var serverURL = 'https://serivcerURL.com/signalr';

            //Hub setup
            var hub = new Hub('CommunicationHub', {
                rootPath: serverURL,
                listeners: {
                    'send': function (data) {
                        console.log("send " + data);

                    }

                },

                errorHandler: function (error) {
                //Here i am getting that websocket closed error
                    console.error(error);

                }
            });

            signalRLocal.Connect = function (user) {
                console.log("SignalR Connecting as :" + user.UserName);
                hub.invoke('connect', user);
            };

            return signalRLocal;
        }
    })();

I have hosted service on IIS. I search for the solution and find something like this link

I also try with above link solution by using "long Polling" as per below

Hub.connection.start({ transport: 'longPolling' });

But i don't want to use "long Polling" at all.
So can someone help me to figure out this issue without use of 'long Polling'.
Can someone tell me what configuration i have to do at client side or at IIS level.

Body:
I am trying same and my client is in vue.js. I have changed below in vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/hub': {
        target: 'https://localhost:5001',
        changeOrigin: false,
        secure: false,
        headers: {
          'x-forwarded-proto': 'http',
        },
      },
    },
  },
}

Previously i am trying 'x-forwarded-proto': 'https', when I changed to http its work.
https://localhost:5001 is my .net endpoint and http://localhost:8080 is my vue enpoint

Changed in Startup.csbelow,

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<CardsHub>("/hub/cardsHub");
            });

Added below code in vue component

this.connection = new signalR.HubConnectionBuilder()
      .withUrl('/hub/cardsHub')
      .build()


问:
Cannot uninstall angular-cli
I've tried several times to uninstall my angular-cli in order to update it but even if I follow the instructions provided on github:

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

When I check using the command ng --version I still get the old version :

```<code> angular-cli: 1.0.0-beta.26

 node: 7.7.1
 os: darwin x64
</code>```

How can i fix this issue? Thanks

答:
Step 1:

```<code>npm uninstall -g angular-cli
</code>```

Step 2:

```<code>npm cache clean
</code>```

Step 3:

```<code>npm cache verify
</code>```

Step 4:

```<code>npm cache verify --force
</code>```

Note:
You can also delete by the following the paths

C:\Users"System_name"\AppData\Roaming\npm and

C:\Users"System_name"\AppData\Roaming\npm-cache

Then

Step 5:

```<code>npm install -g @angular/cli@latest
</code>```

Title: Cannot uninstall angular-cli

Body:
I've tried several times to uninstall my angular-cli in order to update it but even if I follow the instructions provided on github:

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

When I check using the command ng --version I still get the old version :

 angular-cli: 1.0.0-beta.26

 node: 7.7.1
 os: darwin x64

How can i fix this issue? Thanks

Body:
Step 1:

npm uninstall -g angular-cli

Step 2:

npm cache clean

Step 3:

npm cache verify

Step 4:

npm cache verify --force

Note:
You can also delete by the following the paths

C:\Users"System_name"\AppData\Roaming\npm and

C:\Users"System_name"\AppData\Roaming\npm-cache

Then

Step 5:

npm install -g @angular/cli@latest


问:
How to combine multiple dataframe values having set of common column values?
I have a dataframe df1 which consists of string values in ColA, These ColA values will have duplicates as shown.

Now my df2 will have same set of values in ColA, which are not repeated. So I want to append the ColD values of df2 to my original df1. (60 will repeat twice for app, 20 will repeat thrice..and so on..). Similarly I want to append ColE values of df3 to my df1

Can it be done by transposing ColA so it becomes column names and then can we append values to it,  or can the ColA be set as indexes and then we need to append values, or is there any other way?

```<code>import numpy as np
import pandas as pd
import io

data1='''
ColA,ColB,ColC
app,5,2
app,6,3
book,10,6
book,4,8
book,9,0
car,7,8
car,1,3
'''

data2='''
ColA,ColD
app,60
book,20
car,8
'''

data3='''
ColA,ColE
app,3
book,6
car,9
'''

df1=pd.read_csv(io.StringIO(data1))
df2=pd.read_csv(io.StringIO(data2))
df3=pd.read_csv(io.StringIO(data3))
</code>```

Expected output: df1

```<code>ColA ColB ColC ColD ColE
app     5    2   60    3
app     6    3   60    3
book   10    6   20    6
book    4    8   20    6
book    9    0   20    6
car     7    8    8    9
car     1    3    8    9
</code>```

答:
You can merge:

```<code>df1.merge(df2, on='ColA', how='left').merge(df3, on='ColA', how='left')
</code>```

Output:

```<code>   ColA  ColB  ColC  ColD  ColE
0   app     5     2    60     3
1   app     6     3    60     3
2  book    10     6    20     6
3  book     4     8    20     6
4  book     9     0    20     6
5   car     7     8     8     9
6   car     1     3     8     9
</code>```

Body:
I have a dataframe df1 which consists of string values in ColA, These ColA values will have duplicates as shown.

Now my df2 will have same set of values in ColA, which are not repeated. So I want to append the ColD values of df2 to my original df1. (60 will repeat twice for app, 20 will repeat thrice..and so on..). Similarly I want to append ColE values of df3 to my df1

Can it be done by transposing ColA so it becomes column names and then can we append values to it,  or can the ColA be set as indexes and then we need to append values, or is there any other way?

import numpy as np
import pandas as pd
import io

data1='''
ColA,ColB,ColC
app,5,2
app,6,3
book,10,6
book,4,8
book,9,0
car,7,8
car,1,3
'''

data2='''
ColA,ColD
app,60
book,20
car,8
'''

data3='''
ColA,ColE
app,3
book,6
car,9
'''

df1=pd.read_csv(io.StringIO(data1))
df2=pd.read_csv(io.StringIO(data2))
df3=pd.read_csv(io.StringIO(data3))

Expected output: df1

ColA ColB ColC ColD ColE
app     5    2   60    3
app     6    3   60    3
book   10    6   20    6
book    4    8   20    6
book    9    0   20    6
car     7    8    8    9
car     1    3    8    9

Body:
You can merge:

df1.merge(df2, on='ColA', how='left').merge(df3, on='ColA', how='left')

Output:

   ColA  ColB  ColC  ColD  ColE
0   app     5     2    60     3
1   app     6     3    60     3
2  book    10     6    20     6
3  book     4     8    20     6
4  book     9     0    20     6
5   car     7     8     8     9
6   car     1     3     8     9


问:
Bootstrap Carousel slideshow (fixed height but keep image center top)
I have the below code:

```<code>    <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
        <img src="assets/slideshowimage.jpg" class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="assets/slideshowimage.jpg" class="d-block w-100" alt="...">
    </div>

  </div>
</div>
</code>```

(image used is 1900 X 305 px)

The code works but I need to keep the image height the same when resized. At the moment when you re-size the screen the image height is lowered as the image is resized.

Ideally I need it to act like a background image (with 'cover' and 'center top') so the image height stays the same and the image simply gets cropped on the left and right as the browsers resized.

Using bootstrap 4.5

I tried setting the carousel-item with a background image but that didn't seem to work.

Can someone point me in the right direction please?

Thanks in advance for your help

答:
d-block w-100 makes the image be and therefor resize 100%. You will have to overwrite the css to make it happen.

Note that you should prefer to overwrite it in your own app.css file not in the bootstrap one.

See docu: https://getbootstrap.com/docs/4.0/utilities/sizing/

E.g.
app.css

```<code>.d-block w-100 {

    width: 10vw;

}
</code>```

Body:
I have the below code:

(image used is 1900 X 305 px)

The code works but I need to keep the image height the same when resized. At the moment when you re-size the screen the image height is lowered as the image is resized.

Ideally I need it to act like a background image (with 'cover' and 'center top') so the image height stays the same and the image simply gets cropped on the left and right as the browsers resized.

Using bootstrap 4.5

I tried setting the carousel-item with a background image but that didn't seem to work.

Can someone point me in the right direction please?

Thanks in advance for your help

Body:
d-block w-100 makes the image be and therefor resize 100%. You will have to overwrite the css to make it happen.

Note that you should prefer to overwrite it in your own app.css file not in the bootstrap one.

See docu: https://getbootstrap.com/docs/4.0/utilities/sizing/

E.g.
app.css

.d-block w-100 {

    width: 10vw;

}


问:
my service return anonymous type data in JSON format, how to use it in angular 9 application as a string[]
My service return data in JSON like

```<code>[
    {
        "txtUserRole": "FinAsst"
    },
    {
        "txtUserRole": "CSG"
    },
    {
        "txtUserRole": "PA"
    },
    {
        "txtUserRole": "ARTEAM"
    }
]
</code>```

now I want to add all this role in a string array.
so i wrote a code like

```<code>  ngOnInit(): void {
    this.generic.getUserRoles().toPromise().then(
      (jsonData) => {
        jsonData.forEach(element => {
          **// console.log(element['txtUserRole']);**
          this.roles.push(element['txtUserRole']);
        });
      }
    );
  }
</code>```

when i was logging with           console.log(element['txtUserRole']);

I am able to see that result as below in the console

```<code>FinAsst
CSG
PA
ARTEAM
</code>```

but when in HTML using interpolation nothing is displayed.

```<code> {{roles}}
</code>```

what is the reason and what code needs to be changes

答:
I presume getUserRoles() function returns an observable. In that case, you could use the array map method to extract the values.

Controller

ngOnInit(): void {
  this.generic.getUserRoles().subscribe(
    jsonData => {
      this.roles = jsonData.map(item => item.txtUserRole)
    }
  );
}
```

<p>And in the template either use <code>json</code> pipe or <code>*ngFor</code> directive to render the data.</p>

<pre class="lang-html prettyprint-override"><code><span> {{ roles | json }} </span>
</code>```

or

  {{ role }}

```

Body:
My service return data in JSON like

[
    {
        "txtUserRole": "FinAsst"
    },
    {
        "txtUserRole": "CSG"
    },
    {
        "txtUserRole": "PA"
    },
    {
        "txtUserRole": "ARTEAM"
    }
]

now I want to add all this role in a string array.
so i wrote a code like

  ngOnInit(): void {
    this.generic.getUserRoles().toPromise().then(
      (jsonData) => {
        jsonData.forEach(element => {
          **// console.log(element['txtUserRole']);**
          this.roles.push(element['txtUserRole']);
        });
      }
    );
  }

when i was logging with           console.log(element['txtUserRole']);

I am able to see that result as below in the console

FinAsst
CSG
PA
ARTEAM

but when in HTML using interpolation nothing is displayed.

 {{roles}}

what is the reason and what code needs to be changes

Body:
I presume getUserRoles() function returns an observable. In that case, you could use the array map method to extract the values.

Controller

ngOnInit(): void {
  this.generic.getUserRoles().subscribe(
    jsonData => {
      this.roles = jsonData.map(item => item.txtUserRole)
    }
  );
}

And in the template either use json pipe or *ngFor directive to render the data.

<span> {{ roles | json }} </span>

or

<span *ngFor="let role of roles">
  {{ role }}
</span>


问:
Call parent method inside super().__init__ when method is overriden by child
I have overriden a method in a child class.
This method is used in the parent class constructor.
When calling super().__init__ in the child class the child's method is executed instead of the parent's one inside the parent's constructor.

Example:

class A:
    def __init__(self):
        self.method()

    def method(self):
        print('parent method!')

class B(A):
    def __init__(self):
        super().__init__()

    def method(self):
        print('child method!')

b = B()

```

Output: child method!

While I want to get parent method!

Edit:

I need the parent's class constructor to use the not-overriden method, but after that each call to method() from the parent class should call overriden one.

答:
Because I need the parent's contructor to be called with the no-overriden method but then I need to use the overriden one each time.

This indicates you are asking one method to do too many things. Split method into two parts: one that is not overridden and called by A.__init__, and another that can be overriden. Something like

```<code>class A:
    def __init__(self):
        self._init_method()

    def _init_method(self):
        print('parent method!')

    def method(self):
        self._init_method()

class B(A):
    def __init__(self):
        super().__init__()

    def method(self):
        print('child method!')

b = B()
</code>```

_init_method does what you claim needs to be done from A.__init__. At the same time, you can have method do the same thing, unless you override it, in which case you'll do whatever it is you want B.method to do.

Body:
I have overriden a method in a child class.
This method is used in the parent class constructor.
When calling super().__init__ in the child class the child's method is executed instead of the parent's one inside the parent's constructor.

Example:

class A:
    def __init__(self):
        self.method()

    def method(self):
        print('parent method!')

class B(A):
    def __init__(self):
        super().__init__()

    def method(self):
        print('child method!')

b = B()

Output: child method!

While I want to get parent method!

Edit:

I need the parent's class constructor to use the not-overriden method, but after that each call to method() from the parent class should call overriden one.

Body:
Because I need the parent's contructor to be called with the no-overriden method but then I need to use the overriden one each time.

This indicates you are asking one method to do too many things. Split method into two parts: one that is not overridden and called by A.__init__, and another that can be overriden. Something like

class A:
    def __init__(self):
        self._init_method()

    def _init_method(self):
        print('parent method!')

    def method(self):
        self._init_method()

class B(A):
    def __init__(self):
        super().__init__()

    def method(self):
        print('child method!')

b = B()

_init_method does what you claim needs to be done from A.__init__. At the same time, you can have method do the same thing, unless you override it, in which case you'll do whatever it is you want B.method to do.


问:
Why is this for loop not logging sum?
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.</p>

```<code>tips = [1,2,3,4,5]
function sumTip (tips){
  for (i=0; i<tips.length; i++){
    var total = total + tips[i];
    console.log(total);
  }
}
sumTip();
</code>```

答:
Couple problems you're running into here. First, in your last line, when you call sumTip, you never pass it the array, like: sumTip(tips). Second, you are resetting total everytime you loop, it should be set up like:

```<code>var total = 0;

for (var i=0; i<tips.length; i++){
    total += tips[i];
    console.log(total);
  }
</code>```

This all could just be reduced though: let sum = tips.reduce((a, b) => a + b, 0)

Title: Why is this for loop not logging sum?

Body:
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.

tips = [1,2,3,4,5]
function sumTip (tips){
  for (i=0; i<tips.length; i++){
    var total = total + tips[i];
    console.log(total);
  }
}
sumTip();

Body:
Couple problems you're running into here. First, in your last line, when you call sumTip, you never pass it the array, like: sumTip(tips). Second, you are resetting total everytime you loop, it should be set up like:

var total = 0;

for (var i=0; i<tips.length; i++){
    total += tips[i];
    console.log(total);
  }

This all could just be reduced though: let sum = tips.reduce((a, b) => a + b, 0)


问:
WebConfig: use @bean or method way?
I know that i can write in webConfig class in this way:

```<code>@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    registry.viewResolver(viewResolver);
}
</code>```

But at the same time - i can write this in another way:

```<code> @Bean(name = "viewResolver")
public ViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}
</code>```

which way is better ?

And why i can't do first way for freemarker, but can do second:

it is correct:

```<code>@Bean(name = "viewResolver")
public ViewResolver getViewResolver() {
    FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
    viewResolver.setPrefix("");
    viewResolver.setSuffix(".ftl");
    return viewResolver;
}

@Bean(name = "freemarkerConfig")
public FreeMarkerConfigurer getFreemarkerConfig() {
    FreeMarkerConfigurer config = new FreeMarkerConfigurer();
    config.setTemplateLoaderPath("/WEB-INF/pages/");
    return config;
}
</code>```

Method way i can't write because i don't know how FreeMarkerConfigurer and FreeMarkerViewResolver interact...

答:
Basically your second usage is not how you should use the ViewResolverRegistry it has some methods to make life easier, like jsp or freeMarker which you should use.

So a proper use would be

```<code>Override
public void configureViewResolvers(ViewResolverRegistry registry) {
  registry.jsp("/WEB-INF/pages/", ".jsp");

}
</code>```

and for FreeMarker

```<code>public void configureViewResolvers(ViewResolverRegistry registry) {
  registry.freeMarker();

}

@Bean
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer config = new FreeMarkerConfigurer();
    config.setTemplateLoaderPath("/WEB-INF/pages/");
    return config;
}
</code>```

You still need the FreeMarkerConfigurer to bootstrap and configure FreeMarker.

Title: WebConfig: use @bean or method way?

Body:
I know that i can write in webConfig class in this way:

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    registry.viewResolver(viewResolver);
}

But at the same time - i can write this in another way:

 @Bean(name = "viewResolver")
public ViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

which way is better ?

And why i can't do first way for freemarker, but can do second:

it is correct:

@Bean(name = "viewResolver")
public ViewResolver getViewResolver() {
    FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
    viewResolver.setPrefix("");
    viewResolver.setSuffix(".ftl");
    return viewResolver;
}

@Bean(name = "freemarkerConfig")
public FreeMarkerConfigurer getFreemarkerConfig() {
    FreeMarkerConfigurer config = new FreeMarkerConfigurer();
    config.setTemplateLoaderPath("/WEB-INF/pages/");
    return config;
}

Method way i can't write because i don't know how FreeMarkerConfigurer and FreeMarkerViewResolver interact...

Body:
Basically your second usage is not how you should use the ViewResolverRegistry it has some methods to make life easier, like jsp or freeMarker which you should use.

So a proper use would be

Override
public void configureViewResolvers(ViewResolverRegistry registry) {
  registry.jsp("/WEB-INF/pages/", ".jsp");

}

and for FreeMarker

public void configureViewResolvers(ViewResolverRegistry registry) {
  registry.freeMarker();

}

@Bean
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer config = new FreeMarkerConfigurer();
    config.setTemplateLoaderPath("/WEB-INF/pages/");
    return config;
}

You still need the FreeMarkerConfigurer to bootstrap and configure FreeMarker.


问:
Using a for loop to create a new list
I have a list of strings and would like to use a for loop to change the strings and create a new list.

```<code>oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
</code>```

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

答:
You need to declare newList outside the for-loop. If you declare it inside the for-loop, then on each iteration of the for-loop you're reassigning the variable newList to be equal to an empty list, and hence you lose your data from the previous iterations (leaving you with only the data from the last iteration.

Here's your code with the declaration fixed:

```<code>oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
</code>```

and here's an even simplified version:

```<code>oldList = ['AAA','BBB','CCC']
newList = ['a_' + str + '_z' for str in oldList]
</code>```

Title: Using a for loop to create a new list

Body:
I have a list of strings and would like to use a for loop to change the strings and create a new list.

oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

Body:
You need to declare newList outside the for-loop. If you declare it inside the for-loop, then on each iteration of the for-loop you're reassigning the variable newList to be equal to an empty list, and hence you lose your data from the previous iterations (leaving you with only the data from the last iteration.

Here's your code with the declaration fixed:

oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)

and here's an even simplified version:

oldList = ['AAA','BBB','CCC']
newList = ['a_' + str + '_z' for str in oldList]


问:
Where in object file does the code of function "main" starts?
I have an object file of a C program which prints hello world, just for the question.
I am trying to understand using readelf utility or gdb or hexedit(I can't figure which tool is a correct one) where in the file does the code of function "main" starts.

I know using readelf that symbol _start & main occurs and the address where it is mapped in a virtual memory. Moreover, I also know what the size of .text section and the of coruse where entry point specified, i.e the address which the same of text section.

The question is - Where in the file does the code of function "main" starts? I tought that is the entry point and the offset of the text section but how I understand it the sections data, bss, rodata should be ran before main and it appears after section text in readelf.

Also I tought we should sum the size all the lines till main in symbol table, but I am not sure at all if it is correct.

Additional question which follow up this one is if I want to replace main function with NOP instrcutres or plant one ret instruction in my object file. how can I know the offset where I can do it using hexedit.

答:
_start normally belongs to a module ( a *.o file) that is fixed (it is called differently on different systems, but a common name is crt0.o which is written in assembler.)  That fixed code prepares the stack (normally  the arguments and the environment are stored in the initial stack segment by the execve(2) system call) the mission of crt0.s is to prepare the initial C stack frame and call main().  Once main() ends, it is responsible of getting the return value from main and calling all the atexit() handlers to finish calling the _exit(2) system call.

The linking of crt0.o is normally transparent due to the fact that you always call the compiler to do the linking itself, so you normally don't have to add crt0.o as the first object module, but the compiler knows (lately, all this stuff has grown considerably, since we depend on architecture and ABIs to pass parameters between functions)

If you execute the compiler with the -v option, you'll get the exact command line it uses to call the linker and you'll get the secrets of the final memory map your program has on its first stages.


问:
Android Layout problem
Hey, I tried to designed my layout to be like below picture, but I don't know how
so, could you guys help me to redesign it or give me some correction

looking forward to hearing from you guys , Thanks for advance

```<code><LinearLayout android:layout_width="fill_parent" android:layout_height="320dip">
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/pic"
    android:id="@+id/picture">
</ImageView>
</LinearLayout>

<TableLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:gravity="center"
    android:stretchColumns="*">
    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
            <SeekBar android:id="@+id/seekbar"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:progress="3"
            android:max="25"
            android:maxWidth="100px"
            android:paddingRight="25px">
            </SeekBar>

            <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:layout_weight="4"
            android:gravity="center"
            android:id="@+id/tx_color"
            android:text="None">
            </TextView>

 </TableRow>
    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">

        <RadioGroup android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/QueGroup1">
            <RadioButton android:checked="true"
            android:id="@+id/simple_mode" android:text="Default"/>
            <RadioButton android:checked="false"
            android:id="@+id/warn_mode" android:text="Warning"/>
            <RadioButton android:checked="false"
            android:id="@+id/grey_mode" android:text="Grey Scale"/>

            </RadioGroup>
    </TableRow>
</TableLayout>
</code>```

|
|
|                   ImageView
|
|
|

|
|______________________
|    Spinner                   | TextView
|
|_______________________
|  3 of radio buttons
|_____________________
 sorry about this b/c I cant post an image T^T

答:
It really depends what you want it to look like (the ascii graphics didn't help much there :) )

For one thing, your layout should have a single topmost container.. so you can do something like this (meta layout):

```<code><LinearLayout android:orientation="vertical">
  <ImageView />
  <TableLayout>
    <TableRow>
      <SeekBar /> <!-- row 1 col 1 -->
      <TextView /> <!-- row 1 col 2 -->
    </TableRow>
    <TableRow>
      <TextView /> <!-- row 2 col 1, if you need an empty column, just leave the text empty -->
      <RadioGroup /> <!-- row 2 col 2 -->
    </TableRow>
  </TableLayout>
</LinearLayout>
</code>```

Is that something like what you need?

It will generate something like this:

UPD: You said that you wanted the radio group to be a single wide column.. In this case you just put it outside the table, same as the ImageView

If this example is your whole layout (i.e. you don't have any other rows with seekBar/textViews, then you can remove the TableLayout completely:

```<code><LinearLayout android:orientation="vertical">
  <ImageView />
  <LinearLayout android:orientation="horizontal">
    <SeekBar />
    <TextView />
  </LinearLayout>
  <RadioGroup />
</LinearLayout>
</code>```

Title: Android Layout problem

Body:
Hey, I tried to designed my layout to be like below picture, but I don't know how
so, could you guys help me to redesign it or give me some correction

looking forward to hearing from you guys , Thanks for advance

<LinearLayout android:layout_width="fill_parent" android:layout_height="320dip">
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/pic"
    android:id="@+id/picture">
</ImageView>
</LinearLayout>

<TableLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:gravity="center"
    android:stretchColumns="*">
    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
            <SeekBar android:id="@+id/seekbar"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:progress="3"
            android:max="25"
            android:maxWidth="100px"
            android:paddingRight="25px">
            </SeekBar>

            <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:layout_weight="4"
            android:gravity="center"
            android:id="@+id/tx_color"
            android:text="None">
            </TextView>

 </TableRow>
    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">

        <RadioGroup android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/QueGroup1">
            <RadioButton android:checked="true"
            android:id="@+id/simple_mode" android:text="Default"/>
            <RadioButton android:checked="false"
            android:id="@+id/warn_mode" android:text="Warning"/>
            <RadioButton android:checked="false"
            android:id="@+id/grey_mode" android:text="Grey Scale"/>

            </RadioGroup>
    </TableRow>
</TableLayout>

|
|
|                   ImageView
|
|
|

|
|______________________
|    Spinner                   | TextView
|
|_______________________
|  3 of radio buttons
|_____________________
 sorry about this b/c I cant post an image T^T

Body:
It really depends what you want it to look like (the ascii graphics didn't help much there :) )

For one thing, your layout should have a single topmost container.. so you can do something like this (meta layout):

<LinearLayout android:orientation="vertical">
  <ImageView />
  <TableLayout>
    <TableRow>
      <SeekBar /> <!-- row 1 col 1 -->
      <TextView /> <!-- row 1 col 2 -->
    </TableRow>
    <TableRow>
      <TextView /> <!-- row 2 col 1, if you need an empty column, just leave the text empty -->
      <RadioGroup /> <!-- row 2 col 2 -->
    </TableRow>
  </TableLayout>
</LinearLayout>

Is that something like what you need?

It will generate something like this:

UPD: You said that you wanted the radio group to be a single wide column.. In this case you just put it outside the table, same as the ImageView

If this example is your whole layout (i.e. you don't have any other rows with seekBar/textViews, then you can remove the TableLayout completely:

<LinearLayout android:orientation="vertical">
  <ImageView />
  <LinearLayout android:orientation="horizontal">
    <SeekBar />
    <TextView />
  </LinearLayout>
  <RadioGroup />
</LinearLayout>


答:
You need to initialize the newList outside the for loop otherwise it will get initialized at every iteration.
This code snippet might help.

```<code>oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
   add1 = 'a_'
   add2 = '_z'

   newStr = add1 + oldList[i] + add2

   newList.append(newStr)
print(newList)
</code>```

Title: Using a for loop to create a new list

Body:
You need to initialize the newList outside the for loop otherwise it will get initialized at every iteration.
This code snippet might help.

oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
   add1 = 'a_'
   add2 = '_z'

   newStr = add1 + oldList[i] + add2

   newList.append(newStr)
print(newList)


问:
Firebase deploy error. Server Error. Client network socket disconnected before secure TLS connection was established
I'm trying to deploy a firebase function from my terminal using this comment firebase deploy
But getting this error. Cant understand why its happening.

```<code>deploying functions
functions: ensuring required API cloudfunctions.googleapis.com is enabled...
functions: required API cloudfunctions.googleapis.com is enabled
functions: preparing functions directory for uploading...
functions: packaged functions (27.96 KB) for uploading
functions: Upload Error: Server Error. Client network socket disconnected before secure TLS connection was established

Error: Server Error. Client network socket disconnected before secure TLS connection was established
</code>```

答:
I had the same error for quite a while and still happened sometimes.
For a rescue, I use a VPN. It is a network issue. Could be happened because of the ISP or may be a country wise block of Google Cloud Storage AP</p>

Body:
I'm trying to deploy a firebase function from my terminal using this comment firebase deploy
But getting this error. Cant understand why its happening.

deploying functions
functions: ensuring required API cloudfunctions.googleapis.com is enabled...
functions: required API cloudfunctions.googleapis.com is enabled
functions: preparing functions directory for uploading...
functions: packaged functions (27.96 KB) for uploading
functions: Upload Error: Server Error. Client network socket disconnected before secure TLS connection was established

Error: Server Error. Client network socket disconnected before secure TLS connection was established


问:
Disable DML execution from GCP console
Is there way to enable/disable DML execution for google cloud spanner through GCP console. With service admin access, people can execute INSERT or DELTE statements. Want to disable it except READ access with SELECT mostly in production.

答:
https://cloud.google.com/spanner/docs/iam#roles

As documented, this predefined IAM role "roles/spanner.databaseReader" grants the users read-only access to a database.

Title: Disable DML execution from GCP console


问:
Explicit specialization in non-namespace scope
```<code>template<typename T>
class CConstraint
{
public:
    CConstraint()
    {
    }

    virtual ~CConstraint()
    {
    }

    template <typename TL>
    void Verify(int position, int constraints[])
    {
    }

    template <>
    void Verify<int>(int, int[])
    {
    }
};
</code>```

Compiling this under g++ gives the following error:

Explicit specialization in non-namespace scope 'class CConstraint'

In VC, it compiles fine. Can anyone please let me know the workaround?

答:
Even better: you can combine partial specialisation with default template arguments. This way modification to the VC++ code are minor, because calls to the specialised function do not need to be modified.</p>

```<code>template <typename TL, class Dummy=int>
void Verify(int position, int constraints[])
{
}

template <class Dummy=int>
void Verify<int, Dummy>(int, int[])
{
}
</code>```

Body:
template<typename T>
class CConstraint
{
public:
    CConstraint()
    {
    }

    virtual ~CConstraint()
    {
    }

    template <typename TL>
    void Verify(int position, int constraints[])
    {
    }

    template <>
    void Verify<int>(int, int[])
    {
    }
};

Compiling this under g++ gives the following error:

Explicit specialization in non-namespace scope 'class CConstraint'

In VC, it compiles fine. Can anyone please let me know the workaround?

Body:
Even better: you can combine partial specialisation with default template arguments. This way modification to the VC++ code are minor, because calls to the specialised function do not need to be modified.

template <typename TL, class Dummy=int>
void Verify(int position, int constraints[])
{
}

template <class Dummy=int>
void Verify<int, Dummy>(int, int[])
{
}


问:
Dismiss SVProgressHUD with Tap Gesture
I need to add a UITapGestureRecognizer to the SVProgressHUD. The SVProgressHUD already has the ability to dismiss using -(void) dismiss;. The code for this will dismiss the animation based on seconds.

```<code>- (void)dismiss {
for (UIGestureRecognizer *gesture in [[[self class] sharedView] gestureRecognizers]) {
    [[[self class] sharedView] removeGestureRecognizer:gesture];
}

NSDictionary *userInfo = [self notificationUserInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification
                                                    object:nil
                                                  userInfo:userInfo];

self.activityCount = 0;
[UIView animateWithDuration:0.15
                      delay:0
                    options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8, 0.8);
                     if(self.isClear) // handle iOS 7 UIToolbar not answer well to hierarchy opacity change
                         self.hudView.alpha = 0;
                     else
                         self.alpha = 0;
                 }
                 completion:^(BOOL finished){
                     if(self.alpha == 0 || self.hudView.alpha == 0) {
                         self.alpha = 0;
                         self.hudView.alpha = 0;

                         [[NSNotificationCenter defaultCenter] removeObserver:self];
                         [self cancelRingLayerAnimation];
                         [self addTapGestureToDismiss];
                         [_hudView removeFromSuperview];
                         _hudView = nil;

                         [_overlayView removeFromSuperview];
                         _overlayView = nil;

                         [_indefiniteAnimatedView removeFromSuperview];
                         _indefiniteAnimatedView = nil;

                         UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                         [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification
                                                                             object:nil
                                                                           userInfo:userInfo];

                         // Tell the rootViewController to update the StatusBar appearance
                         UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;
                         if ([rootController respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
                             [rootController setNeedsStatusBarAppearanceUpdate];
                         }
                         // uncomment to make sure UIWindow is gone from app.windows
                         //NSLog(@"%@", [UIApplication sharedApplication].windows);
                         //NSLog(@"keyWindow = %@", [UIApplication sharedApplication].keyWindow);
                     }
                 }];
</code>```

}

My thought process is to add the tapGesture code to the dismiss method. This is what I have written so far.

```<code>- (void)addTapGestureToDismiss {

// Creation and initializer of the tap gesture
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(dismiss)];

// Specify that the gesture must be a single tap
tapRecognizer.numberOfTapsRequired = 1;

// Add the tap gesture recognizer to the view
[[[self class] sharedView] addGestureRecognizer:tapRecognizer];
</code>```

}

As you can see I'm just initializing the tapGesture. I've run into the issue of placing it in a few places and causing the app to only have one single tap. I've pretty much confused myself in the process. Should I

add this gesture to the view?

add this gesture to dismiss?

答:
An easy way to implement this is by:

creating a class that dismisses the HUD:

class HUDManager {
    @objc
    class func dismissHUD() {
        SVProgressHUD.dismiss()
    }
}
```

<ol start="2">
<li>Subscribing to the <code>SVProgressHUDDidReceiveTouchEvent</code> notification:</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>NotificationCenter.default.addObserver(HUDManager.self,
                                       selector: #selector(HUDManager.dismissHUD),
                                       name: .SVProgressHUDDidReceiveTouchEvent,
                                       object: nil)
</code>```

Title: Dismiss SVProgressHUD with Tap Gesture

Body:
I need to add a UITapGestureRecognizer to the SVProgressHUD. The SVProgressHUD already has the ability to dismiss using -(void) dismiss;. The code for this will dismiss the animation based on seconds.

- (void)dismiss {
for (UIGestureRecognizer *gesture in [[[self class] sharedView] gestureRecognizers]) {
    [[[self class] sharedView] removeGestureRecognizer:gesture];
}

NSDictionary *userInfo = [self notificationUserInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification
                                                    object:nil
                                                  userInfo:userInfo];

self.activityCount = 0;
[UIView animateWithDuration:0.15
                      delay:0
                    options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8, 0.8);
                     if(self.isClear) // handle iOS 7 UIToolbar not answer well to hierarchy opacity change
                         self.hudView.alpha = 0;
                     else
                         self.alpha = 0;
                 }
                 completion:^(BOOL finished){
                     if(self.alpha == 0 || self.hudView.alpha == 0) {
                         self.alpha = 0;
                         self.hudView.alpha = 0;

                         [[NSNotificationCenter defaultCenter] removeObserver:self];
                         [self cancelRingLayerAnimation];
                         [self addTapGestureToDismiss];
                         [_hudView removeFromSuperview];
                         _hudView = nil;

                         [_overlayView removeFromSuperview];
                         _overlayView = nil;

                         [_indefiniteAnimatedView removeFromSuperview];
                         _indefiniteAnimatedView = nil;

                         UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                         [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification
                                                                             object:nil
                                                                           userInfo:userInfo];

                         // Tell the rootViewController to update the StatusBar appearance
                         UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;
                         if ([rootController respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
                             [rootController setNeedsStatusBarAppearanceUpdate];
                         }
                         // uncomment to make sure UIWindow is gone from app.windows
                         //NSLog(@"%@", [UIApplication sharedApplication].windows);
                         //NSLog(@"keyWindow = %@", [UIApplication sharedApplication].keyWindow);
                     }
                 }];

}

My thought process is to add the tapGesture code to the dismiss method. This is what I have written so far.

- (void)addTapGestureToDismiss {

// Creation and initializer of the tap gesture
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(dismiss)];

// Specify that the gesture must be a single tap
tapRecognizer.numberOfTapsRequired = 1;

// Add the tap gesture recognizer to the view
[[[self class] sharedView] addGestureRecognizer:tapRecognizer];

}

As you can see I'm just initializing the tapGesture. I've run into the issue of placing it in a few places and causing the app to only have one single tap. I've pretty much confused myself in the process. Should I

add this gesture to the view?

add this gesture to dismiss?

Body:
An easy way to implement this is by:

creating a class that dismisses the HUD:

class HUDManager {
    @objc
    class func dismissHUD() {
        SVProgressHUD.dismiss()
    }
}

Subscribing to the SVProgressHUDDidReceiveTouchEvent notification:

NotificationCenter.default.addObserver(HUDManager.self,
                                       selector: #selector(HUDManager.dismissHUD),
                                       name: .SVProgressHUDDidReceiveTouchEvent,
                                       object: nil)


问:
Can't run bash file inside ZSH
I've placed a bash file inside .zshrc and tried all different ways to run it every time I open a new terminal window or source .zshrc but no luck.

FYI: it was working fine on .bashrc

here is .zshrc script:

```<code>#Check if ampps is running
bash ~/ampps_runner.sh & disown
</code>```

Different approach:

```<code>#Check if ampps is running
sh ~/ampps_runner.sh & disown
</code>```

Another approach:

```<code>#Check if ampps is running
% ~/ampps_runner.sh & disown
</code>```

All the above approaches didn't work (meaning it supposes to run an app named ampps but it doesn't in zsh.

Note: It was working fine before switching to zsh from bash. so it does not have permission or syntax problems.

Update: content of ampps_runner.sh

```<code>#! /usr/bin/env

echo "########################"
echo "Checking for ampps server to be running:"

check=$(pgrep -f "/usr/local/ampps" )

#[  -z "$check" ] && echo "Empty: Yes" || echo "Empty: No"

if [ -z "$check" ]; then
    echo "It's not running!"
    cd /usr/local/ampps
    echo password | sudo -S ./Ampps
else
    echo "It's running ..."
fi
</code>```

答:
The easiest way to run bash temporarily from a zsh terminal is to

```<code>exec bash
</code>```

or just

```<code>bash
</code>```

Then you can run commands you previously could only run in bash. An example

```<code>help exec
</code>```

To exit

```<code>exit
</code>```

Now you are back in your original shell

If you want to know your default shell

```<code>echo $SHELL
</code>```

or

```<code>set | grep SHELL=
</code>```

If you want to reliably know your current shell

```<code>ps -p $$
</code>```

Or if you want just the shell name you might use

```<code>ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-'
</code>```

And you might just put that last one in a function for later, just know that it is only available if it was sourced in a current shell.

```<code>whichShell(){
   local defaultShell=$(echo $SHELL | tr -d '/bin/')
   echo "Default: $defaultShell"

   local currentShell=$(ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-')
   echo "Current: $currentShell"
}
</code>```

Call the method to see your results

```<code>whichShell
</code>```

Title: Can't run bash file inside ZSH

Body:
I've placed a bash file inside .zshrc and tried all different ways to run it every time I open a new terminal window or source .zshrc but no luck.

FYI: it was working fine on .bashrc

here is .zshrc script:

#Check if ampps is running
bash ~/ampps_runner.sh & disown

Different approach:

#Check if ampps is running
sh ~/ampps_runner.sh & disown

Another approach:

#Check if ampps is running
% ~/ampps_runner.sh & disown

All the above approaches didn't work (meaning it supposes to run an app named ampps but it doesn't in zsh.

Note: It was working fine before switching to zsh from bash. so it does not have permission or syntax problems.

Update: content of ampps_runner.sh

#! /usr/bin/env

echo "########################"
echo "Checking for ampps server to be running:"

check=$(pgrep -f "/usr/local/ampps" )

#[  -z "$check" ] && echo "Empty: Yes" || echo "Empty: No"

if [ -z "$check" ]; then
    echo "It's not running!"
    cd /usr/local/ampps
    echo password | sudo -S ./Ampps
else
    echo "It's running ..."
fi

Body:
The easiest way to run bash temporarily from a zsh terminal is to

exec bash

or just

bash

Then you can run commands you previously could only run in bash. An example

help exec

To exit

exit

Now you are back in your original shell

If you want to know your default shell

echo $SHELL

or

set | grep SHELL=

If you want to reliably know your current shell

ps -p $$

Or if you want just the shell name you might use

ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-'

And you might just put that last one in a function for later, just know that it is only available if it was sourced in a current shell.

whichShell(){
   local defaultShell=$(echo $SHELL | tr -d '/bin/')
   echo "Default: $defaultShell"

   local currentShell=$(ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-')
   echo "Current: $currentShell"
}

Call the method to see your results

whichShell


问:
HTML Resize content of iFrame
I'm currently using the prebuildt email form of sendgrid as an iFrame.

Everything is working as expected. The only problem I have is that on mobile devices the content of the iFrame is too big to get shown on the screen as you can see on the image:

So I tried to resize the content with the scale: 0.5, but it just make the whole iFrame smaller.

My current CSS-Code is the following:

```<code> .bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}
</code>```

and my HTML is this:

```<code><div class="bg-modal">
<div class="modal-contents">
    <iframe scrolling="no" class="iframeClass" frameborder="0" src="https://..."></iframe>
</div>
</div>
</code>```

I don't want to show the scrollbars.

Does someone know a solution for this repsonsive problem?

答:
You set width and height to 600px of the model-content and also 100% height and width of the iframe.So irespective of screen size iframe always 600px*600px.
You can fix it by set width to max-width and add some padding and mergin according to your design.
Or you can user vw for width and vh for height in model-content .

.modal-contents {
    height: 600px;
    max-width: 600px;
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;

}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}```

Title: HTML Resize content of iFrame

Body:
I'm currently using the prebuildt email form of sendgrid as an iFrame.

Everything is working as expected. The only problem I have is that on mobile devices the content of the iFrame is too big to get shown on the screen as you can see on the image:

So I tried to resize the content with the scale: 0.5, but it just make the whole iFrame smaller.

My current CSS-Code is the following:

 .bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}

and my HTML is this:

I don't want to show the scrollbars.

Does someone know a solution for this repsonsive problem?


问:
Extract row value where the 2 columns are not equal in a data frame in R
Is there a way to extract values in the dataframe when the columns values are not equal

```<code>df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf
</code>```

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

```<code>Row values
2, 4
</code>```

```<code>Cel_value_ColC  # Corresponding values
fsd, dsf
</code>```

答:
Here's an alternative approach that does not require any subtraction:</p>

```<code>row.values <- which(df$ColA != df$Colb)
row.values
#[1] 2 4

Cel_value_ColC <- df[df$ColA != df$Colb,"ColC"]
Cel_value_ColC
#[1] fsd dsf
</code>```

Body:
Is there a way to extract values in the dataframe when the columns values are not equal

df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

Row values
2, 4

Cel_value_ColC  # Corresponding values
fsd, dsf

Body:
Here's an alternative approach that does not require any subtraction:

row.values <- which(df$ColA != df$Colb)
row.values
#[1] 2 4

Cel_value_ColC <- df[df$ColA != df$Colb,"ColC"]
Cel_value_ColC
#[1] fsd dsf


问:
To check access for 1hr
I want to know how to grant access for 1hr to the guest users. I have tried it's not working</p>

```<code>Guest.findOne({ email: email})
        .then(user => {
            if(user){
                //Users exist
                if( Guest.createdAt + (0*1*60*60) < Date.now){

                res.render('Guestlogin');}
                // res.render('Guestboard');
                else{
                    res.render('Guestboard');
                }
        }else {
        const newUser = new Guest({
        email,
        name
         });
         newUser.save();
         return res.redirect('/Guestboard');
        }
</code>```

答:
OK so the user in the first then has your actual data. The createdAt is an ISO String hence we add the + to convert it into milliseconds and then add 1hr to it. If it is greater than Date.now() then more than 1hr has passed.

The last save function has been modified. You should ideally wait for the results of the save function to confirm your guest has actually been saved before return res object.

While the code is fine, you should check out async/ await as a superior alternative to using Promises.

```<code>Guest.findOne({
    email: email
  })
  .then(user => {
    if (user) {
      //Users existh
      if (+user.createdAt + (1000 * 60 * 60) < Date.now()) {
        // It has been over 1hr
        res.render('Guestlogin');
      } else {
        res.render('Guestboard');
      }
    } else {
      const newUser = new Guest({
        email,
        name
      });
      return newUser.save();
    }
  })
  .then(result =>  {
     return res.redirect('/Guestboard');
  }
</code>```

Title: To check access for 1hr

Body:
I want to know how to grant access for 1hr to the guest users. I have tried it's not working

Guest.findOne({ email: email})
        .then(user => {
            if(user){
                //Users exist
                if( Guest.createdAt + (0*1*60*60) < Date.now){

                res.render('Guestlogin');}
                // res.render('Guestboard');
                else{
                    res.render('Guestboard');
                }
        }else {
        const newUser = new Guest({
        email,
        name
         });
         newUser.save();
         return res.redirect('/Guestboard');
        }

Body:
OK so the user in the first then has your actual data. The createdAt is an ISO String hence we add the + to convert it into milliseconds and then add 1hr to it. If it is greater than Date.now() then more than 1hr has passed.

The last save function has been modified. You should ideally wait for the results of the save function to confirm your guest has actually been saved before return res object.

While the code is fine, you should check out async/ await as a superior alternative to using Promises.

Guest.findOne({
    email: email
  })
  .then(user => {
    if (user) {
      //Users existh
      if (+user.createdAt + (1000 * 60 * 60) < Date.now()) {
        // It has been over 1hr
        res.render('Guestlogin');
      } else {
        res.render('Guestboard');
      }
    } else {
      const newUser = new Guest({
        email,
        name
      });
      return newUser.save();
    }
  })
  .then(result =>  {
     return res.redirect('/Guestboard');
  }