问:
How does Angular handle binding for [class.example]="true"?
There are these special template bindings that you can do with CSS classes and styles.

They look something like this:

```<code><div [class.example]="true"
     [style.width.px]="100">
</div>
</code>```

I took a look at the ngClass and ngStyle directives, but couldn't figure out how they work.

I was wondering if I can use this kind of syntax with my own bindings for my components.

For example:

```<code><my-component [name.first]="John" [name.last]="Smith></my-component>
</code>```

With the code like this:

```<code>@Component({..})
export class MyComponent {
    @Input()
    public name: any;
}
</code>```

I was hoping angular would pass something like {first:"John",last:"Smith"} to the name input, but I just get an error saying that the name.first and name.last inputs don't exist on the component.

Is there a way to get the above to work like the [class.any-thing-here] does?

答:
These bindings are kind of special cases BoundElementPropertyAst
Live example

```<code>PropertyBindingType.Class
PropertyBindingType.Style
</code>```

Angular parses it in https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/template_parser/binding_parser.ts#L244-L298

binding_parser.ts

```<code>const ATTRIBUTE_PREFIX = 'attr';
const CLASS_PREFIX = 'class';
const STYLE_PREFIX = 'style';

createElementPropertyAst(elementSelector: string, boundProp: BoundProperty):
    BoundElementPropertyAst {
  if (boundProp.isAnimation) {
    return new BoundElementPropertyAst(
        boundProp.name, PropertyBindingType.Animation, SecurityContext.NONE, boundProp.expression,
        null, boundProp.sourceSpan);
  }

  let unit: string|null = null;
  let bindingType: PropertyBindingType = undefined !;
  let boundPropertyName: string|null = null;
  const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  let securityContexts: SecurityContext[] = undefined !;

  // Check check for special cases (prefix style, attr, class)
  if (parts.length > 1) {
    if (parts[0] == ATTRIBUTE_PREFIX) {
      boundPropertyName = parts[1];
      this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
      securityContexts = calcPossibleSecurityContexts(
          this._schemaRegistry, elementSelector, boundPropertyName, true);

      const nsSeparatorIdx = boundPropertyName.indexOf(':');
      if (nsSeparatorIdx > -1) {
        const ns = boundPropertyName.substring(0, nsSeparatorIdx);
        const name = boundPropertyName.substring(nsSeparatorIdx + 1);
        boundPropertyName = mergeNsAndName(ns, name);
      }

      bindingType = PropertyBindingType.Attribute;
    } else if (parts[0] == CLASS_PREFIX) {
      boundPropertyName = parts[1];
      bindingType = PropertyBindingType.Class;
      securityContexts = [SecurityContext.NONE];
    } else if (parts[0] == STYLE_PREFIX) {
      unit = parts.length > 2 ? parts[2] : null;
      boundPropertyName = parts[1];
      bindingType = PropertyBindingType.Style;
      securityContexts = [SecurityContext.STYLE];
    }
  }

  // If not a special case, use the full property name
  if (boundPropertyName === null) {
    boundPropertyName = this._schemaRegistry.getMappedPropName(boundProp.name);
    securityContexts = calcPossibleSecurityContexts(
        this._schemaRegistry, elementSelector, boundPropertyName, false);
    bindingType = PropertyBindingType.Property;
    this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, false);
  }

  return new BoundElementPropertyAst(
      boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit,
      boundProp.sourceSpan);
}
</code>```

They have no connection with any of @Inputs of build-in directives. They are just bindings for elements.

When angular creates view it uses these bindings to apply to element

```<code>return jit_viewDef1(0,[(_l()(),jit_elementDef2(0,null,null,1,'div',[],[[2,'example',
      null],[4,'width','px']],null,null,null,null)),(_l()(),jit_textDef3(null,['\n'])),
      (_l()(),jit_textDef3(null,['\n']))],null,function(_ck,_v) {
    var currVal_0 = true;
    var currVal_1 = 100;
    _ck(_v,0,0,currVal_0,currVal_1);
});
</code>```

Look at elementDef above. This function takes bindings params:

```<code>function elementDef(................................bindings...
                                                       \/
jit_elementDef2(0,null,null,1,'div',[],[[2,'example', null],4,'width','px']]
</code>```

[class.any-thing-here] binding doesn't do what you want. ngClass and ngStyle do it. But if you take a look at their implementation

```<code>[ngStyle]="{'font-style': styleExp}"
[ngClass]="{'first': true, 'second': true, 'third': false}"
</code>```

you can notice that there is no magic here. They can take an object.

So angular respects [attr.x] [class.x] [style.x] but won't work with [name.x] since will expect name.x property Plunker (see console)

Body:
There are these special template bindings that you can do with CSS classes and styles.

They look something like this:

I took a look at the ngClass and ngStyle directives, but couldn't figure out how they work.

I was wondering if I can use this kind of syntax with my own bindings for my components.

For example:

<my-component [name.first]="John" [name.last]="Smith></my-component>

With the code like this:

@Component({..})
export class MyComponent {
    @Input()
    public name: any;
}

I was hoping angular would pass something like {first:"John",last:"Smith"} to the name input, but I just get an error saying that the name.first and name.last inputs don't exist on the component.

Is there a way to get the above to work like the [class.any-thing-here] does?

Body:
These bindings are kind of special cases BoundElementPropertyAst
Live example

PropertyBindingType.Class
PropertyBindingType.Style

Angular parses it in https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/template_parser/binding_parser.ts#L244-L298

binding_parser.ts

const ATTRIBUTE_PREFIX = 'attr';
const CLASS_PREFIX = 'class';
const STYLE_PREFIX = 'style';

createElementPropertyAst(elementSelector: string, boundProp: BoundProperty):
    BoundElementPropertyAst {
  if (boundProp.isAnimation) {
    return new BoundElementPropertyAst(
        boundProp.name, PropertyBindingType.Animation, SecurityContext.NONE, boundProp.expression,
        null, boundProp.sourceSpan);
  }

  let unit: string|null = null;
  let bindingType: PropertyBindingType = undefined !;
  let boundPropertyName: string|null = null;
  const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  let securityContexts: SecurityContext[] = undefined !;

  // Check check for special cases (prefix style, attr, class)
  if (parts.length > 1) {
    if (parts[0] == ATTRIBUTE_PREFIX) {
      boundPropertyName = parts[1];
      this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
      securityContexts = calcPossibleSecurityContexts(
          this._schemaRegistry, elementSelector, boundPropertyName, true);

      const nsSeparatorIdx = boundPropertyName.indexOf(':');
      if (nsSeparatorIdx > -1) {
        const ns = boundPropertyName.substring(0, nsSeparatorIdx);
        const name = boundPropertyName.substring(nsSeparatorIdx + 1);
        boundPropertyName = mergeNsAndName(ns, name);
      }

      bindingType = PropertyBindingType.Attribute;
    } else if (parts[0] == CLASS_PREFIX) {
      boundPropertyName = parts[1];
      bindingType = PropertyBindingType.Class;
      securityContexts = [SecurityContext.NONE];
    } else if (parts[0] == STYLE_PREFIX) {
      unit = parts.length > 2 ? parts[2] : null;
      boundPropertyName = parts[1];
      bindingType = PropertyBindingType.Style;
      securityContexts = [SecurityContext.STYLE];
    }
  }

  // If not a special case, use the full property name
  if (boundPropertyName === null) {
    boundPropertyName = this._schemaRegistry.getMappedPropName(boundProp.name);
    securityContexts = calcPossibleSecurityContexts(
        this._schemaRegistry, elementSelector, boundPropertyName, false);
    bindingType = PropertyBindingType.Property;
    this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, false);
  }

  return new BoundElementPropertyAst(
      boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit,
      boundProp.sourceSpan);
}

They have no connection with any of @Inputs of build-in directives. They are just bindings for elements.

When angular creates view it uses these bindings to apply to element

return jit_viewDef1(0,[(_l()(),jit_elementDef2(0,null,null,1,'div',[],[[2,'example',
      null],[4,'width','px']],null,null,null,null)),(_l()(),jit_textDef3(null,['\n'])),
      (_l()(),jit_textDef3(null,['\n']))],null,function(_ck,_v) {
    var currVal_0 = true;
    var currVal_1 = 100;
    _ck(_v,0,0,currVal_0,currVal_1);
});

Look at elementDef above. This function takes bindings params:

function elementDef(................................bindings...
                                                       \/
jit_elementDef2(0,null,null,1,'div',[],[[2,'example', null],4,'width','px']]

[class.any-thing-here] binding doesn't do what you want. ngClass and ngStyle do it. But if you take a look at their implementation

[ngStyle]="{'font-style': styleExp}"
[ngClass]="{'first': true, 'second': true, 'third': false}"

you can notice that there is no magic here. They can take an object.

So angular respects [attr.x] [class.x] [style.x] but won't work with [name.x] since will expect name.x property Plunker (see console)


来源: stackexchange

问:
How to use sequence when testing async methods?
I am using Moq.Sequences and I am having trouble with testing async methods.
When I do this:

```<code>[Test]
public async Task Demo()
{
    using (Sequence.Create())
    {
        _fooMock.Setup(f => f.Fooxiate()).InSequence();

        _barMock.Setup(b => b.Baronize()).InSequence();

        var result = await _cut.DoMyStuffAsync();

        Assert.AreEqual("someString", result);
    }
}
</code>```

The I get an exception in the production code when calling _foo.Fooxiate() saying:

Moq.Sequences.SequenceUsageException: 'Mock invocation can only be called with an active MockSequence created with MockSequence.Create()

Am I doing something wrong or is testing of call sequence in async methods not supported?

Here is the full demo code including the above mentioned production code:

```<code>using System.Threading.Tasks;
using Moq;
using Moq.Sequences;
using NUnit.Framework;

namespace TestingAsync.Tests
{
    [TestFixture]
    public class SomeClassTests
    {
        private SomeClass _cut;

        private Mock<IFoo> _fooMock;
        private Mock<IBar> _barMock;

        [SetUp]
        public void Setup()
        {
            _fooMock = new Mock<IFoo>();
            _barMock = new Mock<IBar>();

            _cut = new SomeClass(_fooMock.Object, _barMock.Object);
        }

        [Test]
        public async Task Demo()
        {
            using (Sequence.Create())
            {
                _fooMock.Setup(f => f.Fooxiate()).InSequence();

                _barMock.Setup(b => b.Baronize()).InSequence();

                var result = await _cut.DoMyStuffAsync();

                Assert.AreEqual("someString", result);
            }
        }
    }

    public class SomeClass
    {
        private readonly IFoo _foo;
        private readonly IBar _bar;

        public SomeClass(IFoo foo, IBar bar)
        {
            _bar = bar;
            _foo = foo;
        }

        public async Task<string> DoMyStuffAsync()
        {
            return await Task.Run(() => DoMyStuff());
        }

        private string DoMyStuff()
        {
            _foo.Fooxiate();

            _bar.Baronize();

            return "someString";
        }
    }

    public interface IBar
    {
        void Baronize();
    }

    public interface IFoo
    {
        void Fooxiate();
    }
}
</code>```

答:
Moq.Sequences is not written to be multi-threaded as it uses the [ThreadStatic] attribute to keep track of the ambient Sequence.

```<code>    [ThreadStatic]
    private static Sequence instance;
</code>```

The result is that the ambient Sequence is only stored for the current thread. Then you call Task.Run which spawns a background thread to do work. This results in the exception being thrown because instance is null for that thread.

```<code>if (Instance == null)
    throw new SequenceUsageException(context + " can only be called with an active MockSequence created with MockSequence.Create()");
</code>```

https://github.com/dwhelan/Moq-Sequences → src/Moq.Sequences/Sequence.cs

There is not a good way for Moq.Sequences to be able to guarantee order of calls in async code because:

Concurrent code does not typically have deterministic order of execution.

Async is an abstraction over threads and because of that is even less predictable than threads. There are many techniques that result in non-deterministic sequence of calls, such as doing work in background threads with Task.Run, using Parallel.For/ForEach, using TPL dataflow, using Task.WhenAll, etc.

ContentLicense: CC BY-SA 3.0

Body:
I am using Moq.Sequences and I am having trouble with testing async methods.
When I do this:

[Test]
public async Task Demo()
{
    using (Sequence.Create())
    {
        _fooMock.Setup(f => f.Fooxiate()).InSequence();

        _barMock.Setup(b => b.Baronize()).InSequence();

        var result = await _cut.DoMyStuffAsync();

        Assert.AreEqual("someString", result);
    }
}

The I get an exception in the production code when calling _foo.Fooxiate() saying:

Moq.Sequences.SequenceUsageException: 'Mock invocation can only be called with an active MockSequence created with MockSequence.Create()

Am I doing something wrong or is testing of call sequence in async methods not supported?

Here is the full demo code including the above mentioned production code:

using System.Threading.Tasks;
using Moq;
using Moq.Sequences;
using NUnit.Framework;

namespace TestingAsync.Tests
{
    [TestFixture]
    public class SomeClassTests
    {
        private SomeClass _cut;

        private Mock<IFoo> _fooMock;
        private Mock<IBar> _barMock;

        [SetUp]
        public void Setup()
        {
            _fooMock = new Mock<IFoo>();
            _barMock = new Mock<IBar>();

            _cut = new SomeClass(_fooMock.Object, _barMock.Object);
        }

        [Test]
        public async Task Demo()
        {
            using (Sequence.Create())
            {
                _fooMock.Setup(f => f.Fooxiate()).InSequence();

                _barMock.Setup(b => b.Baronize()).InSequence();

                var result = await _cut.DoMyStuffAsync();

                Assert.AreEqual("someString", result);
            }
        }
    }

    public class SomeClass
    {
        private readonly IFoo _foo;
        private readonly IBar _bar;

        public SomeClass(IFoo foo, IBar bar)
        {
            _bar = bar;
            _foo = foo;
        }

        public async Task<string> DoMyStuffAsync()
        {
            return await Task.Run(() => DoMyStuff());
        }

        private string DoMyStuff()
        {
            _foo.Fooxiate();

            _bar.Baronize();

            return "someString";
        }
    }

    public interface IBar
    {
        void Baronize();
    }

    public interface IFoo
    {
        void Fooxiate();
    }
}

Body:
Moq.Sequences is not written to be multi-threaded as it uses the [ThreadStatic] attribute to keep track of the ambient Sequence.

    [ThreadStatic]
    private static Sequence instance;

The result is that the ambient Sequence is only stored for the current thread. Then you call Task.Run which spawns a background thread to do work. This results in the exception being thrown because instance is null for that thread.

if (Instance == null)
    throw new SequenceUsageException(context + " can only be called with an active MockSequence created with MockSequence.Create()");

https://github.com/dwhelan/Moq-Sequences → src/Moq.Sequences/Sequence.cs

There is not a good way for Moq.Sequences to be able to guarantee order of calls in async code because:

Concurrent code does not typically have deterministic order of execution.

Async is an abstraction over threads and because of that is even less predictable than threads. There are many techniques that result in non-deterministic sequence of calls, such as doing work in background threads with Task.Run, using Parallel.For/ForEach, using TPL dataflow, using Task.WhenAll, etc.


问:
KeyboardAvoidingView - Reset height when Keyboard is hidden
I'm using React Natives KeyboardAvoidingView to set the height of my View when the Keyboard is shown. But when I close the the keyboard in the app, the height of the View is not changed back to it's original value.

```<code><KeyboardAvoidingView behavior="height" style={styles.step}>
  <View style={styles.stepHeader}>
    // my content
  </View>
</KeyboardAvoidingView>
</code>```

The View with the red outline did take up the whole space before I opened and closed the keyboard.

答:
Please give key to KeyboardAvoidingView and change when keyboard open and close so it will render and take height </p>

```<code><KeyboardAvoidingView behavior="height" style={styles.step} key={values}>
</code>```

Body:
I'm using React Natives KeyboardAvoidingView to set the height of my View when the Keyboard is shown. But when I close the the keyboard in the app, the height of the View is not changed back to it's original value.

<KeyboardAvoidingView behavior="height" style={styles.step}>
  <View style={styles.stepHeader}>
    // my content
  </View>
</KeyboardAvoidingView>

The View with the red outline did take up the whole space before I opened and closed the keyboard.

Body:
Please give key to KeyboardAvoidingView and change when keyboard open and close so it will render and take height

<KeyboardAvoidingView behavior="height" style={styles.step} key={values}>


问:
Issue loading data from array into a select list in react
I have the following class:

```<code>class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => {
            <option value={c.value} >{c.text}</option>
          })
        }
      </select>
    );
  }
}
</code>```

If I render the select list with regular html syntax then it works perfectly, where as if I try to create it dynamically then it doesn't load anything. How would you go about creating a list dynamically in react so that it maintains its binding?

Any advice would be appreciated!

Thanks.

答:
I guess you missing key={i}

```<code>  <select value={this.state.value} onChange={this.handleChange}>
    {
      this.bookOptions.map((c, i) => {
        <option key={i} value={c.value} >{c.text}</option>
      })
    }
  </select>
</code>```

I just guess, not sure right or wrong.

Body:
I have the following class:

class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => {
            <option value={c.value} >{c.text}</option>
          })
        }
      </select>
    );
  }
}

If I render the select list with regular html syntax then it works perfectly, where as if I try to create it dynamically then it doesn't load anything. How would you go about creating a list dynamically in react so that it maintains its binding?

Any advice would be appreciated!

Thanks.

Body:
I guess you missing key={i}

  <select value={this.state.value} onChange={this.handleChange}>
    {
      this.bookOptions.map((c, i) => {
        <option key={i} value={c.value} >{c.text}</option>
      })
    }
  </select>

I just guess, not sure right or wrong.


问:
Conflicting type C for global variable
I wanted to use a file to have all my #define and constants: Example

```<code> #ifndef CONSTANTS_H_
 #define CONSTANTS_H_

 #include <avr/io.h>

 //OVERALL DEFS
 #define TRUE 1
 #define FALSE 0

 // CLK_32MHz.h
 const uint8_t NEW_CLOCK_FREQ = 0b00000010;

 #endif /* CONSTANTS_H_ */
</code>```

Then a different file to call it. Example:

```<code>#ifndef CLK_32MHZ_H_
#define CLK_32MHZ_H_

#include <avr/io.h>
#include "constants.h"

extern uint8_t NEW_CLOCK_FREQ;

void Change_CLK_32HZ(){

    //Set the clk config
    OSC_CTRL = NEW_CLOCK_FREQ;

    //Wait for the right flag to be set in the OSC_STATUS reg
    while((OSC_STATUS & PIN1_bm) != PIN1_bm);

    //Write the “IOREG” signature to the CPU_CCP reg
    CPU_CCP = CCP_IOREG_gc;

    //Select the new clock source in the CLK_CTRL reg
    CLK_CTRL = CLK_SCLKSEL_RC32M_gc;

    return;
}
#endif /* CLK_32MHZ_H_ */
</code>```

This is my main function:

```<code>#include <avr/io.h>
#include "constants.h"
#include "Clk_32MHz.h"

int main(void){

}
</code>```

This is the error I get on the terminal:

Conflicting type qualifiers for 'NEW_CLOCK_FREQ' File: Clk_32MHz.h
previous definition of 'NEW_CLOCK_FREQ' was here File: constants.h

答:
Try the following...

in header.h:

```<code>extern const uint8_t myconst;
</code>```

in foo.c:

```<code>#include "header.h"
const uint8_t myconst = 42;
</code>```

Title: Conflicting type C for global variable

Body:
I wanted to use a file to have all my #define and constants: Example

 #ifndef CONSTANTS_H_
 #define CONSTANTS_H_

 #include <avr/io.h>

 //OVERALL DEFS
 #define TRUE 1
 #define FALSE 0

 // CLK_32MHz.h
 const uint8_t NEW_CLOCK_FREQ = 0b00000010;

 #endif /* CONSTANTS_H_ */

Then a different file to call it. Example:

#ifndef CLK_32MHZ_H_
#define CLK_32MHZ_H_

#include <avr/io.h>
#include "constants.h"

extern uint8_t NEW_CLOCK_FREQ;

void Change_CLK_32HZ(){

    //Set the clk config
    OSC_CTRL = NEW_CLOCK_FREQ;

    //Wait for the right flag to be set in the OSC_STATUS reg
    while((OSC_STATUS & PIN1_bm) != PIN1_bm);

    //Write the “IOREG” signature to the CPU_CCP reg
    CPU_CCP = CCP_IOREG_gc;

    //Select the new clock source in the CLK_CTRL reg
    CLK_CTRL = CLK_SCLKSEL_RC32M_gc;

    return;
}
#endif /* CLK_32MHZ_H_ */

This is my main function:

#include <avr/io.h>
#include "constants.h"
#include "Clk_32MHz.h"

int main(void){

}

This is the error I get on the terminal:

Conflicting type qualifiers for 'NEW_CLOCK_FREQ' File: Clk_32MHz.h
previous definition of 'NEW_CLOCK_FREQ' was here File: constants.h

Body:
Try the following...

in header.h:

extern const uint8_t myconst;

in foo.c:

#include "header.h"
const uint8_t myconst = 42;


问:
How to pass user image from Tablecell to Viewcontroller on firebase?
I was only able to pass user name labels from table cell to another Viewcontroller but not the user image. I tried using prepare for segue function as you can see in my code below. thanks

```<code>import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage

class MainVc: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableview2: UITableView!
var user = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    retrieveUsers()

}

func retrieveUsers() {
    let ref = Database.database().reference()

    ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

        let users = snapshot.value as! [String : AnyObject]
        self.user.removeAll()
        for (_, value) in users {
            if let uid = value["uid"] as? String {
                if uid != Auth.auth().currentUser!.uid {
                    let userToShow = User()
                    if let fullName = value["full name"] as? String,let businessType = value["Business Type"] as? String, let imagePath = value["urlToImage"] as? String {

                        userToShow.fullName = fullName
                        userToShow.businessType = businessType

                        userToShow.imagePath = imagePath
                        userToShow.userID = uid

                        self.user.append(userToShow)

                    }

                }

            }

        }

        self.tableview2.reloadData()
    })

    ref.removeAllObservers()

}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let upcoming: ViewController = segue.destination as! ViewController

    let indexPath = self.tableview2.indexPathForSelectedRow!

    let titleString = self.user[indexPath.row].fullName

    let imageView = self.user[indexPath.row].imagePath! // i tried using this to transfer the image  from tableview to viewcontroller but its not working

    upcoming.imageView = imageView

    upcoming.titleString = titleString

    self.tableview2.deselectRow(at: indexPath, animated: true)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return user.count ?? 0
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableview2.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UserCell

    cell.userNameLbl.text = self.user[indexPath.row].fullName
     cell.businessTypeLbl.text = self.user[indexPath.row].businessType

    cell.userID = self.user[indexPath.row].userID
    cell.userImage.downloadImage(from: self.user[indexPath.row].imagePath!)

    return cell
}
}

extension UIImageView {

    func downloadImage(from imgURL: String!) {
        let url = URLRequest(url: URL(string: imgURL)!)

        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }

        }

        task.resume()
    }

    }
</code>```

class ViewController: UIViewController {

```<code>@IBOutlet weak var profileImage: UIImageView!

@IBOutlet weak var testLbl: UILabel!

var titleString: String!
var imageView: String!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

     self.testLbl.text = self.titleString
     self.profileImage.image = UIImage(named: imageView!)

}
</code>```

import UIKit

class User: NSObject {

```<code>var userID: String!
var fullName: String!
var imagePath: String!
var businessType: String!
</code>```

}

答:
You can define UIImage or image name property in your ViewController and access it from your MainVc. I have passed image name below.

```<code>class ViewController: UIViewController {

     @IBOutlet weak var profileImage: UIImageView!

     @IBOutlet weak var testLbl: UILabel!

     var titleString: String!
     var yourImageName:String!
     override func viewDidLoad() {
     super.viewDidLoad()

     self.testLbl.text = self.titleString
     self.imageview.image = UIImage(named:yourImageName)
}
</code>```

and pass image Name in your prepare for segue as

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let upcoming: ViewController = segue.destination as! ViewController
    let indexPath = self.tableview.indexPathForSelectedRow!
    let titleString = self.user[indexPath.row].fullName
    let imageName = self.user[indexPath.row].imagename // access image name from user array
    upcoming.titleString = titleString
    upcoming.yourImageName = imageName

    // here i want to pass user image as welH from cell to the viewcontroller
    self.tableview.deselectRow(at: indexPath, animated: true)
 }
</code>```

Hope it helps. Happy Coding!!

Body:
I was only able to pass user name labels from table cell to another Viewcontroller but not the user image. I tried using prepare for segue function as you can see in my code below. thanks

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage

class MainVc: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableview2: UITableView!
var user = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    retrieveUsers()

}

func retrieveUsers() {
    let ref = Database.database().reference()

    ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

        let users = snapshot.value as! [String : AnyObject]
        self.user.removeAll()
        for (_, value) in users {
            if let uid = value["uid"] as? String {
                if uid != Auth.auth().currentUser!.uid {
                    let userToShow = User()
                    if let fullName = value["full name"] as? String,let businessType = value["Business Type"] as? String, let imagePath = value["urlToImage"] as? String {

                        userToShow.fullName = fullName
                        userToShow.businessType = businessType

                        userToShow.imagePath = imagePath
                        userToShow.userID = uid

                        self.user.append(userToShow)

                    }

                }

            }

        }

        self.tableview2.reloadData()
    })

    ref.removeAllObservers()

}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let upcoming: ViewController = segue.destination as! ViewController

    let indexPath = self.tableview2.indexPathForSelectedRow!

    let titleString = self.user[indexPath.row].fullName

    let imageView = self.user[indexPath.row].imagePath! // i tried using this to transfer the image  from tableview to viewcontroller but its not working

    upcoming.imageView = imageView

    upcoming.titleString = titleString

    self.tableview2.deselectRow(at: indexPath, animated: true)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return user.count ?? 0
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableview2.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UserCell

    cell.userNameLbl.text = self.user[indexPath.row].fullName
     cell.businessTypeLbl.text = self.user[indexPath.row].businessType

    cell.userID = self.user[indexPath.row].userID
    cell.userImage.downloadImage(from: self.user[indexPath.row].imagePath!)

    return cell
}
}

extension UIImageView {

    func downloadImage(from imgURL: String!) {
        let url = URLRequest(url: URL(string: imgURL)!)

        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }

        }

        task.resume()
    }

    }

class ViewController: UIViewController {

@IBOutlet weak var profileImage: UIImageView!

@IBOutlet weak var testLbl: UILabel!

var titleString: String!
var imageView: String!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

     self.testLbl.text = self.titleString
     self.profileImage.image = UIImage(named: imageView!)

}

import UIKit

class User: NSObject {

var userID: String!
var fullName: String!
var imagePath: String!
var businessType: String!

}

Body:
You can define UIImage or image name property in your ViewController and access it from your MainVc. I have passed image name below.

class ViewController: UIViewController {

     @IBOutlet weak var profileImage: UIImageView!

     @IBOutlet weak var testLbl: UILabel!

     var titleString: String!
     var yourImageName:String!
     override func viewDidLoad() {
     super.viewDidLoad()

     self.testLbl.text = self.titleString
     self.imageview.image = UIImage(named:yourImageName)
}

and pass image Name in your prepare for segue as

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let upcoming: ViewController = segue.destination as! ViewController
    let indexPath = self.tableview.indexPathForSelectedRow!
    let titleString = self.user[indexPath.row].fullName
    let imageName = self.user[indexPath.row].imagename // access image name from user array
    upcoming.titleString = titleString
    upcoming.yourImageName = imageName

    // here i want to pass user image as welH from cell to the viewcontroller
    self.tableview.deselectRow(at: indexPath, animated: true)
 }

Hope it helps. Happy Coding!!


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'where clause'
I have some code producing the following error. How can I fix it?

```<code> "SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'where clause' (SQL: select count(*) as aggregate from `authors` where ` name` = Azzario Razy Junaidi and `id` <> 4)"
</code>```

```<code>AuthorsController.php
public function update(Request $request, $id)
{
    $this->validate($request, ['name' => 'required|unique:authors, name,'.$id]);
    $author = Author::find($id);
    $author->update($request->only('name'));
    Session::flash("flash_notification", [
      "level" => "success",
      "message" => "Berhasil menyimpan $author->name"
    ]);
    return redirect()->route('authors.edit');
}
</code>```

答:
Sounds to me like your database is missing the name column on the authors table.

"SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'where clause' (SQL: select count(*) as aggregate from authors where name = Azzario Razy Junaidi and id <> 4)

Body:
I have some code producing the following error. How can I fix it?

 "SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'where clause' (SQL: select count(*) as aggregate from `authors` where ` name` = Azzario Razy Junaidi and `id` <> 4)"

AuthorsController.php
public function update(Request $request, $id)
{
    $this->validate($request, ['name' => 'required|unique:authors, name,'.$id]);
    $author = Author::find($id);
    $author->update($request->only('name'));
    Session::flash("flash_notification", [
      "level" => "success",
      "message" => "Berhasil menyimpan $author->name"
    ]);
    return redirect()->route('authors.edit');
}


问:
WordPress Site Having Fatal Error in Root View
I have running WordPress Site but now a error occurs when I login to Admin Panel of WordPress and site is also not live now. A 'Fatal Error' is showing:

```<code>Fatal error: Cannot redeclare class WP_Theme_Handler_Checker in /home/niteshvyas84/public_html/shreejeeexcellency.restaurant/wp-content/themes/resca/inc/theme-checker.php on line 4
</code>```

Does anyone know how to fix this or do I have to uninstall WordPress and start from scratch?

答: There must be something wrong with your theme.  Connect to your site's FTP server and move the folder wp-content/themes/resca to another folder (such as the root) or download and then delete it.  You should then be able to log into the backend and set another theme.</p>

Body:
I have running WordPress Site but now a error occurs when I login to Admin Panel of WordPress and site is also not live now. A 'Fatal Error' is showing:

Fatal error: Cannot redeclare class WP_Theme_Handler_Checker in /home/niteshvyas84/public_html/shreejeeexcellency.restaurant/wp-content/themes/resca/inc/theme-checker.php on line 4

Does anyone know how to fix this or do I have to uninstall WordPress and start from scratch?


问:
Cannot implicitly convert type 'string' to 'System.DateTime'
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
</code>```

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

答:
```<code>DateTime dtnew = Convert.ToString(s2);
</code>```

problem is that your converting  string s2 to string again and store it in DateTime variable

Try this:

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string  s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToDateTime(s2);
</code>```

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

Body:
DateTime dtnew = Convert.ToString(s2);

problem is that your converting  string s2 to string again and store it in DateTime variable

Try this:

DateTime dt = Convert.ToDateTime("11/23/2010");
string  s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToDateTime(s2);

ContentLicense: CC BY-SA 2.5


问:
Get variable outsite foreach
I want to create a slideshow to work with Seblod, but I don't know how to get the thumbs outsite foreach:

```<code>    <ul class="bxslider">
<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

 <?php } ?>
 </ul>
<div id="bx-pager">
  <a data-slide-index="1" href=""><img src="/<?php echo $fx->thumb1; ?>" /></a>
</div>
</code>```

Because $fx->thumb1 is outsite foreach - I can't get the links of thumbs :(

答:
Try to use following code :
Hope it helps.    </p>

```<code>$img_thumb = array();
    <ul class="bxslider">
    <?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

      <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>
    $img_thumb[] =  $fx->thumb1;
     <?php } ?>
     </ul>
    <div id="bx-pager">
      <a data-slide-index="1" href=""><img src="/<?php echo $img_thumb; ?>" /></a>
    </div>
</code>```

Title: Get variable outsite foreach

Body:
I want to create a slideshow to work with Seblod, but I don't know how to get the thumbs outsite foreach:

<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

 <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" />

 <?php } ?>

  <img src="/<?php echo $fx->thumb1; ?>" />

Because $fx->thumb1 is outsite foreach - I can't get the links of thumbs :(

Body:
Try to use following code :
Hope it helps.

$img_thumb = array();
    <ul class="bxslider">
    <?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

      <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>
    $img_thumb[] =  $fx->thumb1;
     <?php } ?>
     </ul>
    <div id="bx-pager">
      <a data-slide-index="1" href=""><img src="/<?php echo $img_thumb; ?>" /></a>
    </div>


问:
Android CoordinatorLayout show ActionBar
I have a CoordinatorLayout that is setup using the default Tabbed Activity in Android Studio. This activity has the scroll flags as follows:

```<code>app:layout_scrollFlags="scroll|enterAlways"
</code>```

I have a 'scroll to top' assigned to an icon in the TabLayout via the pager adapter:

```<code>mSectionsPagerAdapter.feedFragment.scrollToTop();
</code>```

When I click this, I would also like to force the ActionBar back into view. I had assumed that I would be able to call:

```<code>getSupportActionBar().show();
</code>```

However, that isn't working. Any suggestions?

答: You can use appBarLayout.setExpanded

Body:
I have a CoordinatorLayout that is setup using the default Tabbed Activity in Android Studio. This activity has the scroll flags as follows:

app:layout_scrollFlags="scroll|enterAlways"

I have a 'scroll to top' assigned to an icon in the TabLayout via the pager adapter:

mSectionsPagerAdapter.feedFragment.scrollToTop();

When I click this, I would also like to force the ActionBar back into view. I had assumed that I would be able to call:

getSupportActionBar().show();

However, that isn't working. Any suggestions?

Body: You can use appBarLayout.setExpanded


答: The problem is in your theme somewhere. If you have another theme installed (but obviously inactive), use this guide to change your theme to something else while you troubleshoot the problem.</p>

Title: WordPress Site Having Fatal Error in Root View


问:
How can I create my own "hint" when calling a function in IDLE?
I know my question might be confusing, it's hard to ask something you don't know what it is exactly (I'm going to call it 'hint'), so my apologies for that. Having that said, here it is what I mean (the text in the white box):

My questions are:

How can I make my own hint (and customize it) text when calling a function?

What is it exactly?

What does the text in this example mean?

答:
IDLE calls the popup a 'calltip'.  For a module defined in python code with a def statement, it shows the signature on the first line and the first line of the doc string on the second.  They are intended to work correctly for any type of callable invoked with parentheses.

If you type '('  the box pops up unless you are typing fast.  After it closes, to bring it back, you position the cursor between '(' and ')' and either select Edit on the top menu and 'Show call tip', or type the shortcut key shown on the menu.  For more, see the doc.

ContentLicense: CC BY-SA 4.0


问:
How sort function works on vector of pair of pairs of integer?
Given

```<code>std::vector<std::pair<std::pair<int,int>, std::pair<int,int>> a;
std::sort(a.begin(),a.end());
</code>```

How is std::sort function going to sort this type of vector? Is there any generalization for further cascading of pairs?

答:
It will sort by first element of the first pair of pairs. In another word, the most left value of pair of pairs.

See this simple example.

```<code>#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int, int> Pair;
typedef pair<Pair, Pair> PPair;

ostream& operator<< (ostream& in, pair<int, int> p)
{
    in << '(' << p.first << ", " << p.second << ')';
    return in;
}

int main(void)
{
    vector<PPair> vPP;
    PPair pp1(Pair(123, 2), Pair(8, 7));
    PPair pp2(Pair(33, 22), Pair(88, 77));
    PPair pp3(Pair(333, 222), Pair(888, 777));

    vPP.push_back(pp1);
    vPP.push_back(pp3);
    vPP.push_back(pp2);

    std::sort(vPP.begin(), vPP.end());

    vector<PPair>::const_iterator cit;
    for (cit = vPP.begin(); cit < vPP.end(); cit++) {
        cout << (*cit).first << (*cit).second << endl;
    }

    return 0;
}
</code>```

Body:
Given

std::vector<std::pair<std::pair<int,int>, std::pair<int,int>> a;
std::sort(a.begin(),a.end());

How is std::sort function going to sort this type of vector? Is there any generalization for further cascading of pairs?

Body:
It will sort by first element of the first pair of pairs. In another word, the most left value of pair of pairs.

See this simple example.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int, int> Pair;
typedef pair<Pair, Pair> PPair;

ostream& operator<< (ostream& in, pair<int, int> p)
{
    in << '(' << p.first << ", " << p.second << ')';
    return in;
}

int main(void)
{
    vector<PPair> vPP;
    PPair pp1(Pair(123, 2), Pair(8, 7));
    PPair pp2(Pair(33, 22), Pair(88, 77));
    PPair pp3(Pair(333, 222), Pair(888, 777));

    vPP.push_back(pp1);
    vPP.push_back(pp3);
    vPP.push_back(pp2);

    std::sort(vPP.begin(), vPP.end());

    vector<PPair>::const_iterator cit;
    for (cit = vPP.begin(); cit < vPP.end(); cit++) {
        cout << (*cit).first << (*cit).second << endl;
    }

    return 0;
}


问:
C# Unexpected performance results for different methods of parsing byte[] as hex string
I have created 3 different methods for converting a byte[] into a hex string using the following format: { 0xx2, ... } (Working Demo)

```<code>using System;
using System.Diagnostics;
using System.Text;

public class Program
{
    public delegate string ParseMethod(byte[] Msg);
    public class Parser
    {
        public string Name { get; private set;}
        public ParseMethod Handler { get; private set; }

        public Parser(string name, ParseMethod method)
        {
            Name = name;
            Handler = method;
        }
    }

    public static void Main()
    {
        Parser HexA = new Parser("ToHexA", ToHexA);
        Parser HexB = new Parser("ToHexB", ToHexB);
        Parser HexC = new Parser("ToHexC", ToHexC);

        TestCorrectness(HexA);
        TestCorrectness(HexB);
        TestCorrectness(HexC);

        Console.WriteLine("Small Message Performance:");
        TestPerformance(HexA, MsgSize: 10, Iterations: 1000000);
        TestPerformance(HexB, MsgSize: 10, Iterations: 1000000);
        TestPerformance(HexC, MsgSize: 10, Iterations: 1000000);
        Console.WriteLine();

        Console.WriteLine("Large Message Performance:");
        TestPerformance(HexA, MsgSize: 500, Iterations: 1000000);
        TestPerformance(HexB, MsgSize: 500, Iterations: 1000000);
        TestPerformance(HexC, MsgSize: 500, Iterations: 1000000);
        Console.WriteLine();
    }

    private static void TestCorrectness(Parser parser)
    {
        Console.WriteLine("Testing Correctness of \"{0}(byte[] Msg)\"", parser.Name);
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{}));
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97 }));
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97, 98, 99, 0, 100 }));
        Console.WriteLine();
    }

    private static void TestPerformance(Parser parser, int MsgSize, int Iterations)
    {
        Stopwatch sw = new Stopwatch();
        sw.Reset();

        byte[] Msg = new byte[MsgSize];

        sw.Start();
        for (uint i = 0; i < Iterations; ++i)
        {
            parser.Handler(Msg);
        }
        sw.Stop();

        Console.WriteLine("Performance for \"{0}\", {1}", parser.Name, sw.Elapsed);
    }

    private static string ToHexA(byte[] buffer)
    {
        return
            (
                "{ 0x" +
                    BitConverter.ToString(buffer).ToLower()
                        .Replace("-", ", 0x") +
                " }"
            )
            .Replace(" 0x }", "}");
    }

    private static string ToHexB(byte[] buffer)
    {
        if (buffer.Length == 0) { return "{}"; }

        const string Preamble = "{ 0x";
        const string Delimiter = ", 0x";
        const string Epilogue = " }";

        string Msg = Preamble + buffer[0].ToString("x2");
        for (int i = 1; i < buffer.Length; ++i)
        {
            Msg += Delimiter + buffer[i].ToString("x2");
        }

        return Msg += Epilogue;
    }

    private static string ToHexC(byte[] buffer)
    {
        if (buffer.Length == 0) { return "{}"; }

        const string Preamble = "{ 0x";
        const string Delimiter = ", 0x";
        const string Epilogue = " }";

        StringBuilder HexOut = new StringBuilder(
            Preamble.Length +
            (Delimiter.Length * (buffer.Length - 1)) +
            (2 * buffer.Length) +
            Epilogue.Length
        );

        HexOut.Append(Preamble);
        HexOut.Append(buffer[0].ToString("x2"));
        for (int i = 1; i < buffer.Length; ++i)
        {
            HexOut.Append(Delimiter);
            HexOut.Append(buffer[i].ToString("x2"));
        }
        HexOut.Append(Epilogue);

        return HexOut.ToString();
    }
}
</code>```

Running this code I get the following performance statistics

```<code>Small Message Performance:
Performance for "ToHexA", 00:00:01.3078387
Performance for "ToHexB", 00:00:01.6939201
Performance for "ToHexC", 00:00:01.2997903

Large Message Performance:
Performance for "ToHexA", 00:00:32.5230253
Performance for "ToHexB", 00:04:23.4798762
Performance for "ToHexC", 00:00:56.2404684
</code>```

I find it surprising that ToHexA (relative to ToHexC) executes faster with a longer message but slower with a shorter message. As I understand it, Replace(), +, and ToLower() all have to perform a create/copy operation because strings are immutable.

At the same time, I suspected the overhead for StringBuilder might make it less suitable for shorter messages yet it executes faster than ToHexA in this situation.

The only thing I expected was the performance hit associated with ToHexB which is kind of an in between worst of both worlds scenario...

So, what is going on with these two methods and their performance characteristics?

Edit to make my intentions with this question more clear

I am not particularly interested in exact performance characteristics of two methods that are closely performant. I am aware this will be different on different devices, architectures, background processes, etc etc. and better testing methods exist to control variables and what not

My purpose in asking this question was to better understand why two noticeably dissimilar (in terms of performance) approaches stack up the way they do. The accepted answer explains the mechanics of ToString in a way that satisfies this question.

One constraint of this question the exact formatting of the output was specific and (we can only muse why, I think it's pretty standard) for some reason not one of the standard output formats in C#/.NET; it was this unique format that led to the question: stacking multiple replace and concatenation operations against StringBuilder

答:
As discussed, here is a highly tuned function that is specialized for this requested output. Please forgive the "magic values" :), I threw this together as a POC :), but it is extremely fast which was the point. It avoids all string operations, StringBuilder, calling additional methods, etc.</p>

```<code>private unsafe static string ToHexA2(byte[] buffer)
{
    int length = buffer.Length;
    int num = (length * 6) + 2;
    char[] array = new char[num];
    int num2 = 0;

    fixed (char* ptr = array)
    {
        *(long*)ptr = 0x0020007B;

        for (int i = 2; i < num; i += 6)
        {
            byte b = buffer[num2++];
            *(long*)(ptr + i) = 0x00780030;
            *(long*)(ptr + i + 2) = digits[b >> 4] | (digits[b & 0x0F] << 16);
            *(long*)(ptr + i + 4) = 0x0020002C;
        }

        *(long*)(ptr + num - 2) = 0x007D0020;
    }

    return new string(array, 0, array.Length);
}
</code>```

Body:
I have created 3 different methods for converting a byte[] into a hex string using the following format: { 0xx2, ... } (Working Demo)

using System;
using System.Diagnostics;
using System.Text;

public class Program
{
    public delegate string ParseMethod(byte[] Msg);
    public class Parser
    {
        public string Name { get; private set;}
        public ParseMethod Handler { get; private set; }

        public Parser(string name, ParseMethod method)
        {
            Name = name;
            Handler = method;
        }
    }

    public static void Main()
    {
        Parser HexA = new Parser("ToHexA", ToHexA);
        Parser HexB = new Parser("ToHexB", ToHexB);
        Parser HexC = new Parser("ToHexC", ToHexC);

        TestCorrectness(HexA);
        TestCorrectness(HexB);
        TestCorrectness(HexC);

        Console.WriteLine("Small Message Performance:");
        TestPerformance(HexA, MsgSize: 10, Iterations: 1000000);
        TestPerformance(HexB, MsgSize: 10, Iterations: 1000000);
        TestPerformance(HexC, MsgSize: 10, Iterations: 1000000);
        Console.WriteLine();

        Console.WriteLine("Large Message Performance:");
        TestPerformance(HexA, MsgSize: 500, Iterations: 1000000);
        TestPerformance(HexB, MsgSize: 500, Iterations: 1000000);
        TestPerformance(HexC, MsgSize: 500, Iterations: 1000000);
        Console.WriteLine();
    }

    private static void TestCorrectness(Parser parser)
    {
        Console.WriteLine("Testing Correctness of \"{0}(byte[] Msg)\"", parser.Name);
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{}));
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97 }));
        Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97, 98, 99, 0, 100 }));
        Console.WriteLine();
    }

    private static void TestPerformance(Parser parser, int MsgSize, int Iterations)
    {
        Stopwatch sw = new Stopwatch();
        sw.Reset();

        byte[] Msg = new byte[MsgSize];

        sw.Start();
        for (uint i = 0; i < Iterations; ++i)
        {
            parser.Handler(Msg);
        }
        sw.Stop();

        Console.WriteLine("Performance for \"{0}\", {1}", parser.Name, sw.Elapsed);
    }

    private static string ToHexA(byte[] buffer)
    {
        return
            (
                "{ 0x" +
                    BitConverter.ToString(buffer).ToLower()
                        .Replace("-", ", 0x") +
                " }"
            )
            .Replace(" 0x }", "}");
    }

    private static string ToHexB(byte[] buffer)
    {
        if (buffer.Length == 0) { return "{}"; }

        const string Preamble = "{ 0x";
        const string Delimiter = ", 0x";
        const string Epilogue = " }";

        string Msg = Preamble + buffer[0].ToString("x2");
        for (int i = 1; i < buffer.Length; ++i)
        {
            Msg += Delimiter + buffer[i].ToString("x2");
        }

        return Msg += Epilogue;
    }

    private static string ToHexC(byte[] buffer)
    {
        if (buffer.Length == 0) { return "{}"; }

        const string Preamble = "{ 0x";
        const string Delimiter = ", 0x";
        const string Epilogue = " }";

        StringBuilder HexOut = new StringBuilder(
            Preamble.Length +
            (Delimiter.Length * (buffer.Length - 1)) +
            (2 * buffer.Length) +
            Epilogue.Length
        );

        HexOut.Append(Preamble);
        HexOut.Append(buffer[0].ToString("x2"));
        for (int i = 1; i < buffer.Length; ++i)
        {
            HexOut.Append(Delimiter);
            HexOut.Append(buffer[i].ToString("x2"));
        }
        HexOut.Append(Epilogue);

        return HexOut.ToString();
    }
}

Running this code I get the following performance statistics

Small Message Performance:
Performance for "ToHexA", 00:00:01.3078387
Performance for "ToHexB", 00:00:01.6939201
Performance for "ToHexC", 00:00:01.2997903

Large Message Performance:
Performance for "ToHexA", 00:00:32.5230253
Performance for "ToHexB", 00:04:23.4798762
Performance for "ToHexC", 00:00:56.2404684

I find it surprising that ToHexA (relative to ToHexC) executes faster with a longer message but slower with a shorter message. As I understand it, Replace(), +, and ToLower() all have to perform a create/copy operation because strings are immutable.

At the same time, I suspected the overhead for StringBuilder might make it less suitable for shorter messages yet it executes faster than ToHexA in this situation.

The only thing I expected was the performance hit associated with ToHexB which is kind of an in between worst of both worlds scenario...

So, what is going on with these two methods and their performance characteristics?

Edit to make my intentions with this question more clear

I am not particularly interested in exact performance characteristics of two methods that are closely performant. I am aware this will be different on different devices, architectures, background processes, etc etc. and better testing methods exist to control variables and what not

My purpose in asking this question was to better understand why two noticeably dissimilar (in terms of performance) approaches stack up the way they do. The accepted answer explains the mechanics of ToString in a way that satisfies this question.

One constraint of this question the exact formatting of the output was specific and (we can only muse why, I think it's pretty standard) for some reason not one of the standard output formats in C#/.NET; it was this unique format that led to the question: stacking multiple replace and concatenation operations against StringBuilder

Body:
As discussed, here is a highly tuned function that is specialized for this requested output. Please forgive the "magic values" :), I threw this together as a POC :), but it is extremely fast which was the point. It avoids all string operations, StringBuilder, calling additional methods, etc.

private unsafe static string ToHexA2(byte[] buffer)
{
    int length = buffer.Length;
    int num = (length * 6) + 2;
    char[] array = new char[num];
    int num2 = 0;

    fixed (char* ptr = array)
    {
        *(long*)ptr = 0x0020007B;

        for (int i = 2; i < num; i += 6)
        {
            byte b = buffer[num2++];
            *(long*)(ptr + i) = 0x00780030;
            *(long*)(ptr + i + 2) = digits[b >> 4] | (digits[b & 0x0F] << 16);
            *(long*)(ptr + i + 4) = 0x0020002C;
        }

        *(long*)(ptr + num - 2) = 0x007D0020;
    }

    return new string(array, 0, array.Length);
}


问:
Scala: Is it legit to refer to underscore parameters as x$n
Say I have this function:

```<code>val f = (x: Int) => x + x
</code>```

Now, I can rewrite this expression as

```<code>val f = (_: Int) + x$1
</code>```

This compiles because _ expands to x$1, x$2, ... internally, but is it legit to use x$n to refer to underscore parameters? Scala language specification 6.23 doesn't say any rule for this 'fresh identifier', so should this be avoided?

答:
No, it is not "legit".

The naming of "fresh identifiers" could change at any time without notice.

It is almost certainly a bug that the compiler chooses a "fresh identifier" that appears in scope.

This does not improve the readability or maintainability of the code in any way, and is likely to confuse the reader.

It's hard to imagine a reason you would actually want to do this.

Body:
Say I have this function:

val f = (x: Int) => x + x

Now, I can rewrite this expression as

val f = (_: Int) + x$1

This compiles because _ expands to x$1, x$2, ... internally, but is it legit to use x$n to refer to underscore parameters? Scala language specification 6.23 doesn't say any rule for this 'fresh identifier', so should this be avoided?


问:
R Split String By Delimiter in a column
I have a file with several lines. For example

```<code>A               B       C
awer.ttp.net    Code    554
abcd.ttp.net    Code    747
asdf.ttp.net    Part    554
xyz.ttp.net     Part    747
</code>```

I want to use R to split just column A of the table and I want a new column added to the table D, with values awe, abcd, asdf, and xyz.  Would prefer this to be done using dplyr.

答:
We can use tidyverse for this

```<code>library(dplyr)
library(tidyr)
df1 %>%
   separate(A, into = 'D', extra = 'drop', remove = FALSE) %>%
   select(LETTERS[1:4])
#             A    B   C    D
#1 awer.ttp.net Code 554 awer
#2 abcd.ttp.net Code 747 abcd
#3 asdf.ttp.net Part 554 asdf
#4  xyz.ttp.net Part 747  xyz
</code>```

Title: R Split String By Delimiter in a column

Body:
I have a file with several lines. For example

A               B       C
awer.ttp.net    Code    554
abcd.ttp.net    Code    747
asdf.ttp.net    Part    554
xyz.ttp.net     Part    747

I want to use R to split just column A of the table and I want a new column added to the table D, with values awe, abcd, asdf, and xyz.  Would prefer this to be done using dplyr.

Body:
We can use tidyverse for this

library(dplyr)
library(tidyr)
df1 %>%
   separate(A, into = 'D', extra = 'drop', remove = FALSE) %>%
   select(LETTERS[1:4])
#             A    B   C    D
#1 awer.ttp.net Code 554 awer
#2 abcd.ttp.net Code 747 abcd
#3 asdf.ttp.net Part 554 asdf
#4  xyz.ttp.net Part 747  xyz


答:
Edit, went a bit beyond scope.

You should set the data as props and add the options to an object to ensure map doesn't freak out when the props are empty.

```<code>class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    let oOptions = [];
    if( this.props.bookOptions ) {
        this.props.bookOptions.map((c) => {
            oOptions.push( <option key= {c.value} value={c.value} >{c.text}</option> );
        });
    }
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        { oOptions }
      </select>
    );
  }
}

App.defaultProps = {
  bookOptions: [
  {
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]
};
</code>```

You can either fetch the data from an endpoint at the top level  mount and pass them as props:

```<code>const resp = await fetch('/givemeprops', ...
const { data } = await resp.json();
<App bookOptions={data} />
</code>```

Or you can put your ajax call inside any component's componentDidMount react.js lifecycle method and set them as state:

```<code>componentDidMount() {
  const resp = await fetch('/givemeprops', ...
  const { data } = await resp.json();
  this.setState({ bookOptions: data });
}
</code>```

And use them from there.

```<code>let bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }];
app.get('/givemeprops',
    res.json({ bookOptions: bookOptions })
);
</code>```

There are other solutions for managing an app's props/state/interaction with the backend like Flux and Redux. I would recommend checking out graphql as well.

Some great references:

React Starter Kit

ComponentDidMount Example

Title: Issue loading data from array into a select list in react

Body:
I have the following class:

class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => {
            <option value={c.value} >{c.text}</option>
          })
        }
      </select>
    );
  }
}

If I render the select list with regular html syntax then it works perfectly, where as if I try to create it dynamically then it doesn't load anything. How would you go about creating a list dynamically in react so that it maintains its binding?

Any advice would be appreciated!

Thanks.

Body:
Edit, went a bit beyond scope.

You should set the data as props and add the options to an object to ensure map doesn't freak out when the props are empty.

class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    let oOptions = [];
    if( this.props.bookOptions ) {
        this.props.bookOptions.map((c) => {
            oOptions.push( <option key= {c.value} value={c.value} >{c.text}</option> );
        });
    }
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        { oOptions }
      </select>
    );
  }
}

App.defaultProps = {
  bookOptions: [
  {
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]
};

You can either fetch the data from an endpoint at the top level  mount and pass them as props:

const resp = await fetch('/givemeprops', ...
const { data } = await resp.json();
<App bookOptions={data} />

Or you can put your ajax call inside any component's componentDidMount react.js lifecycle method and set them as state:

componentDidMount() {
  const resp = await fetch('/givemeprops', ...
  const { data } = await resp.json();
  this.setState({ bookOptions: data });
}

And use them from there.

let bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }];
app.get('/givemeprops',
    res.json({ bookOptions: bookOptions })
);

There are other solutions for managing an app's props/state/interaction with the backend like Flux and Redux. I would recommend checking out graphql as well.

Some great references:

React Starter Kit

ComponentDidMount Example


问:
How to find newly created files in ClearCase
When I check out files I have a new branch for those files. If I create a new file it is not added into the branch until I check the files back in. Before they are checked in the new file is under /Main/LATEST. Is there any way to find all files associated with a branch including newly created files?

So far I have only been able to find all files in the branch.

答:
When I check out files I have a new branch for those files.

Only if your config spec is set to create a new branch, though. It has to have a -mkbranch rule in it (as this one)

If you add to source control a file, without checking it in immediately, it creates a /main/0 version (with an empty content file).

You can search for those file having just a version 0:

```<code>cleartool find -avobs -branch'{
    brtype(mybranch)&&!
    (version(.../mybranch/1))}'
     -print
</code>```

But if the new file was not even added to source control, then it is a private file, and you can list those as well (cleartool lsprivate in a dynamic view, for instance).

Body:
When I check out files I have a new branch for those files.

Only if your config spec is set to create a new branch, though. It has to have a -mkbranch rule in it (as this one)

If you add to source control a file, without checking it in immediately, it creates a /main/0 version (with an empty content file).

You can search for those file having just a version 0:

cleartool find -avobs -branch'{
    brtype(mybranch)&&!
    (version(.../mybranch/1))}'
     -print

But if the new file was not even added to source control, then it is a private file, and you can list those as well (cleartool lsprivate in a dynamic view, for instance).


问:
I need user input to tell the program which list to use?
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

```<code>import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)
</code>```

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

```<code>import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)
</code>```

now the variable secretword stores the word that is randomly chosen from the list.

答:
You can use Python dictionary or you can add option and take option number from the user. </p>

```<code>import random
print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('1.Press 1 for Animal, 2.Press 2 for Clothing')
print('3.Press 3 for Weather, 4.Press 4 for Colors')

category=int(input())

# you can iterate over this
if category == 1: random.choice(Animal)
elif category == 2: random.choice(Clothing)
elif category == 3: random.choice(Weather)
elif category == 4: random.choice(Colors)

randomwordindex = random.randint(1,7)
</code>```

Body:
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)

now the variable secretword stores the word that is randomly chosen from the list.

Body:
You can use Python dictionary or you can add option and take option number from the user.

import random
print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('1.Press 1 for Animal, 2.Press 2 for Clothing')
print('3.Press 3 for Weather, 4.Press 4 for Colors')

category=int(input())

# you can iterate over this
if category == 1: random.choice(Animal)
elif category == 2: random.choice(Clothing)
elif category == 3: random.choice(Weather)
elif category == 4: random.choice(Colors)

randomwordindex = random.randint(1,7)


问:
two different sounds need to play when hovering an image?
I am a beginner in JavaScript, CSS and HTML. I have two images at the top of a bag that I want to play two different sounds when hovered. However, when I hover on either of the images they play the same sound. I would like to know what I am doing wrong and how to get the images to play two different sounds. thank you!!!         </p>

```<code><script>
   function play(){
   var audio = document.getElementById("audio");
   audio.play();
             }
   </script>

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play()" onmouseout="stop()">
 <audio id="audio" src="Sounds/divers.mp3" ></audio>

    <script>
  function play(){
       var audio = document.getElementById("audio");
       audio.play();
                 }
   </script>

<img src="Photos/harptour.png" height="150" width="150" value="PLAY"  onmouseover="play()" onmouseout="stop()">
<audio id="audio" src="Sounds/cosmia.mp3" ></audio>
</code>```

答:
You can pass parameter into your play() funciton.

```<code>function play(selector){
    document.getElementById(selector).play();
}
</code>```

Then, assign different id to different <audio>:

```<code><audio id="anID" src="Sounds/divers.mp3" ></audio>
<audio id="anotherID" src="Sounds/cosmia.mp3" ></audio>
</code>```

Then, in your inline function call:

```<code><img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play('anID')" onmouseout="stop()">

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play('anotherID')" onmouseout="stop()">
</code>```

Usually, we don't assign identical id to more than 1 element because it serves like an identity of the element, similar to our identity card number where each person has a unique number.

The function's parameter is like a predefined variable for the particular function. Unlike the usual variable declaration var bla = 'bla', value of function parameter is given at the time of calling the function like what you see above play('audio1').

Body:
I am a beginner in JavaScript, CSS and HTML. I have two images at the top of a bag that I want to play two different sounds when hovered. However, when I hover on either of the images they play the same sound. I would like to know what I am doing wrong and how to get the images to play two different sounds. thank you!!!

 <audio id="audio" src="Sounds/divers.mp3" ></audio>

<audio id="audio" src="Sounds/cosmia.mp3" ></audio>

Body:
You can pass parameter into your play() funciton.

function play(selector){
    document.getElementById(selector).play();
}

Then, assign different id to different <audio>:

<audio id="anID" src="Sounds/divers.mp3" ></audio>
<audio id="anotherID" src="Sounds/cosmia.mp3" ></audio>

Then, in your inline function call:

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play('anID')" onmouseout="stop()">

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play('anotherID')" onmouseout="stop()">

Usually, we don't assign identical id to more than 1 element because it serves like an identity of the element, similar to our identity card number where each person has a unique number.

The function's parameter is like a predefined variable for the particular function. Unlike the usual variable declaration var bla = 'bla', value of function parameter is given at the time of calling the function like what you see above play('audio1').


问:
Problems of using curl on windows compared to mac
i use xampp apache to run some of my php files.

In one of my php file i use curl to get data from external website, on my windows machine, everything works fine. However, on my mac machine, my browser just can not run those files.. it just takes very long to load, and in the end stop loading.

Attached is one of my php file:

```<code><?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);

print $contents;
?>
</code>```

I am really desprate on why mac machine can not run these files? is there another way to go about doing this on a mac machine? THanks all for your help!

EDIT: [SOLVED] Thanks all for your help. Manage to solve it, due, to because i am connecting to the net using a proxy server...thus my script need to handle that.

Code used:

```<code><?php
$aContext = array(
'http' => array(
'proxy' =>'tcp://xxxxx:xx',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);

$content = file_get_contents("http://www.example.com", False, $csContext);

print $content;
?>
</code>```

答: Do you have the CURL extension installed on your MAC machine. Check that by running a php script with phpinfo(); in it and see if you have the CURL installed/enabled.</p>

Body:
i use xampp apache to run some of my php files.

In one of my php file i use curl to get data from external website, on my windows machine, everything works fine. However, on my mac machine, my browser just can not run those files.. it just takes very long to load, and in the end stop loading.

Attached is one of my php file:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);

print $contents;
?>

I am really desprate on why mac machine can not run these files? is there another way to go about doing this on a mac machine? THanks all for your help!

EDIT: [SOLVED] Thanks all for your help. Manage to solve it, due, to because i am connecting to the net using a proxy server...thus my script need to handle that.

Code used:

<?php
$aContext = array(
'http' => array(
'proxy' =>'tcp://xxxxx:xx',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);

$content = file_get_contents("http://www.example.com", False, $csContext);

print $content;
?>


问:
hiding of template parameter of member template
from temp.local :

In the definition of a member of a class template that appears outside
  of the class template definition, the name of a member of the class
  template hides the name of a template-parameter of any enclosing class
  templates (but not a template-parameter of the member if the member is
  a class or function template).
  [ Example:

```<code>template<class T> struct A {
  struct B { /* ... */ };
  typedef void C;
  void f();
  template<class U> void g(U);
};

template<class B> void A<B>::f() {
  B b;              // A's B, not the template parameter
}

template<class B> template<class C> void A<B>::g(C) {
  B b;              // A's B, not the template parameter
  C c;              // the template parameter C, not A's C
}
</code>```

— end example ]

the problem is that, each compiler, that i have tried ( g++, vc, icc, clang ), treats C in A::g(C) as A's member name and doesn't compile that example.

Is this a common bug.?

答:
While the link you gave appears to be a draft and explicitly states it is not a part of any standard (http://eel.is/c++draft/), this particular clause in the draft appears to be identical to ISO C++ 14.6.1, paragraph 7.

So it does indeed seem to be either a common compiler bug or a clause that conflicts with and lost out to other clauses. I verified the example doesn't compile on MacOS Clang v802.0.42). Since you say all the major compilers emit errors here, I would suspect this clause is not reasonable to implement due to conflicts with some other clause(s).

EDIT: I also found a discussion within the standards community here related to this topic. The depth with which it gets discussed here suggests to me that this rule is contentious and may even be changed.

Body:
from temp.local :

In the definition of a member of a class template that appears outside
  of the class template definition, the name of a member of the class
  template hides the name of a template-parameter of any enclosing class
  templates (but not a template-parameter of the member if the member is
  a class or function template).
  [ Example:

template<class T> struct A {
  struct B { /* ... */ };
  typedef void C;
  void f();
  template<class U> void g(U);
};

template<class B> void A::f() {
  B b;              // A's B, not the template parameter
}

template<class B> template<class C> void A::g(C) {
  B b;              // A's B, not the template parameter
  C c;              // the template parameter C, not A's C
}

— end example ]

the problem is that, each compiler, that i have tried ( g++, vc, icc, clang ), treats C in A::g(C) as A's member name and doesn't compile that example.

Is this a common bug.?


答:
Try This:</p>

```<code><script>
function playDriver(){
   var audio = document.getElementById("audio-driver");
   audio.play();
             }

function playCosmia(){
       var audio = document.getElementById("audio-cosmia");
       audio.play();
                 }
   </script>

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="playDriver()" onmouseout="stop()">
 <audio id="audio-driver" src="Sounds/divers.mp3" ></audio>

<img src="Photos/harptour.png" height="150" width="150" value="PLAY"  onmouseover="playCosmia()" onmouseout="stop()">
<audio id="audio-cosmia" src="Sounds/cosmia.mp3" ></audio>
</code>```

Title: two different sounds need to play when hovering an image?

Body:
Try This:

<script>
function playDriver(){
   var audio = document.getElementById("audio-driver");
   audio.play();
             }

function playCosmia(){
       var audio = document.getElementById("audio-cosmia");
       audio.play();
                 }
   </script>

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="playDriver()" onmouseout="stop()">
 <audio id="audio-driver" src="Sounds/divers.mp3" ></audio>

<img src="Photos/harptour.png" height="150" width="150" value="PLAY"  onmouseover="playCosmia()" onmouseout="stop()">
<audio id="audio-cosmia" src="Sounds/cosmia.mp3" ></audio>


问:
Using immutability-helper in typescript and react
I imported update from @types/immutability-helper. Now I want to push an item to the an array in a React's component state.

The syntax in index.d.ts file says:

```<code>interface UpdateFunction {
    (value: any[], spec: UpdateArraySpec): any[];
    (value: {}, spec: UpdateSpec): any;
    extend: (commandName: string, handler: CommandHandler) => any;
}
</code>```

and UpdateArraySpec is

```<code>interface UpdateArraySpec extends UpdateSpecCommand {
    $push?: any[];
    $unshift?: any[];
    $splice?: any[][];
    [customCommand: string]: any;
}
</code>```

does it mean I have to write 2 updates?:

```<code>this.setState(update(this.state, update(this.state.Markers, { $push: [info] })));
</code>```

Or what?

答:
This is the syntax that worked for me:

```<code>this.setState(update(this.state, { Markers: { $push: [info] } }));
</code>```

This is not obvious from typescript definition file. But the docs says something like it.

Body:
I imported update from @types/immutability-helper. Now I want to push an item to the an array in a React's component state.

The syntax in index.d.ts file says:

interface UpdateFunction {
    (value: any[], spec: UpdateArraySpec): any[];
    (value: {}, spec: UpdateSpec): any;
    extend: (commandName: string, handler: CommandHandler) => any;
}

and UpdateArraySpec is

interface UpdateArraySpec extends UpdateSpecCommand {
    $push?: any[];
    $unshift?: any[];
    $splice?: any[][];
    [customCommand: string]: any;
}

does it mean I have to write 2 updates?:

this.setState(update(this.state, update(this.state.Markers, { $push: [info] })));

Or what?

Body:
This is the syntax that worked for me:

this.setState(update(this.state, { Markers: { $push: [info] } }));

This is not obvious from typescript definition file. But the docs says something like it.


问:
Does a CNAME "hide" the domain you're CNAME'ing to?
Say domain A.COM has a CNAME for www which points to B.COM, and B.COM also has a www CNAME which points to C.COM, and C.COM has multiple A records/IP's.

Is there any way for someone snooping around to query A.COM and see that it's simply pointing to B.COM? Or is it impossible to get that information without having full access to the DNS zone manager (meaning all they would see are the final IP's that C.COM resolve to)?

EDIT: I'm using CloudFlare (A, B, & C), so I'm not sure if that changes the answer. It seems to me they all point to CloudFlare as A records and you can't pull out a CNAME?

答:
No, a CNAME does not hide anything. You can run a dig WWW.A.COM and it will show you the CNAME pointer. That said, casual users browsing your website will never see or know that your website points to C.COM.

Example:

```<code>$ dig ak.nextag.com

; <<>> DiG 9.8.3-P1 <<>> ak.nextag.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9813
;; flags: qr rd ra; QUERY: 1, ANSWER: 11, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;ak.nextag.com.         IN  A

;; ANSWER SECTION:
ak.nextag.com.      879 IN  CNAME   img.nextag.com.
img.nextag.com.     86379   IN  CNAME   img05.static-nextag.com.
img05.static-nextag.com. 7179   IN  CNAME   d2lhs8hfggtuez.cloudfront.net.
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.195
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.200
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.186
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.218
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.251
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.132
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.42
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.7

;; Query time: 106 msec
;; SERVER: 10.100.51.31#53(10.100.51.31)
;; WHEN: Sat Jul  8 01:18:44 2017
;; MSG SIZE  rcvd: 254
</code>```

Body:
No, a CNAME does not hide anything. You can run a dig WWW.A.COM and it will show you the CNAME pointer. That said, casual users browsing your website will never see or know that your website points to C.COM.

Example:

$ dig ak.nextag.com

; <<>> DiG 9.8.3-P1 <<>> ak.nextag.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9813
;; flags: qr rd ra; QUERY: 1, ANSWER: 11, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;ak.nextag.com.         IN  A

;; ANSWER SECTION:
ak.nextag.com.      879 IN  CNAME   img.nextag.com.
img.nextag.com.     86379   IN  CNAME   img05.static-nextag.com.
img05.static-nextag.com. 7179   IN  CNAME   d2lhs8hfggtuez.cloudfront.net.
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.195
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.200
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.186
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.218
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.251
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.132
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.42
d2lhs8hfggtuez.cloudfront.net. 39 IN    A   54.230.143.7

;; Query time: 106 msec
;; SERVER: 10.100.51.31#53(10.100.51.31)
;; WHEN: Sat Jul  8 01:18:44 2017
;; MSG SIZE  rcvd: 254


问:
I have json object in constructor in my component and how to use the object when using click function
I have given below is my object in constructor.

I am passing value from previous conmponent to below component. and i
  am getting the item json object. but i need to use below object when i
  am clicking.

```<code>constructor(public navCtrl: NavController, public navParams: NavParams) {
     this.item= navParams.get('item');
</code>```

}

How i will use the item json object when i am click the button?

答:
You can just use it as

```<code><button (click)="myFunc()"></button>
</code>```

and you can use it in typescript as,

```<code>myFunc(){
  console.log(this.item);
}
</code>```

Body:
I have given below is my object in constructor.

I am passing value from previous conmponent to below component. and i
  am getting the item json object. but i need to use below object when i
  am clicking.

constructor(public navCtrl: NavController, public navParams: NavParams) {
     this.item= navParams.get('item');

}

How i will use the item json object when i am click the button?

Body:
You can just use it as

<button (click)="myFunc()"></button>

and you can use it in typescript as,

myFunc(){
  console.log(this.item);
}


问:
How to programmatically change focus from devtools to page upon keyboard command
Is it possible? Keyboard commands are detected even when the focus is within devtools.

Is there a trick using the chrome extension API to then defocus devtools and focus the page?

答:
The API to change focus to a different window is: windows.update. Specifically, the focused property. It can definitely move the focus away from DevTools windows. You would do something like to bring "the next window in the z-order to the front":

chrome.windows.update(devToolsWindowId,{focused:false});
```

<p>Alternately, you could instead focus a different specific window:</p>

<pre class="lang-js prettyprint-override"><code>chrome.windows.update(someOtherWindowId,{focused:true});
</code>```

Body:
The API to change focus to a different window is: windows.update. Specifically, the focused property. It can definitely move the focus away from DevTools windows. You would do something like to bring "the next window in the z-order to the front":

chrome.windows.update(devToolsWindowId,{focused:false});

Alternately, you could instead focus a different specific window:

chrome.windows.update(someOtherWindowId,{focused:true});


问:
Segmentation fault using Swift Accelerate vDSP_ctoz
I'm trying to convert an interleaved DSPComplex vector to a DSPSplitComplex vector, using vDSP_ctoz from the Swift Accelerate library. The last line of the code below produces the error Segmentation fault: 11

I don't understand why vDSP_ctoz would try to access out-of-bound memory when I've allocated large vectors and am only trying to process a small number of elements. The vectors are size 2048 and the argument for N (number of elements to process) in vDSP_ctoz is 1.

I've also tried using different stride and N values when calling vDSP_ctoz, to no avail.

```<code>// set stride values
let dspComplexStride = MemoryLayout<DSPComplex>.stride
let dspSplitComplexStride = MemoryLayout<DSPSplitComplex>.stride

// make interleaved vector
var interleaved = UnsafeMutablePointer<DSPComplex>.allocate(capacity: 2048)
for index in 0..<16 {
    interleaved[index] = DSPComplex(real: Float(2*index), imag: Float(2*index+1))
}

// make split vector
var splitComplex = UnsafeMutablePointer<DSPSplitComplex>.allocate(capacity: 2048)
vDSP_ctoz(
    interleaved, dspComplexStride, splitComplex, dspSplitComplexStride, 1
)
</code>```

答:
DSPSplitComplex is a structure containing pointers arrays,
so you need a single DSPSplitComplex element and must allocate
storage for its realp and imagp properties.

The "stride" arguments are not measured in bytes but in "element" units.
So you pass __IZ == 1 because you want to fill contiguous elements
in the destination arrays.

It may not be obvious that you have to pass __IC == 2 for the source array, i.e.
the stride of the source array is given in Float units and not in
DSPComplex units. This can be deduced from the vDSP_ctoz documentation
which mentions that the function effectively does

```<code>for (n = 0; n < N; ++n)
{
  Z->realp[n*IZ] = C[n*IC/2].real;
  Z->imagp[n*IZ] = C[n*IC/2].imag;
}
</code>```

Finally, the last argument of vDSP_ctoz is the number of elements to
process.

Putting it all together, this is how it should work:

```<code>import Accelerate

let N = 16

var interleaved = UnsafeMutablePointer<DSPComplex>.allocate(capacity: N)
for index in 0..<N {
    interleaved[index] = DSPComplex(real: Float(2*index), imag: Float(2*index+1))
}

let realp = UnsafeMutablePointer<Float>.allocate(capacity: N)
let imagp = UnsafeMutablePointer<Float>.allocate(capacity: N)
var splitComplex = DSPSplitComplex(realp: realp, imagp: imagp)

vDSP_ctoz(interleaved, 2, &splitComplex, 1, vDSP_Length(N))

for index in 0..<N {
    print(splitComplex.realp[index], splitComplex.imagp[index])
}
</code>```

and of course you have to release the memory eventually.

Body:
I'm trying to convert an interleaved DSPComplex vector to a DSPSplitComplex vector, using vDSP_ctoz from the Swift Accelerate library. The last line of the code below produces the error Segmentation fault: 11

I don't understand why vDSP_ctoz would try to access out-of-bound memory when I've allocated large vectors and am only trying to process a small number of elements. The vectors are size 2048 and the argument for N (number of elements to process) in vDSP_ctoz is 1.

I've also tried using different stride and N values when calling vDSP_ctoz, to no avail.

// set stride values
let dspComplexStride = MemoryLayout<DSPComplex>.stride
let dspSplitComplexStride = MemoryLayout<DSPSplitComplex>.stride

// make interleaved vector
var interleaved = UnsafeMutablePointer<DSPComplex>.allocate(capacity: 2048)
for index in 0..<16 {
    interleaved[index] = DSPComplex(real: Float(2*index), imag: Float(2*index+1))
}

// make split vector
var splitComplex = UnsafeMutablePointer<DSPSplitComplex>.allocate(capacity: 2048)
vDSP_ctoz(
    interleaved, dspComplexStride, splitComplex, dspSplitComplexStride, 1
)

Body:
DSPSplitComplex is a structure containing pointers arrays,
so you need a single DSPSplitComplex element and must allocate
storage for its realp and imagp properties.

The "stride" arguments are not measured in bytes but in "element" units.
So you pass __IZ == 1 because you want to fill contiguous elements
in the destination arrays.

It may not be obvious that you have to pass __IC == 2 for the source array, i.e.
the stride of the source array is given in Float units and not in
DSPComplex units. This can be deduced from the vDSP_ctoz documentation
which mentions that the function effectively does

for (n = 0; n < N; ++n)
{
  Z->realp[n*IZ] = C[n*IC/2].real;
  Z->imagp[n*IZ] = C[n*IC/2].imag;
}

Finally, the last argument of vDSP_ctoz is the number of elements to
process.

Putting it all together, this is how it should work:

import Accelerate

let N = 16

var interleaved = UnsafeMutablePointer<DSPComplex>.allocate(capacity: N)
for index in 0..<N {
    interleaved[index] = DSPComplex(real: Float(2*index), imag: Float(2*index+1))
}

let realp = UnsafeMutablePointer<Float>.allocate(capacity: N)
let imagp = UnsafeMutablePointer<Float>.allocate(capacity: N)
var splitComplex = DSPSplitComplex(realp: realp, imagp: imagp)

vDSP_ctoz(interleaved, 2, &splitComplex, 1, vDSP_Length(N))

for index in 0..<N {
    print(splitComplex.realp[index], splitComplex.imagp[index])
}

and of course you have to release the memory eventually.