问:
Capturing folder path from Windows Explorer
I would like to add to a Delphi application a way for the user to call Windows Explorer (possibly using something like ShellExecute, perhaps).

However, and this is where I need some help, please, the application would need to capture ^H^H^H^H^H^H read the folder path that the user navigates to while within Windows Explorer.

Is it possible to obtain this information from Windows Explorer?

[edit: If not possible, or unrealistic, my fallback plan is to provide a separate "Browse for folder" button, to allow the user to select the folder first, then they can launch the Window explorer afterwards].

Thanks for any advice.
PhilW.

答:
Can't you just use the TOpenDialog?  From Delphi Help:

Description

TOpenDialog displays a modal Windows dialog box for selecting and opening files. The dialog does not appear at runtime until it is activated by a call to the Execute method. When the user clicks Open, the dialog closes and the selected file or files are stored in the Files property.

```<code>if OpenDialog1.Execute then
   filename := OpenDialog1.FileName;
</code>```

Body:
Can't you just use the TOpenDialog?  From Delphi Help:

Description

TOpenDialog displays a modal Windows dialog box for selecting and opening files. The dialog does not appear at runtime until it is activated by a call to the Execute method. When the user clicks Open, the dialog closes and the selected file or files are stored in the Files property.

if OpenDialog1.Execute then
   filename := OpenDialog1.FileName;


来源: stackexchange

问:
EPPlus: Values in column of pivot table
When you create a pivot table in Excel and add fields to Rows and Values, you get an additional field [Symbol Sigma] Values in the GUI, that you can drag and drop to Columns.

I am creating a pivot table using EPPlus. How can I add this [Symbol Sigma] Values field to my column fields?

Edit: Here is some code. I dont' see how this is supposed to help, what it was asked for.

```<code>private static ExcelWorksheet CreatePivotWorksheet(ExcelPackage excel, ExcelWorksheet dataWorksheet)
{
    string worksheetName = "Pivot";

    ExcelWorksheet pivotWorksheet = excel.Workbook.Worksheets.Add(worksheetName);

    ExcelRangeBase dataRange = dataWorksheet.Cells[dataWorksheet.Dimension.Address];
    ExcelPivotTable pivotTable = pivotWorksheet.PivotTables.Add(pivotWorksheet.Cells[1,1], dataRange, "pivotTable");

    pivotTable.RowGrandTotals = false;

    pivotTable.RowFields.Add(pivotTable.Fields["BaseValue"]);
    pivotTable.RowFields.Add(pivotTable.Fields["Remaining Runtime"])
        .AddNumericGrouping(0, 500000, 30);
    pivotTable.RowFields.Add(pivotTable.Fields["Emittent"]);
    pivotTable.RowFields.Add(pivotTable.Fields["CountIfs"]);
    pivotTable.RowFields.Add(pivotTable.Fields["ISIN"]);

    var stressField = pivotTable.DataFields.Add(pivotTable.Fields["StressScenario - Percent"]);
    stressField.Function = DataFieldFunctions.Average;
    stressField.Format = "0.00%";
    var pessimisticField = pivotTable.DataFields.Add(pivotTable.Fields["PessimisticScenario - Percent"]);
    pessimisticField.Function = DataFieldFunctions.Average;
    pessimisticField.Format = "0.00%";
    var mediumField = pivotTable.DataFields.Add(pivotTable.Fields["MediumScenario - Percent"]);
    mediumField.Function = DataFieldFunctions.Average;
    mediumField.Format = "0.00%";
    var optimisticField = pivotTable.DataFields.Add(pivotTable.Fields["optimisticScenario - Percent"]);
    optimisticField.Function = DataFieldFunctions.Average;
    optimisticField.Format = "0.00%";

    // remove subtotals, this has to be done _after_ adding the field (see https://stackoverflow.com/a/34768357/5909613)
    foreach (ExcelPivotTableField rowField in pivotTable.RowFields)
    {
        rowField.SubTotalFunctions = eSubTotalFunctions.None;
    }
    return pivotWorksheet;
}
</code>```

答:
try to change Values Row filed to column. Here 3 is Values filed index.</p>

```<code>  PivotField row = (PivotField)oPivotTable.RowFields[3];
  row.Orientation = XlPivotFieldOrientation.xlColumnField;
</code>```

ContentLicense: CC BY-SA 4.0

Title: EPPlus: Values in column of pivot table

Body:
When you create a pivot table in Excel and add fields to Rows and Values, you get an additional field [Symbol Sigma] Values in the GUI, that you can drag and drop to Columns.

I am creating a pivot table using EPPlus. How can I add this [Symbol Sigma] Values field to my column fields?

Edit: Here is some code. I dont' see how this is supposed to help, what it was asked for.

private static ExcelWorksheet CreatePivotWorksheet(ExcelPackage excel, ExcelWorksheet dataWorksheet)
{
    string worksheetName = "Pivot";

    ExcelWorksheet pivotWorksheet = excel.Workbook.Worksheets.Add(worksheetName);

    ExcelRangeBase dataRange = dataWorksheet.Cells[dataWorksheet.Dimension.Address];
    ExcelPivotTable pivotTable = pivotWorksheet.PivotTables.Add(pivotWorksheet.Cells[1,1], dataRange, "pivotTable");

    pivotTable.RowGrandTotals = false;

    pivotTable.RowFields.Add(pivotTable.Fields["BaseValue"]);
    pivotTable.RowFields.Add(pivotTable.Fields["Remaining Runtime"])
        .AddNumericGrouping(0, 500000, 30);
    pivotTable.RowFields.Add(pivotTable.Fields["Emittent"]);
    pivotTable.RowFields.Add(pivotTable.Fields["CountIfs"]);
    pivotTable.RowFields.Add(pivotTable.Fields["ISIN"]);

    var stressField = pivotTable.DataFields.Add(pivotTable.Fields["StressScenario - Percent"]);
    stressField.Function = DataFieldFunctions.Average;
    stressField.Format = "0.00%";
    var pessimisticField = pivotTable.DataFields.Add(pivotTable.Fields["PessimisticScenario - Percent"]);
    pessimisticField.Function = DataFieldFunctions.Average;
    pessimisticField.Format = "0.00%";
    var mediumField = pivotTable.DataFields.Add(pivotTable.Fields["MediumScenario - Percent"]);
    mediumField.Function = DataFieldFunctions.Average;
    mediumField.Format = "0.00%";
    var optimisticField = pivotTable.DataFields.Add(pivotTable.Fields["optimisticScenario - Percent"]);
    optimisticField.Function = DataFieldFunctions.Average;
    optimisticField.Format = "0.00%";

    // remove subtotals, this has to be done _after_ adding the field (see https://stackoverflow.com/a/34768357/5909613)
    foreach (ExcelPivotTableField rowField in pivotTable.RowFields)
    {
        rowField.SubTotalFunctions = eSubTotalFunctions.None;
    }
    return pivotWorksheet;
}

Body:
try to change Values Row filed to column. Here 3 is Values filed index.

  PivotField row = (PivotField)oPivotTable.RowFields[3];
  row.Orientation = XlPivotFieldOrientation.xlColumnField;


问:
Math domain error with calculating discriminate
My program is solving quadratic equations that the user inputs with their a, b and c values. The issue is with my compute_discriminate function. I thought it was because you cannot take the square root of a negative number, so I said if d is negative, say there is no solution. However, I am getting an error in line 56, saying
x1 = (-b + math.sqrt(d)) / (2 * a)
ValueError: math domain error

Help with this situation would be extremely helpful, Python is new to me and I am wanting to get this to work!

Tried saying if d is negative, say there is no solution before defining x1 and x2.

```<code>a = 0
b = 0
c = 0
import math

def evaluate_quad_function(a, b, c, x):
    f_of_x = a * (x ** 2) + (b * x) + c
    return f_of_x  # return the calculated result

print("Welcome to the Quadratic Solver for f(x)=ax^2+bx+c")
a = input("Enter Value for a:")
b = input("Enter Value for b:")
c = input("Enter Value for c:")
# cannot do math on string, convert to float
a = float(a)
b = float(b)
c = float(c)
f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

def print_sign(x):
    # check the sign if positive or negative
    return '+' if x > 0 else '-'

if a == 1:
    print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")
if b == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
if c == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")

x = input("Enter Value for x:")
x = float(x)

fx = evaluate_quad_function(a, b, c, x)
print("F" + "(" + str(x) + ")""=", str(fx))
temp = input("\nPress Enter to continue...")  # wait

x0 = -b / (2 * a)
x0 = float(x0)
if a > 0:
    print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
else:
    print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
temp = input("\nPress Enter to continue...")  # wait

def compute_discriminate():
    print("Solving for f(x) = 0")
    d = (b ** 2) - (4 * a * c)
    if d < 0:
        print("No real solution.")
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print("Discriminant is", str(d))
    if d > 0:
        (print("Two Real Solutions", str(x1), "and", str(x2)))

    if d == 0:
        print("One real solution:", str(x0))

print(compute_discriminate())
</code>```

答:
Untietled123 is absolutely right, or you could do this:

```<code>assert d>=0
</code>```

assert means that the function has to be true
otherwise, it raises an error

if you want to make it come with a message, you could do:

```<code>try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))
</code>```

it is pretty handy in situations where there is a huge chunk of code after this and you want the code to end right when it come across that error.

this way you don't have to exit the loop or anything

also, in the end there

```<code>print(compute_discriminate())
</code>```

you don't need to print the function, I guess you never realized cos you get an error every time before it is completed :)

hope it helps :)

here's a version where you can solve equations multiple times, I tweaked it a bit

Untietled123 is absolutely right, or you could do this:

```<code>assert d>=0
</code>```

assert means that the function has to be true
otherwise, it raises an error

if you want to make it come with a message, you could do:

```<code>try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))
</code>```

it is pretty handy in situations where there is a huge chunk of code after this and you want the code to end right when it come across that error.

this way you don't have to exit the loop or anything

also, in the end there

```<code>print(compute_discriminate())
</code>```

you don't need to print the function, I guess you never realized cos you get an error every time before it is completed :)

hope it helps :)

EDIT: here's a version where you can solve equations multiple times, I tweaked it a bit e.g got rid of the pauses, but you can still get them back if you want

```<code>import math

print('Credit to Adam Hermon from stack overflow')
'''asked a question, I fixed his code and now I'm using it '''
print("Welcome to the Quadratic Solver for")
print('f(x)=ax^2+bx+c')
done = False
while not done:
    a = input("Enter Value for a:")
    b = input("Enter Value for b:")
    c = input("Enter Value for c:")
    # cannot do math on string, convert to float
    a = float(a)
    b = float(b)
    c = float(c)
    f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

    def evaluate_quad_function(a, b, c, x):
        f_of_x = a * (x ** 2) + (b * x) + c
        return f_of_x  # return the calculated result

    def print_sign(x):
        # check the sign if positive or negative
        return '+' if x > 0 else '-'

    if a == 1:
        print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x",
        print_sign(c), abs(c), sep="")
    if b == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ",
        print_sign(c), abs(c), sep="")
    if c == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b),
              "x", print_sign(c), abs(c), sep="")

    x = input("Enter Value for x:")
    x = float(x)

    fx = evaluate_quad_function(a, b, c, x)
    print("F" + "(" + str(x) + ")""=", str(fx))
    ##temp = input("\nPress Enter to continue...")  # wait

    x0 = -b / (2 * a)
    x0 = float(x0)
    if a > 0:
        print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" +
            str(f_x0))
    else:
        print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" +
            str(f_x0))
    ##temp = input("\nPress Enter to continue...")  # wait

    def compute_discriminate():
    ##    print("Solving for f(x) = 0")
        d = (b ** 2) - (4 * a * c)
        if d < 0 :
            print('No Real Solutions')
            return 'bad'
        x1 = (-b + math.sqrt(d)) / (2 * a)
        x2 = (-b - math.sqrt(d)) / (2 * a)
        print("Discriminant(the stuff under the sqrt sign) is", str(d))
        if d > 0:
            (print("Two Real Solutions", str(x1), "and", str(x2)))

        if d == 0:
            print("One real solution:", str(x0))

    compute_discriminate()
    print('')
    print('Another one? Press enter')
    i = input('if not, type no')
    if i == 'no' or i == 'No' or i == 'NO':
        done = True
    else:
        print('Solving another equation:')
</code>```

Body:
My program is solving quadratic equations that the user inputs with their a, b and c values. The issue is with my compute_discriminate function. I thought it was because you cannot take the square root of a negative number, so I said if d is negative, say there is no solution. However, I am getting an error in line 56, saying
x1 = (-b + math.sqrt(d)) / (2 * a)
ValueError: math domain error

Help with this situation would be extremely helpful, Python is new to me and I am wanting to get this to work!

Tried saying if d is negative, say there is no solution before defining x1 and x2.

a = 0
b = 0
c = 0
import math

def evaluate_quad_function(a, b, c, x):
    f_of_x = a * (x ** 2) + (b * x) + c
    return f_of_x  # return the calculated result

print("Welcome to the Quadratic Solver for f(x)=ax^2+bx+c")
a = input("Enter Value for a:")
b = input("Enter Value for b:")
c = input("Enter Value for c:")
# cannot do math on string, convert to float
a = float(a)
b = float(b)
c = float(c)
f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

def print_sign(x):
    # check the sign if positive or negative
    return '+' if x > 0 else '-'

if a == 1:
    print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")
if b == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
if c == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")

x = input("Enter Value for x:")
x = float(x)

fx = evaluate_quad_function(a, b, c, x)
print("F" + "(" + str(x) + ")""=", str(fx))
temp = input("\nPress Enter to continue...")  # wait

x0 = -b / (2 * a)
x0 = float(x0)
if a > 0:
    print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
else:
    print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
temp = input("\nPress Enter to continue...")  # wait

def compute_discriminate():
    print("Solving for f(x) = 0")
    d = (b ** 2) - (4 * a * c)
    if d < 0:
        print("No real solution.")
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print("Discriminant is", str(d))
    if d > 0:
        (print("Two Real Solutions", str(x1), "and", str(x2)))

    if d == 0:
        print("One real solution:", str(x0))

print(compute_discriminate())

Body:
Untietled123 is absolutely right, or you could do this:

assert d>=0

assert means that the function has to be true
otherwise, it raises an error

if you want to make it come with a message, you could do:

try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))

it is pretty handy in situations where there is a huge chunk of code after this and you want the code to end right when it come across that error.

this way you don't have to exit the loop or anything

also, in the end there

print(compute_discriminate())

you don't need to print the function, I guess you never realized cos you get an error every time before it is completed :)

hope it helps :)

here's a version where you can solve equations multiple times, I tweaked it a bit

Untietled123 is absolutely right, or you could do this:

assert d>=0

assert means that the function has to be true
otherwise, it raises an error

if you want to make it come with a message, you could do:

try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))

it is pretty handy in situations where there is a huge chunk of code after this and you want the code to end right when it come across that error.

this way you don't have to exit the loop or anything

also, in the end there

print(compute_discriminate())

you don't need to print the function, I guess you never realized cos you get an error every time before it is completed :)

hope it helps :)

EDIT: here's a version where you can solve equations multiple times, I tweaked it a bit e.g got rid of the pauses, but you can still get them back if you want

import math

print('Credit to Adam Hermon from stack overflow')
'''asked a question, I fixed his code and now I'm using it '''
print("Welcome to the Quadratic Solver for")
print('f(x)=ax^2+bx+c')
done = False
while not done:
    a = input("Enter Value for a:")
    b = input("Enter Value for b:")
    c = input("Enter Value for c:")
    # cannot do math on string, convert to float
    a = float(a)
    b = float(b)
    c = float(c)
    f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

    def evaluate_quad_function(a, b, c, x):
        f_of_x = a * (x ** 2) + (b * x) + c
        return f_of_x  # return the calculated result

    def print_sign(x):
        # check the sign if positive or negative
        return '+' if x > 0 else '-'

    if a == 1:
        print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x",
        print_sign(c), abs(c), sep="")
    if b == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ",
        print_sign(c), abs(c), sep="")
    if c == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b),
              "x", print_sign(c), abs(c), sep="")

    x = input("Enter Value for x:")
    x = float(x)

    fx = evaluate_quad_function(a, b, c, x)
    print("F" + "(" + str(x) + ")""=", str(fx))
    ##temp = input("\nPress Enter to continue...")  # wait

    x0 = -b / (2 * a)
    x0 = float(x0)
    if a > 0:
        print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" +
            str(f_x0))
    else:
        print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" +
            str(f_x0))
    ##temp = input("\nPress Enter to continue...")  # wait

    def compute_discriminate():
    ##    print("Solving for f(x) = 0")
        d = (b ** 2) - (4 * a * c)
        if d < 0 :
            print('No Real Solutions')
            return 'bad'
        x1 = (-b + math.sqrt(d)) / (2 * a)
        x2 = (-b - math.sqrt(d)) / (2 * a)
        print("Discriminant(the stuff under the sqrt sign) is", str(d))
        if d > 0:
            (print("Two Real Solutions", str(x1), "and", str(x2)))

        if d == 0:
            print("One real solution:", str(x0))

    compute_discriminate()
    print('')
    print('Another one? Press enter')
    i = input('if not, type no')
    if i == 'no' or i == 'No' or i == 'NO':
        done = True
    else:
        print('Solving another equation:')


问:
Should I keep a global shared component, or using one per child?

My App:

I am implementing a React Native application where a FlatList is used to display each item fullscreen. Each may contain/display several things, like Text, Images, GIFs. Also, some sound/song may be played. Think of this like a "enhanced" gallery/carousel.

My actual implementation is something like:

```<code>
export default class App extends React.PureComponent {

    this.state = {
      currentIndex: null //currentIndex gets updated when displayed FlatList item changes
    };

   // Black magic here to update currentIndex

   render() {
      const data = [{image: "...", text: "...", sound: "..."}, {...},...]
      return (
          <FlatList
            data = {data}
            renderItem={({ item, index }) => {
              const isDisplayed = this.state.currentIndex === index;
              return <Thing {...item} isDisplayed={isDisplayed} />;
            }}
            ...
          />
   }
}
</code>```

The Thing component is something similar to:

```<code>export default class Thing extends React.PureComponent {
  render() {
    if (this.props.isDisplayed){
       <SoundComponent sound={this.props.sound}/>
       <View>
            <Text> this.props.text</Text>
            <Image> this.props.image</Image>
       </View>
    }

}
</code>```

My question:

Should I keep one SoundComponent per Thing, or should I use one global SoundComponent managed by and inside App? On one side I think that App should be unaware of how data is used, on the other side one centralized SoundComponent seems easier to orchestrate one sound at the time.

Notice that only one sound can be played at the same time.

答:
There isn't any kind of "global" component in React. Every component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:

1) Create a Higher Order Component that renders the PageContent and the wrapped component.

```<code>import PageContent from './PageContent';

const withPageContent = WrappedComponent => {
  return class extends React.Component {
    render () {
      return (
        <PageContent>
          <WrappedComponent />
        </PageContent>
      )
    }
  }
};

export default withPageContent;
</code>```

// Usage

```<code>import withPageContent from './withPageContent';

class MyComponent extends React.Component {
  render () {
    return (
      <div>
        I'm wrapped in PageContent!
      </div>
    )
  }
}

export default withPageContent(MyComponent);
</code>```

2) Pass PageContent as a prop to a component:

```<code>import PageContent from './PageContent';

export default class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Child1 content={PageContent} />
        <Child2 content={PageContent} />
      </React.Fragment>
    )
  }
}
</code>```

// Usage

```<code>export default class Child1 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}

export default class Child2 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}
</code>```

Body:
My App:

I am implementing a React Native application where a FlatList is used to display each item fullscreen. Each may contain/display several things, like Text, Images, GIFs. Also, some sound/song may be played. Think of this like a "enhanced" gallery/carousel.

My actual implementation is something like:

export default class App extends React.PureComponent {

    this.state = {
      currentIndex: null //currentIndex gets updated when displayed FlatList item changes
    };

   // Black magic here to update currentIndex

   render() {
      const data = [{image: "...", text: "...", sound: "..."}, {...},...]
      return (
          <FlatList
            data = {data}
            renderItem={({ item, index }) => {
              const isDisplayed = this.state.currentIndex === index;
              return <Thing {...item} isDisplayed={isDisplayed} />;
            }}
            ...
          />
   }
}

The Thing component is something similar to:

export default class Thing extends React.PureComponent {
  render() {
    if (this.props.isDisplayed){
       <SoundComponent sound={this.props.sound}/>
       <View>
            <Text> this.props.text</Text>
            <Image> this.props.image</Image>
       </View>
    }

}

My question:

Should I keep one SoundComponent per Thing, or should I use one global SoundComponent managed by and inside App? On one side I think that App should be unaware of how data is used, on the other side one centralized SoundComponent seems easier to orchestrate one sound at the time.

Notice that only one sound can be played at the same time.

Body:
There isn't any kind of "global" component in React. Every component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:

1) Create a Higher Order Component that renders the PageContent and the wrapped component.

import PageContent from './PageContent';

const withPageContent = WrappedComponent => {
  return class extends React.Component {
    render () {
      return (
        <PageContent>
          <WrappedComponent />
        </PageContent>
      )
    }
  }
};

export default withPageContent;

// Usage

import withPageContent from './withPageContent';

class MyComponent extends React.Component {
  render () {
    return (
      <div>
        I'm wrapped in PageContent!
      </div>
    )
  }
}

export default withPageContent(MyComponent);

2) Pass PageContent as a prop to a component:

import PageContent from './PageContent';

export default class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Child1 content={PageContent} />
        <Child2 content={PageContent} />
      </React.Fragment>
    )
  }
}

// Usage

export default class Child1 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}

export default class Child2 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}


问:
How to pass parameters in headers
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

```<code>checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}
</code>```

In Node,

```<code>router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });
</code>```

答:
You can do it by using interceptors which is Angular Service.
this should be helpfull :How to pass a param to HttpInterceptor?</p>

Title: How to pass parameters in headers

Body:
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}

In Node,

router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });


问:
Full Calendar - not implementing time dynamic input
I am dynamically implementing the events in calendar using javascript.

Let me tell you how it actually build

Clicking a button opens a  BS 4 modal.

Modal container daterangepicker ( I am using it just for date not for time )

For selection of time I have added custom select options.

add event fields name, description etc.

after clicking the add button modal disapper and the event is successfully add.

So what's the problem.

The problem is when I statically add the event it gets me this ( The expected result );

But,,

When I try to do it dynamically it gets me this ( Non Expected result );

So to know that my time is implementing I have used eventClick(); which is in-built in fullcalendar

```<code>eventClick: function(info) {
    console.log(info);
    console.log(info.start._i);
    console.log(info.end._i);
}
</code>```

info.start._i get the date with time as expected and info.end._i get the date with time as expected. So why I am getting non expected result.

答: So I have figured it out the issue is allDay is true is should be set to false

Body:
I am dynamically implementing the events in calendar using javascript.

Let me tell you how it actually build

Clicking a button opens a  BS 4 modal.

Modal container daterangepicker ( I am using it just for date not for time )

For selection of time I have added custom select options.

add event fields name, description etc.

after clicking the add button modal disapper and the event is successfully add.

So what's the problem.

The problem is when I statically add the event it gets me this ( The expected result );

But,,

When I try to do it dynamically it gets me this ( Non Expected result );

So to know that my time is implementing I have used eventClick(); which is in-built in fullcalendar

eventClick: function(info) {
    console.log(info);
    console.log(info.start._i);
    console.log(info.end._i);
}

info.start._i get the date with time as expected and info.end._i get the date with time as expected. So why I am getting non expected result.


问:
CollectionView with height equal to max height of CustomCell in Swift
I am trying to have collection view(horizontal/vertical) with some height. Inside this, I have custom cells with many subviews(ex:image, title, description, last updated etc. ).

Now I want all cells to maintain same height which is the max height of all cells(based on data). (Each Cell height = Cell with max height)

I am able to create dynamic height cell but could not understand where to put the max height logic.

Currently I have following code

ViewController

```<code>lazy var flowLayout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal // .vertical
    layout.minimumInteritemSpacing = 10

    return layout
}()

lazy var collectionView: UICollectionView = {
    let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
    cv.backgroundColor = .white

    return cv
}()

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let targetWidth = collectionView.bounds
        .inset(collectionView.contentInset)
        .inset(flowLayout.sectionInset)
        .width

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SampleCell
    cell.configure(data: randomTexts[indexPath.row])

    let size = cell.systemLayoutSizeFitting(
        .init(width: targetWidth, height: 0),
        withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)

    return size
}
</code>```

SampleCell : UICollectionViewCell

```<code>override func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
                                       verticalFittingPriority: UILayoutPriority) -> CGSize {

    let contentSize = contentView.systemLayoutSizeFitting(
        targetSize,
        withHorizontalFittingPriority: horizontalFittingPriority,
        verticalFittingPriority: verticalFittingPriority)

    return contentSize.withWidth(targetSize.width)
}
</code>```

Extensions

```<code>extension CGRect {
func inset(_ insets: UIEdgeInsets) -> CGRect {
    return self.inset(by: insets)
}}
</code>```

Where will max height logic goes: ViewController or SampleCell and how to achieve the same?

Note: Also looking on how to do this for horizontal/vertical scrolling( collection with some height(and adjust a/c to the cell content) inside a viewcontroller)

答: Inside the collectionView(_:layout:sizeForItemAt:) method, return the max height here.

Body:
I am trying to have collection view(horizontal/vertical) with some height. Inside this, I have custom cells with many subviews(ex:image, title, description, last updated etc. ).

Now I want all cells to maintain same height which is the max height of all cells(based on data). (Each Cell height = Cell with max height)

I am able to create dynamic height cell but could not understand where to put the max height logic.

Currently I have following code

ViewController

lazy var flowLayout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal // .vertical
    layout.minimumInteritemSpacing = 10

    return layout
}()

lazy var collectionView: UICollectionView = {
    let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
    cv.backgroundColor = .white

    return cv
}()

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let targetWidth = collectionView.bounds
        .inset(collectionView.contentInset)
        .inset(flowLayout.sectionInset)
        .width

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SampleCell
    cell.configure(data: randomTexts[indexPath.row])

    let size = cell.systemLayoutSizeFitting(
        .init(width: targetWidth, height: 0),
        withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)

    return size
}

SampleCell : UICollectionViewCell

override func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
                                       verticalFittingPriority: UILayoutPriority) -> CGSize {

    let contentSize = contentView.systemLayoutSizeFitting(
        targetSize,
        withHorizontalFittingPriority: horizontalFittingPriority,
        verticalFittingPriority: verticalFittingPriority)

    return contentSize.withWidth(targetSize.width)
}

Extensions

extension CGRect {
func inset(_ insets: UIEdgeInsets) -> CGRect {
    return self.inset(by: insets)
}}

Where will max height logic goes: ViewController or SampleCell and how to achieve the same?

Note: Also looking on how to do this for horizontal/vertical scrolling( collection with some height(and adjust a/c to the cell content) inside a viewcontroller)


问:
php artisan queue not showing anything
I'm using laravel 5.0 and trying to set a queue for sending an email, I have created it and wrote code like.
Queue::pushOn('emails', new SendEmail($user));

It's adding a row in the jobs table, then I'm running the following command

$ php artisan queue:listen

But it is not showing anything and not sending emails too.

答:
Hay, I had this same issue,
I had an error in my job code that's why it's stuck in queue:listen , to make sure there is no error in your job code.

you can put the following check in job handle() methfor the error.

```<code>public function handle()
{
  try{
   // your code here.
  } catch (\Exception $e) {
      dd($e->getMessage());
  }
}
</code>```

then run.

$ php artisan queue:listen emails

Now, if there is an error in your code the error will display in the command line.
Hope this can help you.

Title: php artisan queue not showing anything

Body:
Hay, I had this same issue,
I had an error in my job code that's why it's stuck in queue:listen , to make sure there is no error in your job code.

you can put the following check in job handle() methfor the error.

public function handle()
{
  try{
   // your code here.
  } catch (\Exception $e) {
      dd($e->getMessage());
  }
}

then run.

$ php artisan queue:listen emails

Now, if there is an error in your code the error will display in the command line.
Hope this can help you.


问:
AWS AppSync - How to query data by date range(Today to 30 days before)?
This is how my schema.graphql looks like.

```<code>type Post
  @model
  @auth(
    rules: [
      { allow: owner }
    ]
  ) {
  id: ID!
  author: User! @connection(name: "UserPosts")
  content: AWSJSON!
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
}
</code>```

Which generated GraphQL query showing below

```<code>export const listPosts = `query listPosts(
  $filter: ModelPostFilterInput
  $limit: Int
  $nextToken: String
) {
  listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
    items {
      id
      author {
        id
        uuid
      }
      content
      createdAt
      updatedAt
    }
    nextToken
  }
}
`;
</code>```

I'm calling listPosts to query list of Posts but not sure how to implement date range into below query that I'm using to get data.

await API.graphql(graphqlOperation(queries.listPosts, {limit: 10, nextToken: nextToken}))

Is it possible to add two strings start: TODAY and end: 30 DAYS BEFORE TODAY to the query above and get it returns 30 latest posts?

答: Check out the new @key directive: https://aws-amplify.github.io/docs/cli/graphql#key</p>

Body:
This is how my schema.graphql looks like.

type Post
  @model
  @auth(
    rules: [
      { allow: owner }
    ]
  ) {
  id: ID!
  author: User! @connection(name: "UserPosts")
  content: AWSJSON!
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
}

Which generated GraphQL query showing below

export const listPosts = `query listPosts(
  $filter: ModelPostFilterInput
  $limit: Int
  $nextToken: String
) {
  listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
    items {
      id
      author {
        id
        uuid
      }
      content
      createdAt
      updatedAt
    }
    nextToken
  }
}
`;

I'm calling listPosts to query list of Posts but not sure how to implement date range into below query that I'm using to get data.

await API.graphql(graphqlOperation(queries.listPosts, {limit: 10, nextToken: nextToken}))

Is it possible to add two strings start: TODAY and end: 30 DAYS BEFORE TODAY to the query above and get it returns 30 latest posts?


问:
attached 'property was already registered by' my generic BaseAttachedProperty class causes design time exception
I'm developing an engineering application for work in WPF with VB.net and have a base class for attached properties which is based on Angel Six's code in C#.  My base attached property is working fine at run time as the application executes without any problems, but for some reason the Visual Studio 2017 design time has suddenly started throwing exceptions on all of my attached properties giving the error, 'Value' property is already registered by 'BaseAttachedProperty'2_1_190297300'. This makes designing any further UI rather challenging.

My problems started when I introduced a dependency object on a custom user control which would fire off an update event whenever it was updated and then manually update the data context of the custom control. This allowed the custom control to update the main page in which it was created.

I've since deleted the custom user control and the dependency object, but the problem still remains.  I've then closed my solution, closed Visual Studio, deleted the bin and obj folders and restarted, but the problem persists.

I've searched the internet and stack overflow extensively for the last few days, but haven't been able to find a solution, which is unusual because up to until now I've always been able to solve any problems I've had by google searching.  While the 'property is already registered by' error seems to be a common one, the solution to the problems associated with this error seems to be different in all cases.

This is my base attached property with the standard get/set value code removed, along with the overridable event methods...

Public MustInherit Class BaseAttachedProperty(Of Parent As {BaseAttachedProperty(Of Parent, [Property]), New}, [Property])

    Private Shared defaultVal As [Property] = Nothing

#Region "Public Events"

#End Region

#Region "Public Properties"

    Public Shared Property Instance As Parent = New Parent()

#End Region

#Region "Attached Property Definitions"

    Public Shared ReadOnly ValueProperty As DependencyProperty = DependencyProperty.RegisterAttached(
        "Value",
        GetType([Property]),
        GetType(BaseAttachedProperty(Of Parent, [Property])),
        New UIPropertyMetadata(defaultVal,
                               New PropertyChangedCallback(AddressOf OnValuePropertyChanged),
                               New CoerceValueCallback(AddressOf OnValuePropertyUpdated)))

    Private Shared Sub OnValuePropertyChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.OnValueChanged(d, e)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.ValueChanged(d, e)

    End Sub

    Private Shared Function OnValuePropertyUpdated(d As DependencyObject, value As Object) As Object

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.OnValueUpdated(d, value)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.ValueUpdated(d, value)

        Return value

    End Function
```

<p>The code for an attached property which then does no more than pass a static value is then as follows...</p>

<pre class="lang-vb prettyprint-override"><code>Public Class ControlTitleProperty
    Inherits BaseAttachedProperty(Of ControlTitleProperty, String)

End Class
</code>```

The attached properties are then called in xaml as you would expect...

<TextBox Text="{Binding PhasePageViewModel.ViscosityValue,
                                                    Source={x:Static local:ViewModelLocator.Instance},
                                                    UpdateSourceTrigger=PropertyChanged,
                                                    ValidatesOnDataErrors=True,
                                                    Mode=TwoWay}"
                                     Style="{StaticResource ValueAndUnitsBox}"
                                     local:NumericInputProperty.Value="True"
                                     local:ControlTitleProperty.Value="Viscosity"
                                     local:ControlDescriptionProperty.Value="The viscosity of this phase and the associated units"/>
```

Since I'm using the attached properties in most of my resource dictionaries, the design time isn't working properly anywhere in my project, so I'd really appreciate some help fixing it.  I've been scratching my head for the last few days with it, but to no avail.

答:
After a lot of head scratching and help from Phil to make sure that my base attached property class was as close as possible to the original C# code I ended up gradually re-building my user interface in a new project piece by piece, starting with the attached properties. After adding each class to the new project as an existing item from the old project I would clean and build the project to see if that broke the Visual Studio designer.  To my surprise, none of my code managed to break the designer and what I ended up with was a carbon copy of my old project but now with the designer in Visual Studio working again.

I can only surmise that when I introduced my custom dependency property for the data context of my custom control, I managed to break the designer in a way that couldn't be undone by simply deleting the offending code and then re-building. This blog post by Travis Illig alludes to a "shadow cache" that is used by the designer to render the design time appearance of your UI within Visual Studio.  I believe that this is what I managed to break.

It's taken me a number of painstaking days to rebuild my project, days that I could have saved if I'd have had a recent back up of my project.  So just in case this problem pops up again in the future, I'm going to back my project up on a regular basis!

Body:
I'm developing an engineering application for work in WPF with VB.net and have a base class for attached properties which is based on Angel Six's code in C#.  My base attached property is working fine at run time as the application executes without any problems, but for some reason the Visual Studio 2017 design time has suddenly started throwing exceptions on all of my attached properties giving the error, 'Value' property is already registered by 'BaseAttachedProperty'2_1_190297300'. This makes designing any further UI rather challenging.

My problems started when I introduced a dependency object on a custom user control which would fire off an update event whenever it was updated and then manually update the data context of the custom control. This allowed the custom control to update the main page in which it was created.

I've since deleted the custom user control and the dependency object, but the problem still remains.  I've then closed my solution, closed Visual Studio, deleted the bin and obj folders and restarted, but the problem persists.

I've searched the internet and stack overflow extensively for the last few days, but haven't been able to find a solution, which is unusual because up to until now I've always been able to solve any problems I've had by google searching.  While the 'property is already registered by' error seems to be a common one, the solution to the problems associated with this error seems to be different in all cases.

This is my base attached property with the standard get/set value code removed, along with the overridable event methods...

Public MustInherit Class BaseAttachedProperty(Of Parent As {BaseAttachedProperty(Of Parent, [Property]), New}, [Property])

    Private Shared defaultVal As [Property] = Nothing

#Region "Public Events"

#End Region

#Region "Public Properties"

    Public Shared Property Instance As Parent = New Parent()

#End Region

#Region "Attached Property Definitions"

    Public Shared ReadOnly ValueProperty As DependencyProperty = DependencyProperty.RegisterAttached(
        "Value",
        GetType([Property]),
        GetType(BaseAttachedProperty(Of Parent, [Property])),
        New UIPropertyMetadata(defaultVal,
                               New PropertyChangedCallback(AddressOf OnValuePropertyChanged),
                               New CoerceValueCallback(AddressOf OnValuePropertyUpdated)))

    Private Shared Sub OnValuePropertyChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.OnValueChanged(d, e)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.ValueChanged(d, e)

    End Sub

    Private Shared Function OnValuePropertyUpdated(d As DependencyObject, value As Object) As Object

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.OnValueUpdated(d, value)

        TryCast(Instance, BaseAttachedProperty(Of Parent, [Property]))?.ValueUpdated(d, value)

        Return value

    End Function

The code for an attached property which then does no more than pass a static value is then as follows...

Public Class ControlTitleProperty
    Inherits BaseAttachedProperty(Of ControlTitleProperty, String)

End Class

The attached properties are then called in xaml as you would expect...

<TextBox Text="{Binding PhasePageViewModel.ViscosityValue,
                                                    Source={x:Static local:ViewModelLocator.Instance},
                                                    UpdateSourceTrigger=PropertyChanged,
                                                    ValidatesOnDataErrors=True,
                                                    Mode=TwoWay}"
                                     Style="{StaticResource ValueAndUnitsBox}"
                                     local:NumericInputProperty.Value="True"
                                     local:ControlTitleProperty.Value="Viscosity"
                                     local:ControlDescriptionProperty.Value="The viscosity of this phase and the associated units"/>

Since I'm using the attached properties in most of my resource dictionaries, the design time isn't working properly anywhere in my project, so I'd really appreciate some help fixing it.  I've been scratching my head for the last few days with it, but to no avail.


问:
Why I cannot see line numbers in gdb backtrace?
I cannot see line numbers in gdb. I have compiled everything with -g flags with mpiicc.

gdb is not showing line numbers even for breakpoints for me.

May be the problem is in "Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64" but I am not a superuser so I cannot install these.

```<code> gdb  --args ./central -g 5 51
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-83.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central...done.
(gdb) break direct.c:55
Breakpoint 1 at 0x40855d: file direct.c, line 55.
(gdb) l direct.c:55
50
51  void direct(int* N, double **PA, Coord **points)
52  {
53      int     i ,j ,k ,l, ir, irr,
54              md = suma(N , NUM_AIRFOILS) - NUM_AIRFOILS,
55              m;
56      double  *D, // **D,
57              *A, *sv;
58
59      int matrix_size_D = md*md;
(gdb) r
Starting program: /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central -g 5 51
[Thread debugging using libthread_db enabled]

Breakpoint 1, 0x000000000040855d in direct ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64
(gdb) bt
#0  0x000000000040855d in direct ()
#1  0x0000000000405ee9 in main ()
(gdb) s
Single stepping until exit from function direct,
which has no line number information.
PMPI_Comm_size (comm=1140850688, size=0x7fffffffc240) at ../../src/mpi/comm/comm_size.c:57
57  ../../src/mpi/comm/comm_size.c: No such file or directory.
    in ../../src/mpi/comm/comm_size.c
(gdb) s
65  in ../../src/mpi/comm/comm_size.c
(gdb) s
57  in ../../src/mpi/comm/comm_size.c
(gdb)
58  in ../../src/mpi/comm/comm_size.c
(gdb)
59  in ../../src/mpi/comm/comm_size.c
(gdb)
65  in ../../src/mpi/comm/comm_size.c
(gdb)
</code>```

Here is the build commands as well:

```<code>mpiicc -g -c -o central.o central.c -qopenmp
mpiicc -g -c -o contours.o contours.c -qopenmp
mpiicc -g -c -o mymath.o mymath.c -qopenmp
mpiicc -g -c -o vort.o vort.c -qopenmp
mpiicc -g -qopenmp   -I/opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/include -c -o  direct.o direct.c
mpiicc -g -c -o a_liftarg.o a_liftarg.c -qopenmp
mpiicc -g -c -o psavel.o psavel.c -qopenmp
mpiicc -g -c -o euler.o euler.c -qopenmp
mpiicc -g -c -o streamline.o streamline.c -qopenmp
mpiicc -g -c -o speedmap.o speedmap.c -qopenmp
mpiicc -g -o central central.o contours.o mymath.o vort.o direct.o a_liftarg.o psavel.o euler.o streamline.o speedmap.o /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_scalapack_lp64.a -Wl,--start-group /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_lp64.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_thread.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_core.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a -Wl,--end-group -liomp5 -lpthread -lm -ldl -qopenmp
</code>```

答:
May be the problem is

No: the problem is not that (neither main, not direct are defined in libc).

This appears to be a bug in GDB: before you execute run, it clearly knows that the address 0x40855d corresponds to direct.c, line 55.

But after run, it somehow forgets that it knew this.

Your version of GDB is also 9 years old. As the first step, I suggest building a current version (8.3 as of today).

Body:
I cannot see line numbers in gdb. I have compiled everything with -g flags with mpiicc.

gdb is not showing line numbers even for breakpoints for me.

May be the problem is in "Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64" but I am not a superuser so I cannot install these.

 gdb  --args ./central -g 5 51
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-83.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central...done.
(gdb) break direct.c:55
Breakpoint 1 at 0x40855d: file direct.c, line 55.
(gdb) l direct.c:55
50
51  void direct(int* N, double **PA, Coord **points)
52  {
53      int     i ,j ,k ,l, ir, irr,
54              md = suma(N , NUM_AIRFOILS) - NUM_AIRFOILS,
55              m;
56      double  *D, // **D,
57              *A, *sv;
58
59      int matrix_size_D = md*md;
(gdb) r
Starting program: /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central -g 5 51
[Thread debugging using libthread_db enabled]

Breakpoint 1, 0x000000000040855d in direct ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64
(gdb) bt
#0  0x000000000040855d in direct ()
#1  0x0000000000405ee9 in main ()
(gdb) s
Single stepping until exit from function direct,
which has no line number information.
PMPI_Comm_size (comm=1140850688, size=0x7fffffffc240) at ../../src/mpi/comm/comm_size.c:57
57  ../../src/mpi/comm/comm_size.c: No such file or directory.
    in ../../src/mpi/comm/comm_size.c
(gdb) s
65  in ../../src/mpi/comm/comm_size.c
(gdb) s
57  in ../../src/mpi/comm/comm_size.c
(gdb)
58  in ../../src/mpi/comm/comm_size.c
(gdb)
59  in ../../src/mpi/comm/comm_size.c
(gdb)
65  in ../../src/mpi/comm/comm_size.c
(gdb)

Here is the build commands as well:

mpiicc -g -c -o central.o central.c -qopenmp
mpiicc -g -c -o contours.o contours.c -qopenmp
mpiicc -g -c -o mymath.o mymath.c -qopenmp
mpiicc -g -c -o vort.o vort.c -qopenmp
mpiicc -g -qopenmp   -I/opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/include -c -o  direct.o direct.c
mpiicc -g -c -o a_liftarg.o a_liftarg.c -qopenmp
mpiicc -g -c -o psavel.o psavel.c -qopenmp
mpiicc -g -c -o euler.o euler.c -qopenmp
mpiicc -g -c -o streamline.o streamline.c -qopenmp
mpiicc -g -c -o speedmap.o speedmap.c -qopenmp
mpiicc -g -o central central.o contours.o mymath.o vort.o direct.o a_liftarg.o psavel.o euler.o streamline.o speedmap.o /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_scalapack_lp64.a -Wl,--start-group /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_lp64.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_thread.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_core.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a -Wl,--end-group -liomp5 -lpthread -lm -ldl -qopenmp


问:
pagination and sorting on 'ngOnInit' is not working after placing my constructor
I have a mat-table using pagination and sorting, it works properly until I place my constructor: "constructor(private _router: Router){}". The table is still showing, but pagination and sorting doesn't. It shows everything all at once. I am new to angular and I'm having trouble identifying the problem.

I tried placing the contents on 'ngOnInit' on the constructor, and in still didn't seem to work.

```<code>export class LogsComponent implements OnInit {
  constructor(private _router: Router){} //If i place this, it works but pagination doesn't

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(EXAMPLE_DATA);
  displayedColumns = ['id', 'name', 'role', 'date'];

  applyFilter(filterValue: string, _router: Router) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}
</code>```

Here is my HTML code:

```<code>//The one I use on mg 'logs' page
<div *ngIf="_router.url == '/logs'">
   <div class="table">
      //table here
   </div>
</div>

//The on I use on the dashboard
<div *ngIf="_router.url != '/logs'">
   <div class="table">
      //table here
   </div>
</div>
</code>```

I'd like to know why is this not working, I've read from some pages that the constructor gets read first before the ngOnInit(). But its not working in my case, can someone point out what I'm doing wrong? Thank you very much!

答:
Firstly, I noticed that you have the _router variable private and you are trying to access from your view, the other thing that I noticed is your applyFilter function, I don't understand  why you are expecting a router parameter if you have it clearly in your class scope. But, back to your problem is your private router variable, try to change it to public.

When something in angular goes wrong, the next steps result interrupted and it's for that reason that your paginator and sort functions have interrupted.

You have to import the RouterModule in your AppModule previously.

Body:
I have a mat-table using pagination and sorting, it works properly until I place my constructor: "constructor(private _router: Router){}". The table is still showing, but pagination and sorting doesn't. It shows everything all at once. I am new to angular and I'm having trouble identifying the problem.

I tried placing the contents on 'ngOnInit' on the constructor, and in still didn't seem to work.

export class LogsComponent implements OnInit {
  constructor(private _router: Router){} //If i place this, it works but pagination doesn't

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(EXAMPLE_DATA);
  displayedColumns = ['id', 'name', 'role', 'date'];

  applyFilter(filterValue: string, _router: Router) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

Here is my HTML code:

//The one I use on mg 'logs' page

      //table here

//The on I use on the dashboard

      //table here

I'd like to know why is this not working, I've read from some pages that the constructor gets read first before the ngOnInit(). But its not working in my case, can someone point out what I'm doing wrong? Thank you very much!


问:
How to highlight strings in a file to download?
I have a text file "output.txt" which is an output of a shell command. I want to highlight certain words taken as $_GET['word'] in that file and then allow to download using href.

I have seen multiple questions but none of them seems to be working in this case.

Highlight multiple keywords from a given string

highlight the word in the string, if it contains the keyword

Code:

```<code>$cmd = shell_exec("/usr/local/bin/clustalw2 -infile=input.txt -tree -type=protein -case=upper &");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = $_GET['word'];
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, $content);
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";
</code>```

It is not giving any error neither highlighting the text.

答:
I suspect the trouble is with opening the initial file. The following did work for me.

I created /home/input.txt:

```<code>this is a test
that may
or may not work.
</code>```

Then ran:

$cmd = shell_exec(" cp /home/input.txt output.txt");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = "may";
$content = str_replace($keyword,''.$keyword.'',$content);
$file = file_put_contents($file, implode("\n", $content));
echo "Download Result file";
```

<p>And the output.txt is now:</p>

<pre class="lang-html prettyprint-override"><code>this is a test
that <span style="color:red">may</span>
or <span style="color:red">may</span> not work.
</code>```

Body:
I have a text file "output.txt" which is an output of a shell command. I want to highlight certain words taken as $_GET['word'] in that file and then allow to download using href.

I have seen multiple questions but none of them seems to be working in this case.

Highlight multiple keywords from a given string

highlight the word in the string, if it contains the keyword

Code:

$cmd = shell_exec("/usr/local/bin/clustalw2 -infile=input.txt -tree -type=protein -case=upper &");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = $_GET['word'];
$content = str_replace($keyword,''.$keyword.'',$content);
$file = file_put_contents($file, $content);
echo "Download Result file";

It is not giving any error neither highlighting the text.

Body:
I suspect the trouble is with opening the initial file. The following did work for me.

I created /home/input.txt:

this is a test
that may
or may not work.

Then ran:

$cmd = shell_exec(" cp /home/input.txt output.txt");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = "may";
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, implode("\n", $content));
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";

And the output.txt is now:

this is a test
that <span style="color:red">may</span>
or <span style="color:red">may</span> not work.


问:
Subarray assignment: initialization with "{...}" expected for aggregate object error
What's a good explanation for the error on Line 1?

```<code>/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];
</code>```

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.

答:
The initializer in an array definition (C-style array, that is) must be a braced list.

This rule covers both of your Line 1 and Line 2, where you provide something that isn't a braced list and therefore the code is incorrect.

Further information: when you do provide a braced list, then each element of the list is taken as the initializer for an element of the array.  As a corollary, it's not possible to supply a single initializer which causes multiple array elements to be set by it.

This rule nearly applies recursively; if you have an array of arrays, then the initializer should be a braced list of braced lists. However there is a rule that nested braces can be omitted in some cases (and the code will behave as if full bracing had been provided). For example int x[2][2] = { 1, 2, 3, 4 }; is allowed and behaves like int x[2][2] = { {1, 2}, {3, 4} };.

Body:
What's a good explanation for the error on Line 1?

/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.


问:
Do I need to use Shared Preferences if I want to retrieve data of the user after the user login?
I am currently learning to develop a mobile application using Android Studio. I have successfully done for the login activity. I would like to know whether I have to use Shared Preferences if I want to retrieve the data of the user after they login ?</p>

答:
Yes, you can use Shared Preference to store user's basic details(If it's not more complicated) like user id, display name and etc. And on logout of user, you need to clear all that stored informations.

You can consider below class as an example:

```<code>public class UserPrefManager {
    private static final String is_LOGIN = "is_user_login";
    private static final String USER_ID = "user_id";

    private SharedPreferences pref;

    private static final String MyPREFERENCES = "myPrefs";

    public UserPrefManager(Context context) {
        pref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    }

    public void setIsLogin(boolean value) {
        pref.edit().putBoolean(is_LOGIN, value).apply();
    }

    public boolean isLogin() {
        return pref.getBoolean(is_LOGIN, false);
    }

    public void setUserId(String value) {
        pref.edit().putString(USER_ID, value).apply();
    }

    public String getUserId(String defValue) {
        return pref.getString(USER_ID, defValue);
    }

    public void setBooleanValue(String key, Boolean value) {
        pref.edit().putBoolean(key, value).apply();
    }

    public boolean getBooleanValue(String key, Boolean defValue) {
        return pref.getBoolean(key, defValue);
    }

    public boolean clear() {
        return pref.edit().clear().commit();
    }

}
</code>```

Body:
Yes, you can use Shared Preference to store user's basic details(If it's not more complicated) like user id, display name and etc. And on logout of user, you need to clear all that stored informations.

You can consider below class as an example:

public class UserPrefManager {
    private static final String is_LOGIN = "is_user_login";
    private static final String USER_ID = "user_id";

    private SharedPreferences pref;

    private static final String MyPREFERENCES = "myPrefs";

    public UserPrefManager(Context context) {
        pref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    }

    public void setIsLogin(boolean value) {
        pref.edit().putBoolean(is_LOGIN, value).apply();
    }

    public boolean isLogin() {
        return pref.getBoolean(is_LOGIN, false);
    }

    public void setUserId(String value) {
        pref.edit().putString(USER_ID, value).apply();
    }

    public String getUserId(String defValue) {
        return pref.getString(USER_ID, defValue);
    }

    public void setBooleanValue(String key, Boolean value) {
        pref.edit().putBoolean(key, value).apply();
    }

    public boolean getBooleanValue(String key, Boolean defValue) {
        return pref.getBoolean(key, defValue);
    }

    public boolean clear() {
        return pref.edit().clear().commit();
    }

}


问:
How to Export binary data in SqlServer to file using DTS
I have an image column in a sql server 2000 table that is used to store the binary of a pdf file.

I need to export the contents of each row in the column to an actual physical file using SqlServer 2000 DTS.

I found the following method for vb at http://www.freevbcode.com/ShowCode.asp?ID=1654&NoBox=True

```<code>Set rs = conn.execute("select BinaryData from dbo.theTable")
FileHandle = FreeFile
Open ("AFile") For Binary As #FileHandle
ByteLength = LenB(rs("BinaryData"))
ByteContent = rs("BinaryData").GetChunk(ByteLength)
Put #FileHandle, ,ByteContent
Close #FileHandle
</code>```

Unfortunately, the DTS script task is VBSCript, not VB, and it throws up on the AS keyword in the third line.

Any other ideas?

答:
Writing binary files is a notoriously difficult task in VBScript. The only direct file operations exposed by VBScript live in the FileSystemObject object, which only supports writing text files. The only viable option is to use ADO Stream objects, which still is cumbersome because VBScript does not support passing script-created Byte arrays to COM objects, which is required to be able to write arbitrary binary data.

Here's a technique using ADO streams that probably won't work but might put you on the track to the right solution.

```<code>adTypeBinary = 1

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT binary_data FROM dbo.data_table", "connection string..."
Set strm = CreateObject("ADODB.Stream")
strm.Type = adTypeBinary
strm.Open
strm.Write rs.Fields("binary_data").GetChunk( _
    LenB(rs.Fields("binary_data").Value))
strm.SaveToFile "binarydata.bin"
strm.Close
rs.Close
</code>```

I experimented with this code using Access, and unfortunately it didn't seem to work. I didn't get the same binary data that was in the table I created, but I haven't bothered going into a hex editor to see what was different.

If you get errors from an ADO operation, you can get the actual messages by adding an "On Error Resume Next" to the top of the script and using this code.

```<code>For Each err In rs.ActiveConnection.Errors
    WScript.Echo err.Number & ": " & err.Description
Next
</code>```

OwnerDisplayName: Nathan

ContentLicense: CC BY-SA 2.5

Body:
I have an image column in a sql server 2000 table that is used to store the binary of a pdf file.

I need to export the contents of each row in the column to an actual physical file using SqlServer 2000 DTS.

I found the following method for vb at http://www.freevbcode.com/ShowCode.asp?ID=1654&NoBox=True

Set rs = conn.execute("select BinaryData from dbo.theTable")
FileHandle = FreeFile
Open ("AFile") For Binary As #FileHandle
ByteLength = LenB(rs("BinaryData"))
ByteContent = rs("BinaryData").GetChunk(ByteLength)
Put #FileHandle, ,ByteContent
Close #FileHandle

Unfortunately, the DTS script task is VBSCript, not VB, and it throws up on the AS keyword in the third line.

Any other ideas?

Body:
Writing binary files is a notoriously difficult task in VBScript. The only direct file operations exposed by VBScript live in the FileSystemObject object, which only supports writing text files. The only viable option is to use ADO Stream objects, which still is cumbersome because VBScript does not support passing script-created Byte arrays to COM objects, which is required to be able to write arbitrary binary data.

Here's a technique using ADO streams that probably won't work but might put you on the track to the right solution.

adTypeBinary = 1

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT binary_data FROM dbo.data_table", "connection string..."
Set strm = CreateObject("ADODB.Stream")
strm.Type = adTypeBinary
strm.Open
strm.Write rs.Fields("binary_data").GetChunk( _
    LenB(rs.Fields("binary_data").Value))
strm.SaveToFile "binarydata.bin"
strm.Close
rs.Close

I experimented with this code using Access, and unfortunately it didn't seem to work. I didn't get the same binary data that was in the table I created, but I haven't bothered going into a hex editor to see what was different.

If you get errors from an ADO operation, you can get the actual messages by adding an "On Error Resume Next" to the top of the script and using this code.

For Each err In rs.ActiveConnection.Errors
    WScript.Echo err.Number & ": " & err.Description
Next

OwnerDisplayName: Tmdean

LastEditorDisplayName: Tmdean


问:
Multiple targets and multiple build configurations in flutter
We are planning to move our codebase to flutter, but we have some specific requirements and trying to validate them before moving all our codebase to flutter.

With same codebase we are producing multiple targets in IOS and Android (In android its called flavors). And each target has different bundleId, application icons, launch images etc...

For each target we have a scheme related with that target.

We've 4 build configurations (Debug_Development,Debug_production,Release_Development,Release_production) to compile all of our targets.

I've looked at the below examples :

https://cogitas.net/creating-flavors-of-a-flutter-app/

https://medium.com/@salvatoregiordanoo/flavoring-flutter-392aaa875f36

But both of them were about creating multiple build configurations, but they don't mention about creating multiple targets.

So my question is , is it possible to create multiple targets and multiple schemes at the same time with flutter ?
If its possible , how can we do that?

You can see our current applications scheme and target configurations in below screenshot:

Thanks

答:
You can use build variants:

A flavour or a build variant can be multiple things, it can be used to
  target different device architectures or different backends. Android
  presents a separate distinction to both, so you can target different
  Android API versions and well as different backend support, for iOS
  I’m not quite certain, but it also does support these in some fashion.

and for doing this you need to modify the main.dart to support variants, here is the full article how this will work on different environments.


问:
Generate dictionaries by permutations/combinations starting from a base dictionary, and associate the result with True/False base on key values
I have a structure similar to dictionaries:

```<code>c  = {

'usize': { '500': False, '100': True}

'isize':  { '200': False, '800':False, '900':True}

'path':  {'/tmp': False, '/var':True, '/tp12':False;}

}
</code>```

I need to combine all the values, create an array of new dictionary and associate a dictionary with a Bollean values based on keys. Can be use something else than dictionaries.

Example:

```<code>c1 = {

'usize': 500,
'isize': 200,
'path': '/tmp' }

Associated value, False and False and False = False

c2 = {

'usize': 100,
'isize': 900,
'path': '/var' }

Associated value, True  and True and True = True

c2 = {

'usize': 500,
'isize': 900,
'path': '/var' }

Associated value, False  and True and True = False
</code>```

答:
You can do this using itertools product and some manipulations of the output to get the desired dicts

```<code>from itertools import product

c  = {

'usize': { '500': False, '100': True},

'isize':  { '200': False, '800':False, '900':True},

'path':  {'/tmp': False, '/var':True, '/tp12':False}

}

result = []
for group in product(*c.values()): #this makes all product groups of values such as (500, 200, '/var') etc.
    temp = dict(zip(c.keys(), group)) #bring back the keys for every group
    #create a new 'value' key with the boolean result
    temp['value'] = all(c[k][v] for k, v in temp.items()) #change to .iteritems() for python 2
    result.append(temp)
print(result)
</code>```

Output:

```<code>[{'usize': '500', 'isize': '200', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '200', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '200', 'path': '/tp12', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/tp12', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/var', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/var', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '900', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '900', 'path': '/var', 'value': True},
 {'usize': '100', 'isize': '900', 'path': '/tp12', 'value': False}]
</code>```

Body:
I have a structure similar to dictionaries:

c  = {

'usize': { '500': False, '100': True}

'isize':  { '200': False, '800':False, '900':True}

'path':  {'/tmp': False, '/var':True, '/tp12':False;}

}

I need to combine all the values, create an array of new dictionary and associate a dictionary with a Bollean values based on keys. Can be use something else than dictionaries.

Example:

c1 = {

'usize': 500,
'isize': 200,
'path': '/tmp' }

Associated value, False and False and False = False

c2 = {

'usize': 100,
'isize': 900,
'path': '/var' }

Associated value, True  and True and True = True

c2 = {

'usize': 500,
'isize': 900,
'path': '/var' }

Associated value, False  and True and True = False

Body:
You can do this using itertools product and some manipulations of the output to get the desired dicts

from itertools import product

c  = {

'usize': { '500': False, '100': True},

'isize':  { '200': False, '800':False, '900':True},

'path':  {'/tmp': False, '/var':True, '/tp12':False}

}

result = []
for group in product(*c.values()): #this makes all product groups of values such as (500, 200, '/var') etc.
    temp = dict(zip(c.keys(), group)) #bring back the keys for every group
    #create a new 'value' key with the boolean result
    temp['value'] = all(c[k][v] for k, v in temp.items()) #change to .iteritems() for python 2
    result.append(temp)
print(result)

Output:

[{'usize': '500', 'isize': '200', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '200', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '200', 'path': '/tp12', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '800', 'path': '/tp12', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/tmp', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/var', 'value': False},
 {'usize': '500', 'isize': '900', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/var', 'value': False},
 {'usize': '100', 'isize': '200', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/var', 'value': False},
 {'usize': '100', 'isize': '800', 'path': '/tp12', 'value': False},
 {'usize': '100', 'isize': '900', 'path': '/tmp', 'value': False},
 {'usize': '100', 'isize': '900', 'path': '/var', 'value': True},
 {'usize': '100', 'isize': '900', 'path': '/tp12', 'value': False}]


问:
Display a warning message with a specific CSS format
I saw the dialog as the picture below,

That is an warning message for erroneous MAC address format after the input text submitted. I would like to verify the input immediately not after it is submitted. Where can I find this css style?

答:
if you need to verify immediately, you have to add novalidate attribute to <form> tag.
then in js code, you have to add listener to the input and on each change you will validate and show your desired message.

```<code>$('input').on('change keyup keydown',()=>{//validation code; })
</code>```

Body:
if you need to verify immediately, you have to add novalidate attribute to <form> tag.
then in js code, you have to add listener to the input and on each change you will validate and show your desired message.

$('input').on('change keyup keydown',()=>{//validation code; })


问:
Camera is not following the airplane in Scenekit
I have a flying aircraft which I am following and I am also showing the path the aircraft has followed. I am drawing cylinders as a line for drawing the path. Its kind of drawing a line between 2 points. I have a cameraNode which is set to (0,200,200) initially. At that point I can see the aircraft. But when I start my flight. It goes out of the screen. I want 2 things :

Follow just the aircraft (Path won't matter).

Show whole path and also the aircraft.

I tried finding the min ad max x,y and z and taking average but it din't work. If you see below gif its too zoomed and aircraft has moved out of the screen

Here is how I set my camera:

```<code>- (void)setUpCamera {
SCNScene *workingScene = [self getWorkingScene];
_cameraNode = [[SCNNode alloc] init];
_cameraNode.camera = [SCNCamera camera];
_cameraNode.camera.zFar = 500;
_cameraNode.position = SCNVector3Make(0, 60, 50);
[workingScene.rootNode addChildNode:_cameraNode];

SCNNode *frontCameraNode = [SCNNode node];
frontCameraNode.position = SCNVector3Make(0, 100, 50);
frontCameraNode.camera = [SCNCamera camera];
frontCameraNode.camera.xFov = 75;
frontCameraNode.camera.zFar = 500;
[_assetActivity addChildNode:frontCameraNode]; //_assetActivity is the aircraft node.
</code>```

}

Here is how I am changing camera position which is not working:

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

DAL3DPoint *point = [self.aircraftLocation convertCooridnateTo3DPoint];
DAL3DPoint *previousPoint = [self.previousAircraftLocation convertCooridnateTo3DPoint];
self.minCoordinate = [self.minCoordinate findMinPoint:self.minCoordinate currentPoint:point];
self.maxCoordinate = [self.minCoordinate findMaxPoint:self.maxCoordinate currentPoint:point];
DAL3DPoint *averagePoint = [[DAL3DPoint alloc] init];
averagePoint = [averagePoint averageBetweenCoordiantes:self.minCoordinate maxPoint:self.maxCoordinate];

SCNVector3 positions[] = {
    SCNVector3Make(point.x,point.y,point.z) ,
    SCNVector3Make(previousPoint.x,previousPoint.y,previousPoint.z)
};
SCNScene *workingScene = [self getWorkingScene];
DALLineNode *lineNodeA = [[DALLineNode alloc] init];
[lineNodeA init:workingScene.rootNode v1:positions[0] v2:positions[1] radius:0.1 radSegementCount:6 lineColor:[UIColor greenColor]] ;
[workingScene.rootNode addChildNode:lineNodeA];
self.previousAircraftLocation = [self.aircraftLocation mutableCopy];
self.cameraNode.position = SCNVector3Make(averagePoint.x, averagePoint.y, z);
self.pointOfView = self.cameraNode;
</code>```

}

Code in swift or objective c are welcomed.

Thanks!!

答:
You need to calculate the angle of the velocity so that the camera points in the direction of the moving SCNNode.

This code will point you in the right direction.

```<code>    func renderer(_ aRenderer: SCNSceneRenderer, didSimulatePhysicsAtTime time: TimeInterval) {

        // get velocity angle using velocity of vehicle

        var degrees = convertVectorToAngle(vector: vehicle.chassisBody.velocity)

        // get rotation of current camera on X and Z axis

        let eX = cameraNode.eulerAngles.x
        let eZ = cameraNode.eulerAngles.z

        // offset rotation on y axis by 90 degrees

        // this needs work, buggy

        let ninety = deg2rad(90)

        // default camera Y Euler angle facing north at 0 degrees

        var eY : Float = 0.0

        if degrees != 0 {

            eY = Float(-degrees) - Float(ninety)

        }

        // rotate camera direction using cameraNode.eulerAngles and direction of velocity as eY

        cameraNode.eulerAngles = SCNVector3Make(eX, eY, eZ)

        // put camera 25 points behind vehicle facing direction of velocity

        let dir = calculateCameraDirection(cameraNode: vehicleNode)
        let pos = pointInFrontOfPoint(point: vehicleNode.position, direction:dir, distance: 25)

        // camera follows driver view from 25 points behind, and 10 points above vehicle

        cameraNode.position = SCNVector3Make(pos.x, vehicleNode.position.y + 10, pos.z)

}

func convertVectorToAngle(vector: SCNVector3) -> CGFloat {

    let degrees = atan2(vector.z, vector.x)

    return CGFloat(degrees)

}

func pointInFrontOfPoint(point: SCNVector3, direction: SCNVector3, distance: Float) -> SCNVector3 {

    var x = Float()
    var y = Float()
    var z = Float()

    x = point.x + distance * direction.x
    y = point.y + distance * direction.y
    z = point.z + distance * direction.z

    let result = SCNVector3Make(x, y, z)
    return result

}

func calculateCameraDirection(cameraNode: SCNNode) -> SCNVector3 {

            let x = -cameraNode.rotation.x
            let y = -cameraNode.rotation.y
            let z = -cameraNode.rotation.z
            let w = cameraNode.rotation.w
            let cameraRotationMatrix = GLKMatrix3Make(cos(w) + pow(x, 2) * (1 - cos(w)),
                                                      x * y * (1 - cos(w)) - z * sin(w),
                                                      x * z * (1 - cos(w)) + y*sin(w),

                                                      y*x*(1-cos(w)) + z*sin(w),
                                                      cos(w) + pow(y, 2) * (1 - cos(w)),
                                                      y*z*(1-cos(w)) - x*sin(w),

                                                      z*x*(1 - cos(w)) - y*sin(w),
                                                      z*y*(1 - cos(w)) + x*sin(w),
                                                      cos(w) + pow(z, 2) * ( 1 - cos(w)))

            let cameraDirection = GLKMatrix3MultiplyVector3(cameraRotationMatrix, GLKVector3Make(0.0, 0.0, -1.0))
            return SCNVector3FromGLKVector3(cameraDirection)
}

func deg2rad(_ number: Double) -> Double {

        return number * .pi / 180

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a flying aircraft which I am following and I am also showing the path the aircraft has followed. I am drawing cylinders as a line for drawing the path. Its kind of drawing a line between 2 points. I have a cameraNode which is set to (0,200,200) initially. At that point I can see the aircraft. But when I start my flight. It goes out of the screen. I want 2 things :

Follow just the aircraft (Path won't matter).

Show whole path and also the aircraft.

I tried finding the min ad max x,y and z and taking average but it din't work. If you see below gif its too zoomed and aircraft has moved out of the screen

Here is how I set my camera:

- (void)setUpCamera {
SCNScene *workingScene = [self getWorkingScene];
_cameraNode = [[SCNNode alloc] init];
_cameraNode.camera = [SCNCamera camera];
_cameraNode.camera.zFar = 500;
_cameraNode.position = SCNVector3Make(0, 60, 50);
[workingScene.rootNode addChildNode:_cameraNode];

SCNNode *frontCameraNode = [SCNNode node];
frontCameraNode.position = SCNVector3Make(0, 100, 50);
frontCameraNode.camera = [SCNCamera camera];
frontCameraNode.camera.xFov = 75;
frontCameraNode.camera.zFar = 500;
[_assetActivity addChildNode:frontCameraNode]; //_assetActivity is the aircraft node.

}

Here is how I am changing camera position which is not working:

- (void)showRealTimeFlightPath {

DAL3DPoint *point = [self.aircraftLocation convertCooridnateTo3DPoint];
DAL3DPoint *previousPoint = [self.previousAircraftLocation convertCooridnateTo3DPoint];
self.minCoordinate = [self.minCoordinate findMinPoint:self.minCoordinate currentPoint:point];
self.maxCoordinate = [self.minCoordinate findMaxPoint:self.maxCoordinate currentPoint:point];
DAL3DPoint *averagePoint = [[DAL3DPoint alloc] init];
averagePoint = [averagePoint averageBetweenCoordiantes:self.minCoordinate maxPoint:self.maxCoordinate];

SCNVector3 positions[] = {
    SCNVector3Make(point.x,point.y,point.z) ,
    SCNVector3Make(previousPoint.x,previousPoint.y,previousPoint.z)
};
SCNScene *workingScene = [self getWorkingScene];
DALLineNode *lineNodeA = [[DALLineNode alloc] init];
[lineNodeA init:workingScene.rootNode v1:positions[0] v2:positions[1] radius:0.1 radSegementCount:6 lineColor:[UIColor greenColor]] ;
[workingScene.rootNode addChildNode:lineNodeA];
self.previousAircraftLocation = [self.aircraftLocation mutableCopy];
self.cameraNode.position = SCNVector3Make(averagePoint.x, averagePoint.y, z);
self.pointOfView = self.cameraNode;

}

Code in swift or objective c are welcomed.

Thanks!!

Body:
You need to calculate the angle of the velocity so that the camera points in the direction of the moving SCNNode.

This code will point you in the right direction.

    func renderer(_ aRenderer: SCNSceneRenderer, didSimulatePhysicsAtTime time: TimeInterval) {

        // get velocity angle using velocity of vehicle

        var degrees = convertVectorToAngle(vector: vehicle.chassisBody.velocity)

        // get rotation of current camera on X and Z axis

        let eX = cameraNode.eulerAngles.x
        let eZ = cameraNode.eulerAngles.z

        // offset rotation on y axis by 90 degrees

        // this needs work, buggy

        let ninety = deg2rad(90)

        // default camera Y Euler angle facing north at 0 degrees

        var eY : Float = 0.0

        if degrees != 0 {

            eY = Float(-degrees) - Float(ninety)

        }

        // rotate camera direction using cameraNode.eulerAngles and direction of velocity as eY

        cameraNode.eulerAngles = SCNVector3Make(eX, eY, eZ)

        // put camera 25 points behind vehicle facing direction of velocity

        let dir = calculateCameraDirection(cameraNode: vehicleNode)
        let pos = pointInFrontOfPoint(point: vehicleNode.position, direction:dir, distance: 25)

        // camera follows driver view from 25 points behind, and 10 points above vehicle

        cameraNode.position = SCNVector3Make(pos.x, vehicleNode.position.y + 10, pos.z)

}

func convertVectorToAngle(vector: SCNVector3) -> CGFloat {

    let degrees = atan2(vector.z, vector.x)

    return CGFloat(degrees)

}

func pointInFrontOfPoint(point: SCNVector3, direction: SCNVector3, distance: Float) -> SCNVector3 {

    var x = Float()
    var y = Float()
    var z = Float()

    x = point.x + distance * direction.x
    y = point.y + distance * direction.y
    z = point.z + distance * direction.z

    let result = SCNVector3Make(x, y, z)
    return result

}

func calculateCameraDirection(cameraNode: SCNNode) -> SCNVector3 {

            let x = -cameraNode.rotation.x
            let y = -cameraNode.rotation.y
            let z = -cameraNode.rotation.z
            let w = cameraNode.rotation.w
            let cameraRotationMatrix = GLKMatrix3Make(cos(w) + pow(x, 2) * (1 - cos(w)),
                                                      x * y * (1 - cos(w)) - z * sin(w),
                                                      x * z * (1 - cos(w)) + y*sin(w),

                                                      y*x*(1-cos(w)) + z*sin(w),
                                                      cos(w) + pow(y, 2) * (1 - cos(w)),
                                                      y*z*(1-cos(w)) - x*sin(w),

                                                      z*x*(1 - cos(w)) - y*sin(w),
                                                      z*y*(1 - cos(w)) + x*sin(w),
                                                      cos(w) + pow(z, 2) * ( 1 - cos(w)))

            let cameraDirection = GLKMatrix3MultiplyVector3(cameraRotationMatrix, GLKVector3Make(0.0, 0.0, -1.0))
            return SCNVector3FromGLKVector3(cameraDirection)
}

func deg2rad(_ number: Double) -> Double {

        return number * .pi / 180

}


问:
Internet Explorer 11 always crashes whenever Developer Tools is opened when working with an Angular Project
So, I've had this issue for days now. That IE will always crash when Developer Tools is opened when working with my angular application. And I'm adding this question since I could not see a solution on stackoverflow of how to deal with this particular issue. (At least when searching with this question as query) And it seems a problem even with Windows 10s Nov 2018 Update. BTW. I'm on the latest beta of WIndows 10, which should have the latest updates for IE should this be a bug on IE 11 really, but to no luck, IE still crashes even on the beta build.

So for a while, I resorted to installing Windows 7 and IE 11 inside Hyper-V and just debugged my angular application inside Hyper-V while making my code Changes in Windows 10 with my IDE IntelliJ. How did I do that?, just follow the instructions from this link.

Debugged Angular Application on a Virtual Machine / Hyper-V

答:
To make it simple, just do the ff.:

Go to Internet Explorer then click

Settings button > Internet Options > Advance > Security >

○ then  on the Settings view, select/check "Enable 64-bit processes for Enhanced Protected Mode"

Close the browser then open I.E again.

You should then be able to Open Developer Tools now without I.E Crashing.

Optional step if the issue still persist.

Go to your run command and then type the ff.

iexplorer.exe -extoff