问:
SwiftUI - Struct Binding doesn't update UI as expected
I have a SwiftUI question which doesn't look like it's answered or a duplicate of another issue, and SwiftUI is rather new.

The following code, with my understanding, show toggle the background of the Button control. The number of likes increments as expected, but the state changes don't seem to pass through to the Book struct.

Everything I have read is that in the preview, you need to use:
.constant(x) within the view of the PreviewProvider.

However, it doesn't work and the Button with likes does not the foreground, nor the background color.

When debugging the app, the result of the book isLiked does change. But the foreground/background colors do not.

Here is the code for the view.

```<code>import SwiftUI

struct BookDetailView: View {

  @Binding var book: Book
    @State var likes: Int = 0
  var body: some View {
    VStack {

      Text(book.title)
      Image(book.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .scaledToFit()

        Button(action: {
            self.book.isLiked.toggle()
            self.likes = self.likes + 1
        }) {
            Text(" Like \(likes)")
                .padding()
                .foregroundColor(self.book.isLiked ? .secondary : .primary)
                .background(self.book.isLiked ? Color.rayWenderlichGreen : Color.white)
                .cornerRadius(10)
        }
    }
  }
}

struct BookDetailView_Previews: PreviewProvider {

  static var previews: some View {
    BookDetailView(book: .constant(Book.demoBooks.randomElement()!))
  }
}
</code>```

Here is the actual book model

```<code>import SwiftUI

struct Book: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var isLiked = false
}

extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    return lhs.id == rhs.id
  }
}
</code>```

I have invested some time in trying to understand why this is happening, and it seems like it could just be a bug with SwiftUI.

Any thoughts or suggestions?

答:
Your code seems OK and your understanding, usage and implementation of the State concept appears to be good.

A weird thing is that this happens to me as well. Sometimes, State var just won't reload the view, and I believe it's because SwiftUI is unstable. I have a few ways to "fix" it.

I create a @State private var toggleMe: Bool! = false and call toggleMe.toggle() to toggle it whenever I need a state change. This sometimes updates the UI

I stop using States and create a custom OberveableObject like in this tutorial, because then I can manually signal when the state will change by calling objectWillChange.send() and it seems to work better then changing a State var, for some reason

None of these suggestions are good practice for your case. They are just a way of dealing with some stability issues SwiftUI has shown because it is new

Body:
I have a SwiftUI question which doesn't look like it's answered or a duplicate of another issue, and SwiftUI is rather new.

The following code, with my understanding, show toggle the background of the Button control. The number of likes increments as expected, but the state changes don't seem to pass through to the Book struct.

Everything I have read is that in the preview, you need to use:
.constant(x) within the view of the PreviewProvider.

However, it doesn't work and the Button with likes does not the foreground, nor the background color.

When debugging the app, the result of the book isLiked does change. But the foreground/background colors do not.

Here is the code for the view.

import SwiftUI

struct BookDetailView: View {

  @Binding var book: Book
    @State var likes: Int = 0
  var body: some View {
    VStack {

      Text(book.title)
      Image(book.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .scaledToFit()

        Button(action: {
            self.book.isLiked.toggle()
            self.likes = self.likes + 1
        }) {
            Text(" Like \(likes)")
                .padding()
                .foregroundColor(self.book.isLiked ? .secondary : .primary)
                .background(self.book.isLiked ? Color.rayWenderlichGreen : Color.white)
                .cornerRadius(10)
        }
    }
  }
}

struct BookDetailView_Previews: PreviewProvider {

  static var previews: some View {
    BookDetailView(book: .constant(Book.demoBooks.randomElement()!))
  }
}

Here is the actual book model

import SwiftUI

struct Book: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var isLiked = false
}

extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    return lhs.id == rhs.id
  }
}

I have invested some time in trying to understand why this is happening, and it seems like it could just be a bug with SwiftUI.

Any thoughts or suggestions?


来源: stackexchange

问:
React+JavaScript: How to erase data fields after a successful 200 code from sign up page and redirect to login?
Please find my code below for the SignUp react function, once I receive response of 200 after clicking the Sign up button, I want to erase the text in all three fields and redirect the user back to login page. Very new to web development, any help is appreciated!  There are three fields needed to sign up: firstName, email and password.</p>

```<code> export default function SignUp() {
      const [firstName, setFirstName] = React.useState("");
      const [email, setEmail] = React.useState("");
      const [password, setPassword] = React.useState("");

  let sign = async (event) => {
    event.preventDefault();
    await ApiService.createUser(
      firstName,
      email,
      password
    )
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => console.log(error));
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
                onChange={(event) => setFirstName(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
                onChange={(event) => setEmail(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
                onChange={(event) => setPassword(event.target.value)}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={sign}
          >
            Sign Up
          </Button>
</code>```

答:
First you need to be controlling the values on those elements.  I'm going to assume that TextField has a property called value (otherwise you'll need to find whatever the property should be called).  Something like this:

```<code><TextField
    value={firstName}   // <-- here
    autoComplete="fname"
    name="firstName"
    variant="outlined"
    required
    fullWidth
    id="firstName"
    label="First Name"
    autoFocus
    onChange={(event) => setFirstName(event.target.value)}
  />
</code>```

Do this with all of your input fields.  That way React will update those fields with the current state any time that changes.  Then you just need to update state after creating the user:

```<code>.then((response) => {
    console.log(response.data);
    setFirstName("");
    setEmail("");
    setPassword("");
})
</code>```

Basically, don't think of it as "updating the fields", but rather separate the management of state from the display of state.  Use the state to drive the display, and update the state as needed.

ContentLicense: CC BY-SA 4.0

Body:
Please find my code below for the SignUp react function, once I receive response of 200 after clicking the Sign up button, I want to erase the text in all three fields and redirect the user back to login page. Very new to web development, any help is appreciated!  There are three fields needed to sign up: firstName, email and password.

 export default function SignUp() {
      const [firstName, setFirstName] = React.useState("");
      const [email, setEmail] = React.useState("");
      const [password, setPassword] = React.useState("");

  let sign = async (event) => {
    event.preventDefault();
    await ApiService.createUser(
      firstName,
      email,
      password
    )
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => console.log(error));
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />

        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
                onChange={(event) => setFirstName(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
                onChange={(event) => setEmail(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
                onChange={(event) => setPassword(event.target.value)}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={sign}
          >
            Sign Up
          </Button>

Body:
First you need to be controlling the values on those elements.  I'm going to assume that TextField has a property called value (otherwise you'll need to find whatever the property should be called).  Something like this:

<TextField
    value={firstName}   // <-- here
    autoComplete="fname"
    name="firstName"
    variant="outlined"
    required
    fullWidth
    id="firstName"
    label="First Name"
    autoFocus
    onChange={(event) => setFirstName(event.target.value)}
  />

Do this with all of your input fields.  That way React will update those fields with the current state any time that changes.  Then you just need to update state after creating the user:

.then((response) => {
    console.log(response.data);
    setFirstName("");
    setEmail("");
    setPassword("");
})

Basically, don't think of it as "updating the fields", but rather separate the management of state from the display of state.  Use the state to drive the display, and update the state as needed.


问:
Automating GMAIL login using Python-Selenium
I am trying to automate logging into GMail using Selenium package of Python. However, I am not able to accomplish the task and get the following error:

```<code>Traceback (most recent call last):
  File "C:\Users\Surojit\Desktop\Python\automaticpasswordFiller.py", line   21, in <module>
    passwordElem = browser.find_element_by_id('Passwd')
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 266, in  find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 744, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site-  packages\selenium\webdriver\remote\webdriver.py", line 233, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate  element: {"method":"id","selector":"Passwd"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo glecode.com/components/driver-component.js:10770)
     at FirefoxDriver.prototype.findElement   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo  glecode.com/components/driver-component.js:10779)
    at DelayedCommand.prototype.executeInternal_/h   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo    glecode.com/components/command-processor.js:12661)
    at DelayedCommand.prototype.executeInternal_    (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo glecode.com/components/command-processor.js:12666)
    at DelayedCommand.prototype.execute/<   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)
</code>```

The simple code that I have written is:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time

browser = webdriver.Firefox()
browser.get('http://gmail.com')
action = webdriver.ActionChains(browser)
emailElem = browser.find_element_by_id('Email')
emailElem.send_keys("MyUserName")
browser.find_element_by_name('signIn').click()
#browser.get('https://accounts.google.com/ServiceLogin?         service=mail&continue=https://mail.google.com/mail/#password')
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys("MyPassword")
browser.find_element_by_name('signIn').click()
</code>```

Also, I have tried to find out the error in my code by comparing it to an answer given to a similar question here at: Auto connect on my Gmail account with Python Selenium

Can someone please guide me on the right path and let me know where I am making a mistake?

P.S: This is my first post on stackoverflow. Please excuse me for any mistake that I have made in posting the question

答:
In 2020 signing in with Gmail is much more tougher because Gmail takes selenium operated window as a bot window and will give a message like this one.img of error

But now I have found a successful way to log in without any error or warning by google.

you can log in to another website as google will accept it as secure login using another website like StackOverflow or some other website with Gmail login.

```<code>def gmail_sign_in(email, password):
    driver = webdriver.Chrome()

    driver.get('https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent')

    driver.find_element_by_xpath('//*[@id="openid-buttons"]/button[1]').click()

    driver.find_element_by_xpath('//*[@id="identifierId"]').send_keys(email)

    input = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="identifierNext"]/span/span'))
    )
    input.click()

    driver.implicitly_wait(1)

    driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password)

    input = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="passwordNext"]/span/span'))
    )
    input.click()
    driver.implicitly_wait(1)
    driver.get('https://www.google.com/')
</code>```

hope the code is understandable just this function and put your email and password make sure you have the appropriate imports.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to automate logging into GMail using Selenium package of Python. However, I am not able to accomplish the task and get the following error:

Traceback (most recent call last):
  File "C:\Users\Surojit\Desktop\Python\automaticpasswordFiller.py", line   21, in <module>
    passwordElem = browser.find_element_by_id('Passwd')
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 266, in  find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 744, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site-  packages\selenium\webdriver\remote\webdriver.py", line 233, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Surojit\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate  element: {"method":"id","selector":"Passwd"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo glecode.com/components/driver-component.js:10770)
     at FirefoxDriver.prototype.findElement   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo  glecode.com/components/driver-component.js:10779)
    at DelayedCommand.prototype.executeInternal_/h   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo    glecode.com/components/command-processor.js:12661)
    at DelayedCommand.prototype.executeInternal_    (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@goo glecode.com/components/command-processor.js:12666)
    at DelayedCommand.prototype.execute/<   (file:///C:/Users/Surojit/AppData/Local/Temp/tmpceecsm46/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)

The simple code that I have written is:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time

browser = webdriver.Firefox()
browser.get('http://gmail.com')
action = webdriver.ActionChains(browser)
emailElem = browser.find_element_by_id('Email')
emailElem.send_keys("MyUserName")
browser.find_element_by_name('signIn').click()
#browser.get('https://accounts.google.com/ServiceLogin?         service=mail&continue=https://mail.google.com/mail/#password')
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys("MyPassword")
browser.find_element_by_name('signIn').click()

Also, I have tried to find out the error in my code by comparing it to an answer given to a similar question here at: Auto connect on my Gmail account with Python Selenium

Can someone please guide me on the right path and let me know where I am making a mistake?

P.S: This is my first post on stackoverflow. Please excuse me for any mistake that I have made in posting the question

Body:
In 2020 signing in with Gmail is much more tougher because Gmail takes selenium operated window as a bot window and will give a message like this one.img of error

But now I have found a successful way to log in without any error or warning by google.

you can log in to another website as google will accept it as secure login using another website like StackOverflow or some other website with Gmail login.

def gmail_sign_in(email, password):
    driver = webdriver.Chrome()

    driver.get('https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent')

    driver.find_element_by_xpath('//*[@id="openid-buttons"]/button[1]').click()

    driver.find_element_by_xpath('//*[@id="identifierId"]').send_keys(email)

    input = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="identifierNext"]/span/span'))
    )
    input.click()

    driver.implicitly_wait(1)

    driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password)

    input = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="passwordNext"]/span/span'))
    )
    input.click()
    driver.implicitly_wait(1)
    driver.get('https://www.google.com/')

hope the code is understandable just this function and put your email and password make sure you have the appropriate imports.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


问:
Error: Unexpected token. A constructor, method, accessor, or property is expected. ts(1068)
I'm trying to build a pie chart using the Highcharts library with angular 8. But when I try to transcribe the code representing the chart the error comes out. Sorry for my bad english

This is my downloads-chart.component.ts:

```<code>import { Component, OnInit, OnChanges, Input, SimpleChanges } from '@angular/core';
import * as Highcharts from 'highcharts';
import HC_exporting from 'highcharts/modules/exporting';
import { Numbers } from 'src/app/model/all/Number';
import { DownloadIOS } from 'src/app/model/all/DownloadIOS';
import { DownloadAndroid } from 'src/app/model/all/DownloadAndroid';
import { NumeroDownload } from 'src/app/model/all/NumeroDownload';
import { SeriesDiagramm } from 'src/app/model/all/SeriesDiagramm';
import { ArrayDiagramm } from 'src/app/model/all/ArrayDiagramm';
import { DashboardService } from 'src/app/modules/dashboard.service';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

declare var require: any;
let Boost = require('highcharts/modules/boost');
let noData = require('highcharts/modules/no-data-to-display');
let More = require('highcharts/highcharts-more');

Boost(Highcharts);
noData(Highcharts);
More(Highcharts);
noData(Highcharts);

@Component({
  selector: 'app-downloads-chart',
  templateUrl: './downloads-chart.component.html',
  styleUrls: ['./downloads-chart.component.scss']
})
export class DownloadsChartComponent implements OnInit {
  // tslint:disable-next-line: no-input-rename
  @Input('diagramName') diagram: Numbers;

  arrIos = new DownloadIOS();
  arrAndr = new DownloadAndroid();
  arrDownload = new NumeroDownload();

  chartOptions = {};
  Highcharts = Highcharts;
  @Input() data = [];

  arrayIos: any[];
  arrayDownloads: any[];
  seriesProva: SeriesDiagramm[];
  seriesIOS: ArrayDiagramm[];
  seriesAndr: ArrayDiagramm[];
  seriesTot: ArrayDiagramm[];

  constructor(
    public service: DashboardService,
    public http: HttpClient,
    public router: Router,
  ) { }

  ngOnInit() {
    this.arrayIos = [];
    this.seriesProva = [];
    this.seriesIOS = [];
    this.seriesAndr = [];
    this.seriesTot = [];
    this.arrayDownloads = [];
    // tslint:disable-next-line: no-unused-expression
    Highcharts.defaultOptions;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.diagram.currentValue.tipoDiagramma === 1) {
      this.diagram = changes.diagram.currentValue;
      this.getStatisticDownloads();
    }
  }

  getStatisticDownloads() {
    this.service.getStatisticDownloadAndroid().subscribe((resp) => {
      this.service.getStatisticDownloadIOS().subscribe((respons) => {
        this.service.getStatisticNumeroDownload().subscribe((response) => {
          this.arrAndr = resp;
          this.arrIos = respons;
          this.arrDownload = response;
          this.arrayIos.push(this.arrIos);
          this.statistic3();
        });
      });
    });
  }

  statistic3() {
    let cont = 0;
    while (cont === 0) {
      this.seriesProva[cont] = new SeriesDiagramm();
      this.seriesProva[cont].data = new Array<ArrayDiagramm>();
      for (let i = 0; i < this.arrayIos.length; i++) {
        this.seriesIOS[i] = new ArrayDiagramm();
        this.seriesIOS[i].name = 'IOS';
        this.seriesIOS[i].y = this.arrIos.numeroDownloadIOS;
        this.seriesAndr[i] = new ArrayDiagramm();
        this.seriesAndr[i].name = 'Android';
        this.seriesAndr[i].y = this.arrAndr.numeroDownloadAnd;
        this.seriesTot[i] = new ArrayDiagramm();
        this.seriesTot[i].name = 'All';
        this.seriesTot[i].y = this.arrDownload.numeroDownload;
        this.seriesProva[cont].data.push(this.seriesIOS[i]);
        this.seriesProva[cont].data.push(this.seriesAndr[i]);
        this.seriesProva[cont].data.push(this.seriesTot[i]);
      }
      this.arrayDownloads.push(this.seriesProva[cont]);
      cont++;
    }
    this.diagrammaTorta();
  }

  diagrammaTorta() {
    // tslint:disable-next-line: space-before-function-paren
    Highcharts.addEvent(Highcharts.Chart, 'afterGetContainer', function () {
      this.container.style.background =
        'url(https://www.highcharts.com/samples/graphics/sand.png)';
    });
  }

   // tslint:disable-next-line: prefer-for-of
  // tslint:disable-next-line: quotemark
 // tslint:disable-next-line: no-unused-expression
new Highcharts.Chart({
    colors: ['#4a96d4', '#b53661', '#99c244', '#80699B', '#296d80',
      '#DB843D', '#92A8CD', '#A47D7C', '#61753e'],
    chart: {
      renderTo: 'container',
      height: 450,
      colorCount: 10,
      borderWidth: 1,
      borderColor: '#009933',
      borderRadius: 3,
      plotBorderWidth: 1,
      plotBorderColor: '#eee',
      plotShadow: false,
      backgroundColor: '#fff2',
      style: {
        fontSize: '14px',
        color: 'black'
      },
      type: 'pie',
    },
    legend: {
      padding: 15,
      itemMarginBottom: 5,
      itemMarginTop: 5,
      backgroundColor: '#ebedbe',
      borderColor: '#C98657',
      borderWidth: 1,
      borderRadius: 5,
      align: 'center',
      verticalAlign: 'bottom',
      layout: 'horizontal',
      // x: -30,
      // y: 50,
      itemDistance: 30,
      itemHoverStyle: {
        color: '#FF0000'
      }
    },
    title: {
      style: {
        color: 'black',
        fontSize: '22px',
        fontWeight: 'bold'
      },
      text: 'Numero Downloads App (Commerciale)'
    },
    tooltip: {
      headerFormat: '<span style="font-size:14px"></span><table>',
      pointFormat: '<span style="font-size:14px; color:{series.color}">{point.name}</span>: <b>{point.y}</b><br/>',
      style: {
        fontSize: '14',
        fontWeight: 'bold',
      },
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '<span style="font-size:14px; color:{series.color}"><b>{point.name}</b><br>{point.y:,.0f} </span>',
          style: {
            fontSize: '14',
          }
        },
        showInLegend: true,
      }
    },
    series: this.arrayDownloads,
  });
  }
</code>```

This is where I get the
typescript error 1068
 , when I try to create the chart, on the word new:

new Highcharts.Chart({

This is my HTML file of component:

答:
You could remove the new keyword, wrap the Highcharts.Chart in a function and call it to create the chart. Try the following

export class DownloadsChartComponent implements OnInit {
  ...

  createChart() {
    // tslint:disable-next-line: prefer-for-of
    // tslint:disable-next-line: quotemark
    // tslint:disable-next-line: no-unused-expression
    Highcharts.Chart({
      colors: ['#4a96d4', '#b53661', '#99c244', '#80699B', '#296d80', '#DB843D', '#92A8CD', '#A47D7C', '#61753e'],
      ...
    });
  }
}
```

Body:
I'm trying to build a pie chart using the Highcharts library with angular 8. But when I try to transcribe the code representing the chart the error comes out. Sorry for my bad english

This is my downloads-chart.component.ts:

import { Component, OnInit, OnChanges, Input, SimpleChanges } from '@angular/core';
import * as Highcharts from 'highcharts';
import HC_exporting from 'highcharts/modules/exporting';
import { Numbers } from 'src/app/model/all/Number';
import { DownloadIOS } from 'src/app/model/all/DownloadIOS';
import { DownloadAndroid } from 'src/app/model/all/DownloadAndroid';
import { NumeroDownload } from 'src/app/model/all/NumeroDownload';
import { SeriesDiagramm } from 'src/app/model/all/SeriesDiagramm';
import { ArrayDiagramm } from 'src/app/model/all/ArrayDiagramm';
import { DashboardService } from 'src/app/modules/dashboard.service';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

declare var require: any;
let Boost = require('highcharts/modules/boost');
let noData = require('highcharts/modules/no-data-to-display');
let More = require('highcharts/highcharts-more');

Boost(Highcharts);
noData(Highcharts);
More(Highcharts);
noData(Highcharts);

@Component({
  selector: 'app-downloads-chart',
  templateUrl: './downloads-chart.component.html',
  styleUrls: ['./downloads-chart.component.scss']
})
export class DownloadsChartComponent implements OnInit {
  // tslint:disable-next-line: no-input-rename
  @Input('diagramName') diagram: Numbers;

  arrIos = new DownloadIOS();
  arrAndr = new DownloadAndroid();
  arrDownload = new NumeroDownload();

  chartOptions = {};
  Highcharts = Highcharts;
  @Input() data = [];

  arrayIos: any[];
  arrayDownloads: any[];
  seriesProva: SeriesDiagramm[];
  seriesIOS: ArrayDiagramm[];
  seriesAndr: ArrayDiagramm[];
  seriesTot: ArrayDiagramm[];

  constructor(
    public service: DashboardService,
    public http: HttpClient,
    public router: Router,
  ) { }

  ngOnInit() {
    this.arrayIos = [];
    this.seriesProva = [];
    this.seriesIOS = [];
    this.seriesAndr = [];
    this.seriesTot = [];
    this.arrayDownloads = [];
    // tslint:disable-next-line: no-unused-expression
    Highcharts.defaultOptions;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.diagram.currentValue.tipoDiagramma === 1) {
      this.diagram = changes.diagram.currentValue;
      this.getStatisticDownloads();
    }
  }

  getStatisticDownloads() {
    this.service.getStatisticDownloadAndroid().subscribe((resp) => {
      this.service.getStatisticDownloadIOS().subscribe((respons) => {
        this.service.getStatisticNumeroDownload().subscribe((response) => {
          this.arrAndr = resp;
          this.arrIos = respons;
          this.arrDownload = response;
          this.arrayIos.push(this.arrIos);
          this.statistic3();
        });
      });
    });
  }

  statistic3() {
    let cont = 0;
    while (cont === 0) {
      this.seriesProva[cont] = new SeriesDiagramm();
      this.seriesProva[cont].data = new Array<ArrayDiagramm>();
      for (let i = 0; i < this.arrayIos.length; i++) {
        this.seriesIOS[i] = new ArrayDiagramm();
        this.seriesIOS[i].name = 'IOS';
        this.seriesIOS[i].y = this.arrIos.numeroDownloadIOS;
        this.seriesAndr[i] = new ArrayDiagramm();
        this.seriesAndr[i].name = 'Android';
        this.seriesAndr[i].y = this.arrAndr.numeroDownloadAnd;
        this.seriesTot[i] = new ArrayDiagramm();
        this.seriesTot[i].name = 'All';
        this.seriesTot[i].y = this.arrDownload.numeroDownload;
        this.seriesProva[cont].data.push(this.seriesIOS[i]);
        this.seriesProva[cont].data.push(this.seriesAndr[i]);
        this.seriesProva[cont].data.push(this.seriesTot[i]);
      }
      this.arrayDownloads.push(this.seriesProva[cont]);
      cont++;
    }
    this.diagrammaTorta();
  }

  diagrammaTorta() {
    // tslint:disable-next-line: space-before-function-paren
    Highcharts.addEvent(Highcharts.Chart, 'afterGetContainer', function () {
      this.container.style.background =
        'url(https://www.highcharts.com/samples/graphics/sand.png)';
    });
  }

   // tslint:disable-next-line: prefer-for-of
  // tslint:disable-next-line: quotemark
 // tslint:disable-next-line: no-unused-expression
new Highcharts.Chart({
    colors: ['#4a96d4', '#b53661', '#99c244', '#80699B', '#296d80',
      '#DB843D', '#92A8CD', '#A47D7C', '#61753e'],
    chart: {
      renderTo: 'container',
      height: 450,
      colorCount: 10,
      borderWidth: 1,
      borderColor: '#009933',
      borderRadius: 3,
      plotBorderWidth: 1,
      plotBorderColor: '#eee',
      plotShadow: false,
      backgroundColor: '#fff2',
      style: {
        fontSize: '14px',
        color: 'black'
      },
      type: 'pie',
    },
    legend: {
      padding: 15,
      itemMarginBottom: 5,
      itemMarginTop: 5,
      backgroundColor: '#ebedbe',
      borderColor: '#C98657',
      borderWidth: 1,
      borderRadius: 5,
      align: 'center',
      verticalAlign: 'bottom',
      layout: 'horizontal',
      // x: -30,
      // y: 50,
      itemDistance: 30,
      itemHoverStyle: {
        color: '#FF0000'
      }
    },
    title: {
      style: {
        color: 'black',
        fontSize: '22px',
        fontWeight: 'bold'
      },
      text: 'Numero Downloads App (Commerciale)'
    },
    tooltip: {
      headerFormat: '
',
      pointFormat: '{point.name}: {point.y}
',
      style: {
        fontSize: '14',
        fontWeight: 'bold',
      },
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '{point.name}
{point.y:,.0f} ',
          style: {
            fontSize: '14',
          }
        },
        showInLegend: true,
      }
    },
    series: this.arrayDownloads,
  });
  }

This is where I get the
typescript error 1068
 , when I try to create the chart, on the word new:

new Highcharts.Chart({

This is my HTML file of component:


问:
Index in postgresql
Firstly, I have a table in database USERS with almost 30 Million records in it. I have different indices for each column. But some of the column have only 2 to 3 non null values while others are Null but still their index size is 847 MB a little less than the one index that contain unique value for each row.

Can anyone know why is it like this?

Secondly, in PostgreSQL we have a index for primary key index for each column by default what if we delete that index what will be the consequences?
What that index is really use for?
As i'm searching based on values in other columns only will it be safe to delete index for primary key?

答:
There is nothing called primary key index, seems to be you are talking about unique index.
First of all you need to understand the difference between primary key and index. You can have only one primary key in a table. Primary key would be your unique identifier of each column and does not allow nulls. Index is used to speed up your fetching process on particular column and you can have one null if it is unique index. Deleting unique index in your table will not impact any thing apart from performance. Its your way of design to have index or not</p>

Title: Index in postgresql


问:
position: sticky to bottom left
I have just been playing around in FF32 & Safari 7, with position: sticky. And it works perfecly with top: 0px or left: 0px (to stick horizontally), but it doesn't seem to work when I try bottom: 0px or even better, combine bottom: 0; left: 0 it doesn't set itself to the bottom of the element. This behaviour could be tried out here: http://html5-demos.appspot.com/static/css/sticky.html, by simply changing the top: 10px attribut to bottom: 0. Is that not supposed to work?

I think it is a valid use-case to stick something to the bottom in the same way as one would want to stick something to the top.
In our case it is, because I am interested in having something sticky on horizontal scroll, but I want this element to be at the bottom of the parent element.

Anyway, any suggestions and extra info are welcome.

答:
```<code>.sticky-container {
  position: sticky;
  top: 100vh; // push it to the bottom from top
  transform: translateY(-100%); // move it up again depending on its own height
  width: 100%;
  background: white;
  padding: 20px 0;
}
</code>```

Title: position: sticky to bottom left


问:
What is the best way to write to a file in a parallel thread in Java?
I have a program that performs lots of calculations and reports them to a file frequently. I know that frequent write operations can slow a program down a lot, so to avoid it I'd like to have a second thread dedicated to the writing operations.

Right now I'm doing it with this class I wrote (the impatient can skip to the end of the question):

```<code>public class ParallelWriter implements Runnable {

    private File file;
    private BlockingQueue<Item> q;
    private int indentation;

    public ParallelWriter( File f ){
        file = f;
        q = new LinkedBlockingQueue<Item>();
        indentation = 0;
    }

    public ParallelWriter append( CharSequence str ){
        try {
            CharSeqItem item = new CharSeqItem();
            item.content = str;
            item.type = ItemType.CHARSEQ;
            q.put(item);
            return this;
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public ParallelWriter newLine(){
        try {
            Item item = new Item();
            item.type = ItemType.NEWLINE;
            q.put(item);
            return this;
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void setIndent(int indentation) {
        try{
            IndentCommand item = new IndentCommand();
            item.type = ItemType.INDENT;
            item.indent = indentation;
            q.put(item);
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void end(){
        try {
            Item item = new Item();
            item.type = ItemType.POISON;
            q.put(item);
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void run() {

        BufferedWriter out = null;
        Item item = null;

        try{
            out = new BufferedWriter( new FileWriter( file ) );
            while( (item = q.take()).type != ItemType.POISON ){
                switch( item.type ){
                    case NEWLINE:
                        out.newLine();
                        for( int i = 0; i < indentation; i++ )
                            out.append("   ");
                        break;
                    case INDENT:
                        indentation = ((IndentCommand)item).indent;
                        break;
                    case CHARSEQ:
                        out.append( ((CharSeqItem)item).content );
                }
            }
        } catch (InterruptedException ex){
            throw new RuntimeException( ex );
        } catch  (IOException ex) {
            throw new RuntimeException( ex );
        } finally {
            if( out != null ) try {
                out.close();
            } catch (IOException ex) {
                throw new RuntimeException( ex );
            }
        }
    }

    private enum ItemType {
        CHARSEQ, NEWLINE, INDENT, POISON;
    }
    private static class Item {
        ItemType type;
    }
    private static class CharSeqItem extends Item {
        CharSequence content;
    }
    private static class IndentCommand extends Item {
        int indent;
    }
}
</code>```

And then I use it by doing:

```<code>ParallelWriter w = new ParallelWriter( myFile );
new Thread(w).start();

/// Lots of
w.append(" things ").newLine();
w.setIndent(2);
w.newLine().append(" more things ");

/// and finally
w.end();
</code>```

While this works perfectly well, I'm wondering:
Is there a better way to accomplish this?

答:
One good way to exchange data with a single consumer thread is to use an Exchanger.

You could use a StringBuilder or ByteBuffer as the buffer to exchange with the background thread. The latency incurred can be around 1 micro-second, doesn't involve creating any objects and which is lower using a BlockingQueue.

From the example which I think is worth repeating here.

```<code>class FillAndEmpty {
   Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
   DataBuffer initialEmptyBuffer = ... a made-up type
   DataBuffer initialFullBuffer = ...

   class FillingLoop implements Runnable {
     public void run() {
       DataBuffer currentBuffer = initialEmptyBuffer;
       try {
         while (currentBuffer != null) {
           addToBuffer(currentBuffer);
           if (currentBuffer.isFull())
             currentBuffer = exchanger.exchange(currentBuffer);
         }
       } catch (InterruptedException ex) { ... handle ... }
     }
   }

   class EmptyingLoop implements Runnable {
     public void run() {
       DataBuffer currentBuffer = initialFullBuffer;
       try {
         while (currentBuffer != null) {
           takeFromBuffer(currentBuffer);
           if (currentBuffer.isEmpty())
             currentBuffer = exchanger.exchange(currentBuffer);
         }
       } catch (InterruptedException ex) { ... handle ...}
     }
   }

   void start() {
     new Thread(new FillingLoop()).start();
     new Thread(new EmptyingLoop()).start();
   }
 }
</code>```

Body:
I have a program that performs lots of calculations and reports them to a file frequently. I know that frequent write operations can slow a program down a lot, so to avoid it I'd like to have a second thread dedicated to the writing operations.

Right now I'm doing it with this class I wrote (the impatient can skip to the end of the question):

public class ParallelWriter implements Runnable {

    private File file;
    private BlockingQueue<Item> q;
    private int indentation;

    public ParallelWriter( File f ){
        file = f;
        q = new LinkedBlockingQueue<Item>();
        indentation = 0;
    }

    public ParallelWriter append( CharSequence str ){
        try {
            CharSeqItem item = new CharSeqItem();
            item.content = str;
            item.type = ItemType.CHARSEQ;
            q.put(item);
            return this;
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public ParallelWriter newLine(){
        try {
            Item item = new Item();
            item.type = ItemType.NEWLINE;
            q.put(item);
            return this;
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void setIndent(int indentation) {
        try{
            IndentCommand item = new IndentCommand();
            item.type = ItemType.INDENT;
            item.indent = indentation;
            q.put(item);
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void end(){
        try {
            Item item = new Item();
            item.type = ItemType.POISON;
            q.put(item);
        } catch (InterruptedException ex) {
            throw new RuntimeException( ex );
        }
    }

    public void run() {

        BufferedWriter out = null;
        Item item = null;

        try{
            out = new BufferedWriter( new FileWriter( file ) );
            while( (item = q.take()).type != ItemType.POISON ){
                switch( item.type ){
                    case NEWLINE:
                        out.newLine();
                        for( int i = 0; i < indentation; i++ )
                            out.append("   ");
                        break;
                    case INDENT:
                        indentation = ((IndentCommand)item).indent;
                        break;
                    case CHARSEQ:
                        out.append( ((CharSeqItem)item).content );
                }
            }
        } catch (InterruptedException ex){
            throw new RuntimeException( ex );
        } catch  (IOException ex) {
            throw new RuntimeException( ex );
        } finally {
            if( out != null ) try {
                out.close();
            } catch (IOException ex) {
                throw new RuntimeException( ex );
            }
        }
    }

    private enum ItemType {
        CHARSEQ, NEWLINE, INDENT, POISON;
    }
    private static class Item {
        ItemType type;
    }
    private static class CharSeqItem extends Item {
        CharSequence content;
    }
    private static class IndentCommand extends Item {
        int indent;
    }
}

And then I use it by doing:

ParallelWriter w = new ParallelWriter( myFile );
new Thread(w).start();

/// Lots of
w.append(" things ").newLine();
w.setIndent(2);
w.newLine().append(" more things ");

/// and finally
w.end();

While this works perfectly well, I'm wondering:
Is there a better way to accomplish this?

Body:
One good way to exchange data with a single consumer thread is to use an Exchanger.

You could use a StringBuilder or ByteBuffer as the buffer to exchange with the background thread. The latency incurred can be around 1 micro-second, doesn't involve creating any objects and which is lower using a BlockingQueue.

From the example which I think is worth repeating here.

class FillAndEmpty {
   Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
   DataBuffer initialEmptyBuffer = ... a made-up type
   DataBuffer initialFullBuffer = ...

   class FillingLoop implements Runnable {
     public void run() {
       DataBuffer currentBuffer = initialEmptyBuffer;
       try {
         while (currentBuffer != null) {
           addToBuffer(currentBuffer);
           if (currentBuffer.isFull())
             currentBuffer = exchanger.exchange(currentBuffer);
         }
       } catch (InterruptedException ex) { ... handle ... }
     }
   }

   class EmptyingLoop implements Runnable {
     public void run() {
       DataBuffer currentBuffer = initialFullBuffer;
       try {
         while (currentBuffer != null) {
           takeFromBuffer(currentBuffer);
           if (currentBuffer.isEmpty())
             currentBuffer = exchanger.exchange(currentBuffer);
         }
       } catch (InterruptedException ex) { ... handle ...}
     }
   }

   void start() {
     new Thread(new FillingLoop()).start();
     new Thread(new EmptyingLoop()).start();
   }
 }


问:
Using a search function for arrays of different types of structs in C
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

```<code>typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;
</code>```

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

```<code>book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}
</code>```

And instead be able to perform the search for both data structures in a single function?

答:
This is where templates of C++ fit great. In pure C, however, this is a hell:
First you would need a common type for your arrays, which is likely void*, but this also removes any type information.

Because of this, your search function then also needs to know the size of one element and the offset inside one element into the isbn member.

This is where pointer arithmetic comes into play and surely nothing you want to do as a beginner. If you want to go that way, have a look at sizeof and maybe the offsetof macro which is commonly used in C code, but I really think this is quite advanced.

Body:
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}

And instead be able to perform the search for both data structures in a single function?


问:
What is the hierarchy for Python module imports?
Lets assume I have Python module in a directory and in the same directory I have a Python script that uses this module somehow.

```<code>wdir
├── module
│   └── module_stuff
└── script.py
</code>```

If I execute this file in a python environment where the module is not installed everything works fine as Python imports the module from it's source code.

The question is: if I install the module in this Python environment and continue executing the script the same way as before, will Python import the module from what was installed or from the source code? What is the hyerarchy Python follows to search for each import?

Why does it matter: If I have a script repeatedly calling other Python scripts and modify the source code of the module during this execution, then there will be results that used the old version of the module and the new version as well, or even worse, executions may be missed if a bug is inserted into the module code. But this would be solved if created a development env separated from the testing env.

答:
You can actually try this yourself:
Lets build a module and install it, then modify it to see who takes preference:

mymod -- | setup.py
          | mymod --| myfun.py
                    | __init__.py

setup.py contains:

```<code>from setuptools import setup, find_packages
setup(
    name='mymod',
    version='1.0',
    packages=find_packages(),
)
</code>```

and myfun.py contains:

```<code>def myfun():
    print('original Mod')
</code>```

Now we make a virtualenv and install it:

```<code>virtualenv venv -p python3
source venv/bin/activate
cd mymod
python setup.py install
</code>```

now we go to python and import

```<code>from mymod.mymod.myfun import myfun

myfun()
# Returns original Mod
</code>```

Now we modify myfun.py wITHOUT installing it:

```<code>def myfun():
    print('Modified Mod')
</code>```

and we go back to python:

```<code>from mymod.mymod.myfun import myfun

myfun()
# returns Modified Mod
</code>```

So looks like directories take precedence over modules, but give it a try!

(Note that if we change to a directory where mymod.myfun is not directly in our path it goes back to printing original mod)

Body:
Lets assume I have Python module in a directory and in the same directory I have a Python script that uses this module somehow.

wdir
├── module
│   └── module_stuff
└── script.py

If I execute this file in a python environment where the module is not installed everything works fine as Python imports the module from it's source code.

The question is: if I install the module in this Python environment and continue executing the script the same way as before, will Python import the module from what was installed or from the source code? What is the hyerarchy Python follows to search for each import?

Why does it matter: If I have a script repeatedly calling other Python scripts and modify the source code of the module during this execution, then there will be results that used the old version of the module and the new version as well, or even worse, executions may be missed if a bug is inserted into the module code. But this would be solved if created a development env separated from the testing env.

Body:
You can actually try this yourself:
Lets build a module and install it, then modify it to see who takes preference:

mymod -- | setup.py
          | mymod --| myfun.py
                    | __init__.py

setup.py contains:

from setuptools import setup, find_packages
setup(
    name='mymod',
    version='1.0',
    packages=find_packages(),
)

and myfun.py contains:

def myfun():
    print('original Mod')

Now we make a virtualenv and install it:

virtualenv venv -p python3
source venv/bin/activate
cd mymod
python setup.py install

now we go to python and import

from mymod.mymod.myfun import myfun

myfun()
# Returns original Mod

Now we modify myfun.py wITHOUT installing it:

def myfun():
    print('Modified Mod')

and we go back to python:

from mymod.mymod.myfun import myfun

myfun()
# returns Modified Mod

So looks like directories take precedence over modules, but give it a try!

(Note that if we change to a directory where mymod.myfun is not directly in our path it goes back to printing original mod)


问:
Dynamic routing in ASP.NET Core 3.1 when part of the url is already another route
I'm trying to use DynamicRouteValueTransformer with IEndpointRouteBuilder.MapDynamicControllerRoute to dynamically map new routes. This is for pages that are added while the application is running.

I'm doing:

```<code>endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{**slug}");
</code>```

to catch all urls that don't already have a route assigned, so that RouteValueTransformer can try to find one when necessary. By putting a breakpoint inside the RouteValueTransformer.TransformAsync method, I can see when it runs. If you just type any nonsense url in, it will enter the method as expected. For a url that doesn't have a route assigned, but an earlier part of the url does, it won't enter the method, as it seems to think it already has a route, but then it obviously gives a 404 error.

For example, if after the above line I do

```<code>endpoints.MapControllerRoute(
   name: "test",
   pattern: "category/product1",
   defaults: new { controller = "Home", action = "Index" });
</code>```

and then try to browse to "category/product2", I think it should enter the TransformAsync method to try and find a route, but it doesn't, and it gives a 404. If you change "category" to something else, it will enter the method.

I'm not sure if this is expected behaviour, a bug, or if I'm using the "pattern" parameter wrong, or maybe {**slug} wrong?

To reproduce

It's very easy to reproduce. Create a new ASP.NET Core 3.1 web application. Add

```<code>app.UseEndpoints(endpoints =>
{
    var defaults = new { controller = "Home", action = "Index" };
    endpoints.MapControllerRoute(name: "test", pattern: "category/product1", defaults: defaults);
    endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{**slug}");
});
</code>```

to the end of Startup.Configure,

```<code>services.AddSingleton<RouteValueTransformer>();
</code>```

to Startup.ConfigureServices,
and

```<code>public class RouteValueTransformer : DynamicRouteValueTransformer
{
    public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        return values;
    }
}
</code>```

and set a breakpoint on return values; to see when it runs.

What else I've tried

endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{one}/{two}"); - also doesn't enter method.

Looking through documentation. There isn't much on DynamicRouteValueTransformer (yet) unfortunately so I've found it quite difficult.

Update

I'm starting to think that it is mostly likely a bug, so I've raised this Github issue

答: It was a bug and a fix is planned. See https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1#conventional-routing-order</p>

Body:
I'm trying to use DynamicRouteValueTransformer with IEndpointRouteBuilder.MapDynamicControllerRoute to dynamically map new routes. This is for pages that are added while the application is running.

I'm doing:

endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{**slug}");

to catch all urls that don't already have a route assigned, so that RouteValueTransformer can try to find one when necessary. By putting a breakpoint inside the RouteValueTransformer.TransformAsync method, I can see when it runs. If you just type any nonsense url in, it will enter the method as expected. For a url that doesn't have a route assigned, but an earlier part of the url does, it won't enter the method, as it seems to think it already has a route, but then it obviously gives a 404 error.

For example, if after the above line I do

endpoints.MapControllerRoute(
   name: "test",
   pattern: "category/product1",
   defaults: new { controller = "Home", action = "Index" });

and then try to browse to "category/product2", I think it should enter the TransformAsync method to try and find a route, but it doesn't, and it gives a 404. If you change "category" to something else, it will enter the method.

I'm not sure if this is expected behaviour, a bug, or if I'm using the "pattern" parameter wrong, or maybe {**slug} wrong?

To reproduce

It's very easy to reproduce. Create a new ASP.NET Core 3.1 web application. Add

app.UseEndpoints(endpoints =>
{
    var defaults = new { controller = "Home", action = "Index" };
    endpoints.MapControllerRoute(name: "test", pattern: "category/product1", defaults: defaults);
    endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{**slug}");
});

to the end of Startup.Configure,

services.AddSingleton<RouteValueTransformer>();

to Startup.ConfigureServices,
and

public class RouteValueTransformer : DynamicRouteValueTransformer
{
    public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        return values;
    }
}

and set a breakpoint on return values; to see when it runs.

What else I've tried

endpoints.MapDynamicControllerRoute<RouteValueTransformer>("{one}/{two}"); - also doesn't enter method.

Looking through documentation. There isn't much on DynamicRouteValueTransformer (yet) unfortunately so I've found it quite difficult.

Update

I'm starting to think that it is mostly likely a bug, so I've raised this Github issue


问:
Why is using Power Pivot getting the Data Model deleted in Excel?
I am using Power Pivot to do some analysis and then make Pivot tables from the data model. There are more then 1 interconnected tables. The tables have been created using Power Query. The relationships are created using Power Pivot.

After my work is done and the Excel File is closed, the data model gets deleted. I can see that as the file size gets reduced. Also when I open the file and try to modify the pivot tables receive the following message: " the connection for this pivot table has been Deleted". The queries that were created using power query do not refresh either (Shows: Download Failed).
When I open the Power Pivot for Excel window, it does not show any tables in it.

I am using Microsoft Professional Plus 2016. Already Repaired MS Office.

Would really appreciate if any one can help.

Thank you.

答: Looks like this problem is caused because of Power Pivot Crashes. Found this blog https://exceleratorbi.com.au/does-the-power-pivot-excel-add-in-crash-for-you/, followed the steps and that seems to solve my problem for now. Its interesting that this problem is there since long and Microsoft has not been able to solve it yet.</p>


问:
Why is my Django test failing when the view actually works?
I have a class based view that works as designed in the browser. I'm trying to write unit tests for the view and they keep failing. I'm wondering why. The view (the UserPassesTest is whether the user is a superuser or not):

class EditUserView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    """handles get and post for adding a new AEUser"""
    template_name = 'editUser.html'
    title = 'Edit User'

    def get(self, request, *args, **kwargs):
        """handles the GET"""
        post_url = reverse('edit_user', args=[kwargs['user_id']])
        usr = get_object_or_404(AEUser, pk=kwargs['user_id'])
        form = EditUserForm(initial={'is_active':usr.is_active, 'is_superuser':usr.is_superuser}, \
            user=usr, request=request)
        return render(request, self.template_name, \
            {'title_text':self.title, 'post_url':post_url, 'form':form})
```

<p>The Test Case:</p>

<pre class="lang-py prettyprint-override"><code>class TestEditUser(TestCase):
    """test the AddUser view"""

    @classmethod
    def setUpTestData(cls):
        cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test')
        cls.user.is_superuser = True
        cls.user.save()

    def setUp(self):
        self.client = Client()

    def test_get(self):
        """tests the GET"""
        self.client.login(username=self.user.username, password=self.user.password)
        get_url = reverse('edit_user', args=[self.user.id])
        response = self.client.get(get_url, follow=True)
        self.assertEqual(self.user.is_superuser, True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'editUser.html')

</code>```

I have 3 asserts in the test case. If I comment out the last two, and only assert that the user is a superuser, the test passes. For whatever reason, though, on the other two asserts, I get failures. The error I receive is:

AssertionError: False is not true : Template 'editUser.html' was not a template used to render the response. Actual template(s) used: 404.html, base.html, which leads me to believe the get_object_or_404 call is what's triggering the failure. Where am I going wrong with this test case? Thanks!

答:
Test should be:

class TestEditUser(TestCase):
    """test the AddUser view"""

    @classmethod
    def setUpTestData(cls):
        cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test')
        cls.user.is_superuser = True
        cls.user.save()

    def setUp(self):
        self.client = Client()

    def test_get(self):
        """tests the GET"""
        self.client.login(username=self.user.username, password='test')
        get_url = reverse('edit_user', args=[self.user.id])
        response = self.client.get(get_url, follow=True)
        self.assertEqual(self.user.is_superuser, True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'editUser.html')
```

Body:
I have a class based view that works as designed in the browser. I'm trying to write unit tests for the view and they keep failing. I'm wondering why. The view (the UserPassesTest is whether the user is a superuser or not):

class EditUserView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    """handles get and post for adding a new AEUser"""
    template_name = 'editUser.html'
    title = 'Edit User'

    def get(self, request, *args, **kwargs):
        """handles the GET"""
        post_url = reverse('edit_user', args=[kwargs['user_id']])
        usr = get_object_or_404(AEUser, pk=kwargs['user_id'])
        form = EditUserForm(initial={'is_active':usr.is_active, 'is_superuser':usr.is_superuser}, \
            user=usr, request=request)
        return render(request, self.template_name, \
            {'title_text':self.title, 'post_url':post_url, 'form':form})

The Test Case:

class TestEditUser(TestCase):
    """test the AddUser view"""

    @classmethod
    def setUpTestData(cls):
        cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test')
        cls.user.is_superuser = True
        cls.user.save()

    def setUp(self):
        self.client = Client()

    def test_get(self):
        """tests the GET"""
        self.client.login(username=self.user.username, password=self.user.password)
        get_url = reverse('edit_user', args=[self.user.id])
        response = self.client.get(get_url, follow=True)
        self.assertEqual(self.user.is_superuser, True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'editUser.html')

I have 3 asserts in the test case. If I comment out the last two, and only assert that the user is a superuser, the test passes. For whatever reason, though, on the other two asserts, I get failures. The error I receive is:

AssertionError: False is not true : Template 'editUser.html' was not a template used to render the response. Actual template(s) used: 404.html, base.html, which leads me to believe the get_object_or_404 call is what's triggering the failure. Where am I going wrong with this test case? Thanks!


问:
Set FFmpeg Process Priority with 2 Pass Encoding
I'm using FFmpeg with PowerShell.

I'm trying to set the Process Priority while using FFmpeg's 2 Pass Encoding.

The script works with 1 Pass and CRF Encoding.

Script

When Pass 1 finishes, it launches FFmpeg again for Pass 2.

Note: Pass 1 outputs to NUL, Pass 2 outputs the video file.

```<code>(Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;

(Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
</code>```

Problem

Using -Wait causes this PowerShell error:

```<code>Exception setting "PriorityClass": "Cannot process request because the process (14324) has exited."
</code>```

But without -Wait the second pass never starts and I get this FFmpeg error:

```<code>Failed to initialize encoder: Invalid parameter
Additional information: rc_twopass_stats_in.buf not set.
</code>```

答:
What you would be looking for is Wait-Process.

You will need to lose the -wait as that command waits for the process to exit before running the next part of the script

```<code>($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
Wait-Process -Id $Process.id
($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
Wait-Process -Id $Process.id
</code>```

You can verify the process has exited by using $Process.HasExited

```<code>($Process = Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
Wait-Process -Id $Process.id
$Process.HasExited
($Process = Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
Wait-Process -Id $Process.id
$Process.HasExited
</code>```

Body:
I'm using FFmpeg with PowerShell.

I'm trying to set the Process Priority while using FFmpeg's 2 Pass Encoding.

The script works with 1 Pass and CRF Encoding.

Script

When Pass 1 finishes, it launches FFmpeg again for Pass 2.

Note: Pass 1 outputs to NUL, Pass 2 outputs the video file.

(Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;

(Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal

Problem

Using -Wait causes this PowerShell error:

Exception setting "PriorityClass": "Cannot process request because the process (14324) has exited."

But without -Wait the second pass never starts and I get this FFmpeg error:

Failed to initialize encoder: Invalid parameter
Additional information: rc_twopass_stats_in.buf not set.

Body:
What you would be looking for is Wait-Process.

You will need to lose the -wait as that command waits for the process to exit before running the next part of the script

($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
Wait-Process -Id $Process.id
($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
Wait-Process -Id $Process.id

You can verify the process has exited by using $Process.HasExited

($Process = Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 1 NUL' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
Wait-Process -Id $Process.id
$Process.HasExited
($Process = Start-Process ffmpeg -NoNewWindow -Wait -ArgumentList '-i "C:\Path\video.mpg" -c:v libx264 -b:v 2000K -pass 2 "C:\Path\video.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
Wait-Process -Id $Process.id
$Process.HasExited


问:
VirtualBox Not Starting after Successful Docker Installation
Before starting to learn docker, I have been able to open oracle virtual machine. But after following steps on how to install docker on windows, then switching on hyper-v, docker started working but this has made the virtual machine to stop working so I decided to uninstall docker and switch off hyper-v then restart the system, surprisingly, the VirtualBox is still showing similar error like so:

```<code>Call to VidMessageSlotMap failed: Last=0xc000000d/87 (VERR_NEM_VM_CREATE_FAILED).

Result Code:
E_FAIL (0x80004005)
Component:
ConsoleWrap
Interface:
IConsole {872da645-4a9b-1727-bee2-5585105b9eed}
</code>```

Please how can I fix this?

答:
From Control Panel\All Control Panel Items\Programs and Features, Click on the "Turn Windows features on or off", and in the pop-up which appears, do the following

```<code> 1. turn off Hyper-V by unchecking the Checkbox
 2. turn off Windows Hypervisor Platform unchecking the Checkbox
 3. turn off Windows Sandbox
 4. turn off Containers
</code>```

Reboot when prompted. Then try Virtual Box again, it should work.
Alternatively you can uninstall and reinstall Virtual box. It might work too.

Body:
Before starting to learn docker, I have been able to open oracle virtual machine. But after following steps on how to install docker on windows, then switching on hyper-v, docker started working but this has made the virtual machine to stop working so I decided to uninstall docker and switch off hyper-v then restart the system, surprisingly, the VirtualBox is still showing similar error like so:

Call to VidMessageSlotMap failed: Last=0xc000000d/87 (VERR_NEM_VM_CREATE_FAILED).

Result Code:
E_FAIL (0x80004005)
Component:
ConsoleWrap
Interface:
IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

Please how can I fix this?

Body:
From Control Panel\All Control Panel Items\Programs and Features, Click on the "Turn Windows features on or off", and in the pop-up which appears, do the following

 1. turn off Hyper-V by unchecking the Checkbox
 2. turn off Windows Hypervisor Platform unchecking the Checkbox
 3. turn off Windows Sandbox
 4. turn off Containers

Reboot when prompted. Then try Virtual Box again, it should work.
Alternatively you can uninstall and reinstall Virtual box. It might work too.


问:
How can I enable Suitescript IntelliSense on vs code?
I want IntelliSense for suitescript on vs code, I tried to put the netsuite2.0 API (the one downloadable from file cabinet) folder with the definitions made a jsconfig.json with only a {} in my workspace like some tutorials says but it doesn't work.
I also tried the extension GVO snippets, in the details it says that have context support for a serie of functions but it seems that it does not work either.</p>

答:
For anyone still looking for a solution to the 2.0 API issue, please check out SuiteSnippets in VS Codes Extension marketplace. It’s an extension I built to solve to bring an intellisense feel VS Code for SuiteScript 2.0.

Would really appreciate any feedback!

https://marketplace.visualstudio.com/items?itemName=ericbirdsall.SuiteSnippets


问:
How to create custom textbox component in Angular 9
I want to create some common components for HTML tags in Angular 9, like text-box.

Parent Component HTML:

```<code><form (ngSubmit)="onSubmit()">
            <textbox [name]="'articleDto.articleName'" (changeEvent)="txtChange($event)" [label]="'Article Name'" [placeholder]="'Article Name'"></textbox>
            <textbox [name]="'articleDto.titleName'" [label]="'Title Name'" [placeholder]="'Title Name'"></textbox>
          <button type="submit" class="btn btn-success mr-2">Submit</button>
</form>
</code>```

Parent Component TS Code:

```<code>import { Component, OnInit } from '@angular/core';
import { spinx } from '../core/lib/spinx.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-new-article',
  templateUrl: './new-article.component.html'
})
export class NewArticleComponent implements OnInit {

  articleDto:any = {};
  constructor(private spinxService: spinx) { }

  ngOnInit(): void {
  }

  txtChange(event){
    alert(this.articleDto.articleName)
  }
}
</code>```

Child Component TS:

```<code>import { Component, forwardRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
  selector: 'textbox',
  template: `
  <div class="form-group">
  <label>{{label}}</label>
  <input type="text" name="{{name}}" [(ngModel)]="{{name}}" (change)="changeComplete()" class="form-control" placeholder="{{placeholder}}">
  </div>
  `,
  providers: [
    {provide: NG_VALUE_ACCESSOR, useExisting: TextboxComponent, multi: true}
  ]
})
export class TextboxComponent  {
  @Input() placeholder: string;
  @Input() name: string;
  @Input() label: string;
  @Output()
  changeEvent = new EventEmitter<string>();
  changeComplete() {
    this.changeEvent.emit('complete');
  }
}
</code>```

I'm not able to use [(ngModel)]="{{name}}" in child component which is mapped with the parent Component.

Please provide a solution/suggestion for this. Thanks!

答:
While doing two way data binding with ngModel, the appropriate syntax is :

```<code> [(ngModel)]="name"
</code>```

Interpolation need not be used with the variable name.

Update :
 1. If the components have a parent/child relationship, as in your case, You can share data between them via @Input() and @Output() decorators.

Sharing data from Parent to Child using @Input() :

```<code><h3>Parent Component</h3>

<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>

<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>
</code>```

And in the child component, the 'parentValue' can be received as :

```<code>import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() value: number;
  constructor() { }

  ngOnInit() {
  }

}
</code>```

Now, in the case of sending data from Child to Parent, we can use an @Output() event emitter. So the parent would have a function to receive the emitted data from child as :

```<code>parent-app.component.html
    <app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>

parent-app.component.ts

childEvent(event) {
console.log(event);
}

And, the child.component.ts would look like :

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() PData: number;
  @Output() childEvent = new EventEmitter();
  constructor() { }
  onChange(value) {
    this.childEvent.emit(value);
  }

  ngOnInit() {
  }

}
</code>```

Body:
I want to create some common components for HTML tags in Angular 9, like text-box.

Parent Component HTML:

<form (ngSubmit)="onSubmit()">
            <textbox [name]="'articleDto.articleName'" (changeEvent)="txtChange($event)" [label]="'Article Name'" [placeholder]="'Article Name'"></textbox>
            <textbox [name]="'articleDto.titleName'" [label]="'Title Name'" [placeholder]="'Title Name'"></textbox>
          <button type="submit" class="btn btn-success mr-2">Submit</button>
</form>

Parent Component TS Code:

import { Component, OnInit } from '@angular/core';
import { spinx } from '../core/lib/spinx.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-new-article',
  templateUrl: './new-article.component.html'
})
export class NewArticleComponent implements OnInit {

  articleDto:any = {};
  constructor(private spinxService: spinx) { }

  ngOnInit(): void {
  }

  txtChange(event){
    alert(this.articleDto.articleName)
  }
}

Child Component TS:

import { Component, forwardRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
  selector: 'textbox',
  template: `

  {{label}}
  <input type="text" name="{{name}}" [(ngModel)]="{{name}}" (change)="changeComplete()" class="form-control" placeholder="{{placeholder}}">

  `,
  providers: [
    {provide: NG_VALUE_ACCESSOR, useExisting: TextboxComponent, multi: true}
  ]
})
export class TextboxComponent  {
  @Input() placeholder: string;
  @Input() name: string;
  @Input() label: string;
  @Output()
  changeEvent = new EventEmitter<string>();
  changeComplete() {
    this.changeEvent.emit('complete');
  }
}

I'm not able to use [(ngModel)]="{{name}}" in child component which is mapped with the parent Component.

Please provide a solution/suggestion for this. Thanks!

Body:
While doing two way data binding with ngModel, the appropriate syntax is :

 [(ngModel)]="name"

Interpolation need not be used with the variable name.

Update :
 1. If the components have a parent/child relationship, as in your case, You can share data between them via @Input() and @Output() decorators.

Sharing data from Parent to Child using @Input() :

<h3>Parent Component</h3>

<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>

<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>

And in the child component, the 'parentValue' can be received as :

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() value: number;
  constructor() { }

  ngOnInit() {
  }

}

Now, in the case of sending data from Child to Parent, we can use an @Output() event emitter. So the parent would have a function to receive the emitted data from child as :

parent-app.component.html
    <app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>

parent-app.component.ts

childEvent(event) {
console.log(event);
}

And, the child.component.ts would look like :

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() PData: number;
  @Output() childEvent = new EventEmitter();
  constructor() { }
  onChange(value) {
    this.childEvent.emit(value);
  }

  ngOnInit() {
  }

}


问:
Delete file if it is owned by specific user
There is a file that is sometimes not owned by root

I want my perl script in linux to basically check if a file is owned by root if it is delete it.

Currently what I have unlink("$File_Path/File_Name");

but this just deletes the file I want it to check if it's owned by root first then delete otherwise ignore.

can you please guide me how I can achieve this I am out of ideas?

答:
If you're doing this to a bunch of files in a folder somewhere, you might be better off by just one of these:

```<code>find /folder/somewhere/ -type f -user root -exec rm {} \;
find /folder/somewhere/ -type f -user root -exec rm -i {} \;   #interactive y/n each file
find /folder/somewhere/ -type f -user root -print0 | xargs -r0 rm
</code>```

You might also need sudo in front of find. Careful though, this is a kind of command that can do a lot of harm...

Body:
If you're doing this to a bunch of files in a folder somewhere, you might be better off by just one of these:

find /folder/somewhere/ -type f -user root -exec rm {} \;
find /folder/somewhere/ -type f -user root -exec rm -i {} \;   #interactive y/n each file
find /folder/somewhere/ -type f -user root -print0 | xargs -r0 rm

You might also need sudo in front of find. Careful though, this is a kind of command that can do a lot of harm...


问:
Add and implement a spinner in fragment
I have seen guides and tutorials implementing spinner for activities. However the same method doesn't work for fragments. This was my code inside the onCreateView method of a fragment class

```<code>val personnames = arrayOf("akshat" , "mourya")
    val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personnames)
    spinner.adapter = arrayAdapter
    spinner.onItemSelectedListener = object :

    AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {

            spinnerText.text = personnames[position]
        }
</code>```

When the ArrayAdapter method is called on line 2, I get a type mismatch error because the first parameter requires a context and in my code it is a fragment.
I tried doing the same thing in the activity and it worked.
Fragment are supposed to be like mini activities, so why this error propping up?

Also is there any way I can add spinner to my Fragment?

答:
Try it like this:</p>

```<code> val arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, personnames)
</code>```

Title: Add and implement a spinner in fragment

Body:
I have seen guides and tutorials implementing spinner for activities. However the same method doesn't work for fragments. This was my code inside the onCreateView method of a fragment class

val personnames = arrayOf("akshat" , "mourya")
    val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personnames)
    spinner.adapter = arrayAdapter
    spinner.onItemSelectedListener = object :

    AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {

            spinnerText.text = personnames[position]
        }

When the ArrayAdapter method is called on line 2, I get a type mismatch error because the first parameter requires a context and in my code it is a fragment.
I tried doing the same thing in the activity and it worked.
Fragment are supposed to be like mini activities, so why this error propping up?

Also is there any way I can add spinner to my Fragment?

Body:
Try it like this:

 val arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, personnames)


问:
jquery animate scrolltop callback
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

```<code>$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});
</code>```

答:
It doesn't wait

It animates your document from top to the top... Funny but that's how it is. You have other alternatives. Either:

check your page position before scrolling (as others suggested by providing some code) or

use some jQuery plugin that works differently

My .scrollintoview() jQuery plugin works that way. It scrolls only if it has to and runs a complete handler after scrolling is complete (if there was scrolling in the first place) or immediately if scrolling is not needed.

But it needs some element that needs to be scrolled. You're actually not scrolling any element into view but rather just HTML. This is of course not the safest way. It's better to use either:

```<code>$("html,body")
</code>```

or

```<code>$(window)
</code>```

It's more cross browser supported. So your $("html") may not work in all of them.

Title: jquery animate scrolltop callback

Body:
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});

Body:
It doesn't wait

It animates your document from top to the top... Funny but that's how it is. You have other alternatives. Either:

check your page position before scrolling (as others suggested by providing some code) or

use some jQuery plugin that works differently

My .scrollintoview() jQuery plugin works that way. It scrolls only if it has to and runs a complete handler after scrolling is complete (if there was scrolling in the first place) or immediately if scrolling is not needed.

But it needs some element that needs to be scrolled. You're actually not scrolling any element into view but rather just HTML. This is of course not the safest way. It's better to use either:

$("html,body")

or

$(window)

It's more cross browser supported. So your $("html") may not work in all of them.


问:
Using Generic swift enum in a protocol
I have case where I often scratch my head around, let's say I have a generic Manager class in a pod that can handle permission, and within the app, I want to be able to extend it to create more meaningful method name, aka to use with enum as parameter, to make its use more clear and less prone to mistake.

But it seems that you can't call private method when you create the extension elsewhere.

I'm sure there would be a more clean way with Generic/AssociatedValue or maybe my pattern is just wrong...

Here's the simplified version of it:

Class in the external pod:

```<code>public class FeatureDataManager {

    public static let shared = FeatureDataManager()

    private var permissionManager: PermissionManager!

    private init() {
        self.permissionManager = PermissionManager()
    }

    private getPermission(forFeature feature: String) -> Bool {
        return self.permissionManager.isEnable(feature)
    }
}
</code>```

and the extension in the app:

```<code>extension FeatureDataManager {
    enum FeatureType: String {
        case ads = "ads"
        case showBanner = "banner"
        case showFullScreenPub = "showFullScreenPub"
    }

    public func isPermissionEnable(forFeature feature: FeatureType) {
        // Does not compile, visibility issue
        self.getPermission(forFeature: feature.rawValue)
    }
}
</code>```

Clarification:

FeatureDataManager is a class in the Pod that is solely used to check for permissions in the form of String value across many app that are using importing it.

I wanted each single app using it, to define an extension that would have their own finite enum of their supported permissions. Let's say App A support Ads, but not App B. So I wanted to have a universal method that when you call featureManager.isPermissionEnable(.Ads), whenever app that is, the auto-complete would just offer the list of the supported permission for that app. Also, the goal of wrapping my string permission value into an enum is to be more bulletproof to mistake and easier refactoring if a name change, just have to change it in a single place.

答: You have to declare fileprivate access level to access it in an extension defined in same file. You cannot access private entities out of its defined scope, even if extension relies on same file!

Title: Using Generic swift enum in a protocol

Body:
I have case where I often scratch my head around, let's say I have a generic Manager class in a pod that can handle permission, and within the app, I want to be able to extend it to create more meaningful method name, aka to use with enum as parameter, to make its use more clear and less prone to mistake.

But it seems that you can't call private method when you create the extension elsewhere.

I'm sure there would be a more clean way with Generic/AssociatedValue or maybe my pattern is just wrong...

Here's the simplified version of it:

Class in the external pod:

public class FeatureDataManager {

    public static let shared = FeatureDataManager()

    private var permissionManager: PermissionManager!

    private init() {
        self.permissionManager = PermissionManager()
    }

    private getPermission(forFeature feature: String) -> Bool {
        return self.permissionManager.isEnable(feature)
    }
}

and the extension in the app:

extension FeatureDataManager {
    enum FeatureType: String {
        case ads = "ads"
        case showBanner = "banner"
        case showFullScreenPub = "showFullScreenPub"
    }

    public func isPermissionEnable(forFeature feature: FeatureType) {
        // Does not compile, visibility issue
        self.getPermission(forFeature: feature.rawValue)
    }
}

Clarification:

FeatureDataManager is a class in the Pod that is solely used to check for permissions in the form of String value across many app that are using importing it.

I wanted each single app using it, to define an extension that would have their own finite enum of their supported permissions. Let's say App A support Ads, but not App B. So I wanted to have a universal method that when you call featureManager.isPermissionEnable(.Ads), whenever app that is, the auto-complete would just offer the list of the supported permission for that app. Also, the goal of wrapping my string permission value into an enum is to be more bulletproof to mistake and easier refactoring if a name change, just have to change it in a single place.