问:
JavaFX force recompute binding
I wanted to achieve something resembling functional reactive programming in JavaFX and I thought that since JavaFX already supports listeners and bindings between properties it should be fairly easy, so I have created small framework for bindings with conversion, e.g. I now am able to do something like this (example in Scala, but it should be possible to understand what I mean):

```<code>val property1: Property[String]
val property2: Property[Path]

Bindings.Conversions
    .bindUni(property1).to(property2)
    .using(p => p.getFileName.toString)
    .connect()
</code>```

Here I bind value of property2 (which is a java.nio.file.Path) through a conversion function which takes the last part of the path and converts to a string to the property1 (which is string).

The implementation of this is really simple (even for bidirectional bindings; I simply took some code from openjfx BidirectionalBinding class, translated it to Scala and adapted it for conversions), and I wonder why there is no such thing in JavaFX already.

This all works well, and I even can create complex chains of such bindings. All is OK unless conversion function depends on some external state.

Suppose, for example, that you have the following chain of bindings:

```<code>Text field value  -1->  intermediate java.nio.file.Path  -2->  another String  -->  Label
</code>```

When text field changes, Path and String are recomputed automatically, and the value of the String property is written to the label. All is wonderful. But suppose that -2-> conversion should depend on toggled state of some checkbox:

```<code>                                       Checkbox state  ---+
                                                          |
Text field value  -1->  intermediate java.nio.file.Path  -2->  another String  -->  Label
</code>```

That is, when checkbox is checked, transformation should be slightly different.

Direct implementation of such construction won't work, obviously, because change of checkbox state does not toggle recomputation of the transformation chain. However, I found that JavaFX does not provide any means for forcing change events. I tried overriding SimpleStringProperty, for example, and exposing its fireValueChangedEvent() method, but this didn't help. Currently I'm doing something like textField.setText(""); textField.setText(oldValue); but this is very ugly and is not the right way, obviously.

Am I missing something, and it is really possible to do what I want to do, or there is no such thing at all and I'm completely screwed here?

If the answer is no, then I think this severly damages expressiveness of the whole framework. I understand that I really can do what I want to with a number of listeners, but this will be ugly, and I want to make the whole thing as general as possible.

答:
As as "ugly" workaround I ended up randomly changing the values without changing the meaning. E.g. for a double value I'd add as small random amount to force a change or for a string value I'd toggle and invisible space. That's all not nice but will get the effect of triggering the property change for a start.

Things get worse in a multithreaded environment. There it can happen that the bounded property will not get the change trigger if the binding happens to be just slightly after the initial setting of the property. If you now set the property to the same value the value will be considered as not changed and the bounded property will not pick up the initial value but stay at the null or default value. Very ugly!

Title: JavaFX force recompute binding

Body:
I wanted to achieve something resembling functional reactive programming in JavaFX and I thought that since JavaFX already supports listeners and bindings between properties it should be fairly easy, so I have created small framework for bindings with conversion, e.g. I now am able to do something like this (example in Scala, but it should be possible to understand what I mean):

val property1: Property[String]
val property2: Property[Path]

Bindings.Conversions
    .bindUni(property1).to(property2)
    .using(p => p.getFileName.toString)
    .connect()

Here I bind value of property2 (which is a java.nio.file.Path) through a conversion function which takes the last part of the path and converts to a string to the property1 (which is string).

The implementation of this is really simple (even for bidirectional bindings; I simply took some code from openjfx BidirectionalBinding class, translated it to Scala and adapted it for conversions), and I wonder why there is no such thing in JavaFX already.

This all works well, and I even can create complex chains of such bindings. All is OK unless conversion function depends on some external state.

Suppose, for example, that you have the following chain of bindings:

Text field value  -1->  intermediate java.nio.file.Path  -2->  another String  -->  Label

When text field changes, Path and String are recomputed automatically, and the value of the String property is written to the label. All is wonderful. But suppose that -2-> conversion should depend on toggled state of some checkbox:

                                       Checkbox state  ---+
                                                          |
Text field value  -1->  intermediate java.nio.file.Path  -2->  another String  -->  Label

That is, when checkbox is checked, transformation should be slightly different.

Direct implementation of such construction won't work, obviously, because change of checkbox state does not toggle recomputation of the transformation chain. However, I found that JavaFX does not provide any means for forcing change events. I tried overriding SimpleStringProperty, for example, and exposing its fireValueChangedEvent() method, but this didn't help. Currently I'm doing something like textField.setText(""); textField.setText(oldValue); but this is very ugly and is not the right way, obviously.

Am I missing something, and it is really possible to do what I want to do, or there is no such thing at all and I'm completely screwed here?

If the answer is no, then I think this severly damages expressiveness of the whole framework. I understand that I really can do what I want to with a number of listeners, but this will be ugly, and I want to make the whole thing as general as possible.


来源: stackexchange

问:
Javascript Web Worker in a Loop
I'm map()ing 2 things, and in each map iteration I'm using a web worker to get a value that I want to assign to the thing that was the thing during the iteration when the web worker call was made. My issue is that the map finishes iterating before the web worker can respond, so all values it returns are assigned to the last "thing" that was iterated. What are some good patterns for this situation? Thanks, Ted</p>

答: In my map loop before each web worker call, I created a unique ID for the call. I created an object keyed by this ID to track the loop indexes that the call related to. I fed the ID into and out of the web worker and used it to assign the values returned from the worker.</p>

ContentLicense: CC BY-SA 3.0

Title: Javascript Web Worker in a Loop


问:
Biztalk web service ports and what happens when the port/application is stopped
I have a question around biztalk and what happens when certain conditions around web service ports are met.

basically we have two applications - a main application (lets call it 'MainApplication') (containing the orchestration) and a web service application (lets call it 'MainApplicationWS'), where we expose a web service (created from biztalks web service tool) to take messages from wherever.

we have a testing tool which replays messages to the MainApplicationWS to simulate messages coming through from various external systems.

I have noticed that if we partial stop the MainApplicationWS application, and send messages through to the web service listed as a recieve location, nothing happens (obviously!) (also, the web service is still running, even though its been delisted as a recieve location). however, if i start up the MainApplicationWS again and bounce the host instances the messages are picked up from somewhere and played through to the orchestration and through to our application.

Im just a bit puzzled as to where its storing these messages while the MainApplicationWS is partially stopped. is the web service somehow hanging on to these? or does it still post through to the biztalk message box?

any clarification would be greatly appreciated :)

cheers,
adam

答:
In short, I can't repeat your behaviour in Biztalk 2009. The closest to 'queueing' messages is if the orchestration is stopped but remains enlisted, such that messages are suspended resumable.

In long - I'm not quite sure what you mean by 'delisted as a receive location'. In Biztalk 2009:

Receive Locations can be enabled or disabled

Orchestrations can be stopped, and unenlisted

A Partial Stop on your BTS application disables receive ports and stops orchestrations (but doesn't unenlist them)

A full stop stops and unenlists orchestrations

The below is observed behaviour on BizTalk 2009 for a simple orchestration with a WCF Request/Response port, which receives a message, Maps the Send back to the same Port
The port is Direct Bound (MessageBox).

If the Isolated Host App Pool is disabled in IIS

A synchronous error is returned to the client - Standard IIS Error (503 Service Unavailable etc)
BizTalk receives no messages at all

If the BizTalk receive Location is disabled

WSDL: Syncrhonous error returned to the client - The Messaging Engine failed to register the adapter for "WCF-BasicHttp" for the receive location "xyz.svc". Please verify that the receive location exists, and that the isolated adapter runs under an account that has access to the BizTalk databases

Service Call : The requested service, xyz.svc could not be activated. See the server's diagnostic trace logs for more information.

If the Orchestration is stopped, but not unenlisted

The received message is Suspended, resumable. The client times out (no response is issued).
If the orch is started and the message resumed, the message is then processed. The client will only get a successful reply if the orch start and the suspended message resume are done before the client's configured WS / WCF timeout.

If the Orchestration is unenlisted

The received message is Suspended, not resumable.
The client receives an error - The server was unable to process the request due to an internal error.

With the WCF CustomBinding it is also possible to listen directly on the relevant BizTalk ReceiveHost (i.e. no need for IIS at all to listen to BasicHTTP or WSHTTP, although we generally still use the Wizard generated svc in IIS solely for the hosting and publication of the WSDL. We then create a new WCF Custom receive location directly in BizTalk and point the client to this)

Hope this helps?

ContentLicense: CC BY-SA 2.5


问:
Is use of `auto` for a function argument against the C++ standard?
Does code like this:

```<code>auto add(auto a, auto b) { return a + b; }
</code>```

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

答:
At the moment this is invalid but maybe in a future version of the standard it will be the equivalent of:</p>

```<code>template<typename T1, typename T2>
auto add(T1 a, T2 b) {return a + b;}
</code>```

Body:
Does code like this:

auto add(auto a, auto b) { return a + b; }

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

Body:
At the moment this is invalid but maybe in a future version of the standard it will be the equivalent of:

template<typename T1, typename T2>
auto add(T1 a, T2 b) {return a + b;}


问:
Aggregate fields selectively based on MAX(value)
I have a very large union query that produces the following results:

```<code>p_id       title_id        title        is_live

1          37              TITANIC      1
2          37              TITANIC      0

3          41              AVATAR       0
4          41              AVATAR       0

5          44              HOME ALONE   0

6          11              COMPUTE      1
7          11              COMPUTE      1
8          11              COMPUTE      1
</code>```

From this result, I want to aggregate it so that I get at least one of each title (title_id), but all titles with is_live = True. (In other words, for each title_id, I want to get exactly one result if MAX(is_live)=0, but all results if MAX(is_live)=1 for that title_id.) Here's an example of the result set that I want, with an explanation for each title:

```<code>p_id       title_id        title        is_live

1          37              TITANIC      1 // live one for titanic

3          41              AVATAR       0 # at least one of each title (which one doesn't matter)

5          44              HOME ALONE   0 /* at least one of each title */

6          11              COMPUTE      1 // keep all, since all are live
7          11              COMPUTE      1
8          11              COMPUTE      1
</code>```

The query that I have so far is along the lines of the following:

```<code>SELECT * FROM (
    80-line UNION query
) d
GROUP BY
  d.title_id
</code>```

But this of course isn't accurate enough and is more an outline. How would I do the above?

Here is a SQLFiddle for the question: http://sqlfiddle.com/#!9/739a36/2/0

答:
One way to do it using union all, first selecting all is_live true rows and selecting one false is_live row for the title_id's not previously selected.

```<code>select *
from `a`
where is_live
union all
select max(p_id),title_id,max(title),max(is_live)
from `a` a1
where not is_live
and not exists (select 1 from `a` a2
                where a1.title_id=a2.title_id and a2.is_live)
group by title_id
</code>```

Body:
I have a very large union query that produces the following results:

p_id       title_id        title        is_live

1          37              TITANIC      1
2          37              TITANIC      0

3          41              AVATAR       0
4          41              AVATAR       0

5          44              HOME ALONE   0

6          11              COMPUTE      1
7          11              COMPUTE      1
8          11              COMPUTE      1

From this result, I want to aggregate it so that I get at least one of each title (title_id), but all titles with is_live = True. (In other words, for each title_id, I want to get exactly one result if MAX(is_live)=0, but all results if MAX(is_live)=1 for that title_id.) Here's an example of the result set that I want, with an explanation for each title:

p_id       title_id        title        is_live

1          37              TITANIC      1 // live one for titanic

3          41              AVATAR       0 # at least one of each title (which one doesn't matter)

5          44              HOME ALONE   0 /* at least one of each title */

6          11              COMPUTE      1 // keep all, since all are live
7          11              COMPUTE      1
8          11              COMPUTE      1

The query that I have so far is along the lines of the following:

SELECT * FROM (
    80-line UNION query
) d
GROUP BY
  d.title_id

But this of course isn't accurate enough and is more an outline. How would I do the above?

Here is a SQLFiddle for the question: http://sqlfiddle.com/#!9/739a36/2/0

Body:
One way to do it using union all, first selecting all is_live true rows and selecting one false is_live row for the title_id's not previously selected.

select *
from `a`
where is_live
union all
select max(p_id),title_id,max(title),max(is_live)
from `a` a1
where not is_live
and not exists (select 1 from `a` a2
                where a1.title_id=a2.title_id and a2.is_live)
group by title_id


问:
Passing function object as a parameter to another function
I am trying to understand the flow of the following code snippet -

```<code>var inner = function (a){
    console.log("a is -- ", 9);
}

var outer = function(b){
    console.log("Executing outer()");
    b();
}

outer(inner(5));
</code>```

The output currently is -

```<code>a is --  9
Executing outer()
app.js:6 Uncaught TypeError: b is not a function
at outer (app.js:6)
at app.js:9
</code>```

I am expecting the following -

```<code>Executing outer()
a is --  9
</code>```

I understand that in the statement outer(inner(9)) : inner(9) is a function call that evaluates (runs the code contained within the inner() function), but i want the code inside the outer() function to evaluate the code within inner(). Basically, i want to pass 9 as a variable to outer() so that it can pass it to inner()

Please point me to any online resource that will help me understand this concept better. Also, please mark this question as duplicate if already answered. Thanks!

答:
The call within outer is made without passing any arguments to the callback function b:

```<code>b();
</code>```

So as you say, you need to pass in as b a function that, when called without arguments, effectively makes the call inner(5) and returns its value.

However compelling the visual similarity of such a b with the expression inner(5), the result of the latter is something else: it is not "a function that, when called...", but rather the return value of inner: undefined.

What you need can be achieved either as a classic Javascript closure:

```<code>outer(function() { inner(5); }); // return omitted as value uninteresting
</code>```

or using Function.prototype.bind:

```<code>outer(inner.bind(this, 5));
</code>```

or using a more modern ES6 arrow function:

```<code>outer(() => inner(5))
</code>```

Body:
I am trying to understand the flow of the following code snippet -

var inner = function (a){
    console.log("a is -- ", 9);
}

var outer = function(b){
    console.log("Executing outer()");
    b();
}

outer(inner(5));

The output currently is -

a is --  9
Executing outer()
app.js:6 Uncaught TypeError: b is not a function
at outer (app.js:6)
at app.js:9

I am expecting the following -

Executing outer()
a is --  9

I understand that in the statement outer(inner(9)) : inner(9) is a function call that evaluates (runs the code contained within the inner() function), but i want the code inside the outer() function to evaluate the code within inner(). Basically, i want to pass 9 as a variable to outer() so that it can pass it to inner()

Please point me to any online resource that will help me understand this concept better. Also, please mark this question as duplicate if already answered. Thanks!

Body:
The call within outer is made without passing any arguments to the callback function b:

b();

So as you say, you need to pass in as b a function that, when called without arguments, effectively makes the call inner(5) and returns its value.

However compelling the visual similarity of such a b with the expression inner(5), the result of the latter is something else: it is not "a function that, when called...", but rather the return value of inner: undefined.

What you need can be achieved either as a classic Javascript closure:

outer(function() { inner(5); }); // return omitted as value uninteresting

or using Function.prototype.bind:

outer(inner.bind(this, 5));

or using a more modern ES6 arrow function:

outer(() => inner(5))


问:
Hibernate ManyToMany save
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.</p>

```<code>class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}
</code>```

答:
As a variant you can use like this 'PrePersist' util method to 'link' events and audiences:

```<code>@Entity
public class Event {

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private final Set<Audience> audiences = new HashSet<>();

    @PrePersist
    public void addAudiences() {
        audiences.forEach(audience -> audience.getEvents().add(this));
    }
}

@Entity
public class Audience {

    @ManyToMany(mappedBy = "audiences")
    private final Set<Event> events = new HashSet<>();

    //...
    public Set<Event> getEvents() {
        return events;
    }
}
</code>```

More info about ManyToMany association and 'utilities  methods': Hibernate User Guide

My example and tests.

Title: Hibernate ManyToMany save

Body:
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.

class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}

Body:
As a variant you can use like this 'PrePersist' util method to 'link' events and audiences:

@Entity
public class Event {

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private final Set<Audience> audiences = new HashSet<>();

    @PrePersist
    public void addAudiences() {
        audiences.forEach(audience -> audience.getEvents().add(this));
    }
}

@Entity
public class Audience {

    @ManyToMany(mappedBy = "audiences")
    private final Set<Event> events = new HashSet<>();

    //...
    public Set<Event> getEvents() {
        return events;
    }
}

More info about ManyToMany association and 'utilities  methods': Hibernate User Guide

My example and tests.


问:
Programmatically creating validation list
I have an array of data that is coming in to the VBA code from an external source. I want to be able to assign that data to use as a validation in a dropdown box in a cell in one of the sheets in this workbook. However, I do not want to copy that data into a sheet and then use a named range - there may be quite a lot of data, and that would not feel very efficient!

I'm sure there must be a way - but I haven't found one yet. Any ideas?

答:
Place the data in some text file delimiting it with comma eg(a,b,c).

Read that data using VBA into a string variable eg ValidationList.

Use some thing like this

With Range("A1").Validation

 .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _

 xlBetween, Formula1:=ValidationList

 .IgnoreBlank = True

 .InCellDropdown = True

 .InputTitle = ""

 .ErrorTitle = ""

 .InputMessage = ""

 .ErrorMessage = ""

 .ShowInput = True

 .ShowError = True

End With

ContentLicense: CC BY-SA 4.0


问:
Instantiating types using AutoMapper with a DI container
Please see the code below:

```<code>public class Test : ITest
    {
        public ITest2 _iTest2;
        public int _id;
        public string _name;

        public Test(ITest2 test2)
        {
            _iTest2 = test2;
        }
    }

    public interface ITest
    {
    }

    public class Test2 : ITest2
    {
    }

    public interface ITest2
    {

    }

    public class Test3 : ITest3
    {
        public int _id;
        public string _name;
    }

    public interface ITest3
    {

    }
</code>```

I have the following in my Global.asax:

```<code>Mapper.Initialize(m =>
            {
 m.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
});
</code>```

I can map the types in my client app doing this:

```<code>cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
</code>```

How can I map the types using Castle Windsor instead of having to use the new keyword for Test and Test2?

I read another answer and someone suggested doing this:

```<code> public void Install(IWindsorContainer container, IConfigurationStore store)
    {

        container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn(typeof(IValueResolver<,,>)));
        // container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn<IValueResolver>());
        container.Register(Types.FromThisAssembly().BasedOn<Profile>().WithServiceBase());
        var profiles = container.ResolveAll<Profile>();

        // Add your list of profiles to the mapper configuration here
        Mapper.Initialize(m => {
            m.ConstructServicesUsing(container.Resolve);
            profiles.ToList().ForEach(p => m.AddProfile(p));
        });

        // I'm not sure about this as I haven't used AutoMapper for a while,
        // but I assume you want to resolve the static mapper instance
        container.Register(Component.For<IMapper>().Instance(Mapper.Instance));
    }
</code>```

Do I have to do this:

```<code>cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
</code>```

or should AutoMapper be able to map the types using this:

```<code>cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>()
</code>```

答:
In order to get AutoMapper to use Windsor to create the target type, you need to configure two things:

Tell AutoMapper to construct services using Windsor

Tell AutoMapper (per-mapping) to actually use the above configuration

```<code> var container = new WindsorContainer();

    Mapper.Initialize(m =>
    {
        m.ConstructServicesUsing(container.Resolve);

        m.CreateMap<Test3, ITest>().ConstructUsingServiceLocator(); // This is important!

    });

    container.Register(Component.For<ITest>().ImplementedBy<Test>());
    container.Register(Component.For<ITest2>().ImplementedBy<Test2>());
    container.Register(Component.For<ITest3>().ImplementedBy<Test3>());

    var test3 = new Test3();
    var test1 = Mapper.Instance.Map<Test3, ITest>(test3);
</code>```

Body:
Please see the code below:

public class Test : ITest
    {
        public ITest2 _iTest2;
        public int _id;
        public string _name;

        public Test(ITest2 test2)
        {
            _iTest2 = test2;
        }
    }

    public interface ITest
    {
    }

    public class Test2 : ITest2
    {
    }

    public interface ITest2
    {

    }

    public class Test3 : ITest3
    {
        public int _id;
        public string _name;
    }

    public interface ITest3
    {

    }

I have the following in my Global.asax:

Mapper.Initialize(m =>
            {
 m.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
});

I can map the types in my client app doing this:

cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));

How can I map the types using Castle Windsor instead of having to use the new keyword for Test and Test2?

I read another answer and someone suggested doing this:

 public void Install(IWindsorContainer container, IConfigurationStore store)
    {

        container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn(typeof(IValueResolver<,,>)));
        // container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn<IValueResolver>());
        container.Register(Types.FromThisAssembly().BasedOn<Profile>().WithServiceBase());
        var profiles = container.ResolveAll<Profile>();

        // Add your list of profiles to the mapper configuration here
        Mapper.Initialize(m => {
            m.ConstructServicesUsing(container.Resolve);
            profiles.ToList().ForEach(p => m.AddProfile(p));
        });

        // I'm not sure about this as I haven't used AutoMapper for a while,
        // but I assume you want to resolve the static mapper instance
        container.Register(Component.For<IMapper>().Instance(Mapper.Instance));
    }

Do I have to do this:

cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));

or should AutoMapper be able to map the types using this:

cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>()

Body:
In order to get AutoMapper to use Windsor to create the target type, you need to configure two things:

Tell AutoMapper to construct services using Windsor

Tell AutoMapper (per-mapping) to actually use the above configuration

 var container = new WindsorContainer();

    Mapper.Initialize(m =>
    {
        m.ConstructServicesUsing(container.Resolve);

        m.CreateMap<Test3, ITest>().ConstructUsingServiceLocator(); // This is important!

    });

    container.Register(Component.For<ITest>().ImplementedBy<Test>());
    container.Register(Component.For<ITest2>().ImplementedBy<Test2>());
    container.Register(Component.For<ITest3>().ImplementedBy<Test3>());

    var test3 = new Test3();
    var test1 = Mapper.Instance.Map<Test3, ITest>(test3);


问:
How to remove a select option using Angular
I am relatively new to angular2 / TS / ES6, I can not seem to find the answer to this anywhere.

I have a select with options that are dynamically rendered using ngFor, the options are in an array.
The select is meant for selecting options for a product. Once an option is selected, it gets pushed to another array that stores the products selected attributes. I would like the option removed from the DOM so it doesn't get in the users way, after it has been selected once.
I know I can disable it but I would really like to remove the option all-together.

Any help would be great.
I'm having trouble understanding how to manipulate the DOM with angular 2+

答:
Once you get the selected option try to remove it from original array. Which indeed re-render the drop-down menu. If directly modifying original array doesn't work then remove element and do something like this.</p>

```<code>OriginalArray = Object.assign([],OriginalArray)
</code>```

Body:
Once you get the selected option try to remove it from original array. Which indeed re-render the drop-down menu. If directly modifying original array doesn't work then remove element and do something like this.

OriginalArray = Object.assign([],OriginalArray)


问:
Ignore parent divs width
I have had issues with modify a navigation bar for mobile. I want the navigation bar to ignore its parent div inner-wrapper width of 80% and use a full width of 100%.

The most logical solution I can think of is to set header: relative, width: 100% and header li to absolute with a width of 100%. However, this doesn't seem to work.

I want each navigation to have a full width of the screen rather than a full width of its parent wrapper.

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}
/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}
/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description">text</span></h3>
  </div>
</div></code>```

答:
Using viewport units seems initially like a good idea, though in this case it is not necessary and will be of no use as the header uses overflow: hidden.

Note, if you start using 100vw it can cause unwanted scrollbar and/or make the element behave in an unwanted way when its parent/body has scrollbar

As the header-li relates to the header (closest ancestor having a position other than static), simply use 100% and transform: translate to position it.

```<code>.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  background: lime;
}
</code>```

Note, it below sample I colored it light gray so one see how it positions itself

Stack snippet

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}

.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  background: lightgray;
}

/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}

/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description"><span>text</span></h3>
  </div>
</div></code>```

If you want the header-li to expand beyond the header as well, you will need to both remove overflow: hidden, use 100vw and remove the padding the ul has as a default (or else you'll get a scroll)

.header {
  background-color: #FFB6C1;
  color: black;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}

.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100vw;
  background: lightgray;
  padding: 0;
}

/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}

/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description"><span>text</span></h3>
  </div>
</div></code>```

Title: Ignore parent divs width

Body:
I have had issues with modify a navigation bar for mobile. I want the navigation bar to ignore its parent div inner-wrapper width of 80% and use a full width of 100%.

The most logical solution I can think of is to set header: relative, width: 100% and header li to absolute with a width of 100%. However, this doesn't seem to work.

I want each navigation to have a full width of the screen rather than a full width of its parent wrapper.

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}
/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}
/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}

text

Menu

About me

Progress

Food

Contact

text

Body:
Using viewport units seems initially like a good idea, though in this case it is not necessary and will be of no use as the header uses overflow: hidden.

Note, if you start using 100vw it can cause unwanted scrollbar and/or make the element behave in an unwanted way when its parent/body has scrollbar

As the header-li relates to the header (closest ancestor having a position other than static), simply use 100% and transform: translate to position it.

.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  background: lime;
}

Note, it below sample I colored it light gray so one see how it positions itself

Stack snippet

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}

.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  background: lightgray;
}

/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}

/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}

<!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description"><span>text</span></h3>
  </div>
</div>

If you want the header-li to expand beyond the header as well, you will need to both remove overflow: hidden, use 100vw and remove the padding the ul has as a default (or else you'll get a scroll)

.header {
  background-color: #FFB6C1;
  color: black;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}

.header-li {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100vw;
  background: lightgray;
  padding: 0;
}

/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}

/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}

<!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description"><span>text</span></h3>
  </div>
</div>


问:
Show only unique results with collection_select
I have a series of reviews for a professor, I want users to be able to sort reviews based on the class taught.  I have a collection_select but I'm having trouble filtering out duplicates,  so for example if more than one user had a professor for "English" you will just see "English" twice in the list.

This is what I have:

<%= collection_select(:professor, :id, Review.where(professor_id: @professor.id), :id, :whatclass) %>

I've seen some solutions saying that I should add .uniq but that dosen't seem to do anything.

<%= collection_select(:professor, :id, Review.where(professor_id: @professor.id).uniq, :id, :whatclass) %> I'm pretty sure this is not working because it's referring to the Review.id rather than Review.whatclass

答:
Your list contains duplicates because it has an entry for every review, not for every class taught, which is not unique for each review. I am not even sure you need to use collection_select to render a simple list of unique class names.

In the controller, try:

```<code>@unique_classes = Review.
  where(professor_id: @professor.id).
  pluck(:whatclass).uniq
</code>```

Here, pluck returns an array of just the whatclass attributes of every review of the professor. Calling uniq on that will drop any duplicates in the array. If you have lots of reviews for each professor, you can get better performance by having the database filter the duplicates:

```<code>@unique_classes = Review.
  where(professor_id: @professor.id).
  pluck("DISTINCT whatclass")
</code>```

This will generate a SELECT DISTINCT query, so the array pluck returns will already be unique.

Finally, you can plug this array of whatclass values into a simple select_tag:

```<code>select_tag :class_name, options_for_select(@unique_classes)
</code>```

The code above is untested, so it might need some changes to work.

Body:
Your list contains duplicates because it has an entry for every review, not for every class taught, which is not unique for each review. I am not even sure you need to use collection_select to render a simple list of unique class names.

In the controller, try:

@unique_classes = Review.
  where(professor_id: @professor.id).
  pluck(:whatclass).uniq

Here, pluck returns an array of just the whatclass attributes of every review of the professor. Calling uniq on that will drop any duplicates in the array. If you have lots of reviews for each professor, you can get better performance by having the database filter the duplicates:

@unique_classes = Review.
  where(professor_id: @professor.id).
  pluck("DISTINCT whatclass")

This will generate a SELECT DISTINCT query, so the array pluck returns will already be unique.

Finally, you can plug this array of whatclass values into a simple select_tag:

select_tag :class_name, options_for_select(@unique_classes)

The code above is untested, so it might need some changes to work.


问:
Using Sphinx to generate Python document using :glob:
I am new to Sphinx.

The file /home/user/myproject/docs/source/index.rst is as following:

```<code>My project contents:

.. toctree::
   :glob:

   *
</code>```

I am getting the below message on running $ make html under /home/user/myproject/docs/:

```<code>checking consistency... /home/user/myproject/docs/source/design/index.rst:: WARNING: document isn't included in any toctree
</code>```

What have I done wrongly? I would like Sphinx to automatically generate the structure depending on the directory hierarchy.

答:
If you are willing to just dump all your source files in source without a folder hierarchy, this is possible. Alternatively you could write a routine and run it from the Makefile before the call to sphinx-build.

As Mike alluded to, :glob: will just pull files in alphabetically by filename. See the docs here.

You can use “globbing” in toctree directives, by giving the glob flag option. All entries are then matched against the list of available documents, and matches are inserted into the list alphabetically.

If you want to use :glob: and maintain ordering with all your files in source, you'll need to prefix your .rst files with numbers.

Example

```<code>source
├── index.html
├── 1_intro.rst
├── 2_install.rst
└── 3_more-than-you-want-to-know.rst
</code>```

Though, you will of course need to rename the files if you decide you want them ordered differently, rather than moving the order of an explicit list in index.rst.

Body:
I am new to Sphinx.

The file /home/user/myproject/docs/source/index.rst is as following:

My project contents:

.. toctree::
   :glob:

   *

I am getting the below message on running $ make html under /home/user/myproject/docs/:

checking consistency... /home/user/myproject/docs/source/design/index.rst:: WARNING: document isn't included in any toctree

What have I done wrongly? I would like Sphinx to automatically generate the structure depending on the directory hierarchy.

Body:
If you are willing to just dump all your source files in source without a folder hierarchy, this is possible. Alternatively you could write a routine and run it from the Makefile before the call to sphinx-build.

As Mike alluded to, :glob: will just pull files in alphabetically by filename. See the docs here.

You can use “globbing” in toctree directives, by giving the glob flag option. All entries are then matched against the list of available documents, and matches are inserted into the list alphabetically.

If you want to use :glob: and maintain ordering with all your files in source, you'll need to prefix your .rst files with numbers.

Example

source
├── index.html
├── 1_intro.rst
├── 2_install.rst
└── 3_more-than-you-want-to-know.rst

Though, you will of course need to rename the files if you decide you want them ordered differently, rather than moving the order of an explicit list in index.rst.


问:
HttpClient vs HttpWebRequest for better performance, security and less connections
I discovered that a single HttpClient could be shared by multiple requests. If shared, and  the requests are to the same destination, multiple requests could reuse the connections. WebRequest needs to recreate the connection for each request.

I also looked up some documentation on other ways to use HttpClient in examples.

The following article summarizes the high-speed NTLM-authenticated connection sharing: HttpWebRequest.UnsafeAuthenticatedConnectionSharing

Possible implementations that I tried out are shown below

A)

```<code>private WebRequestHandler GetWebRequestHandler()
{
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(ResourceUriCanBeAnyUri, "NTLM", CredentialCache.DefaultNetworkCredentials);
    WebRequestHandler handler = new WebRequestHandler
    {
        UnsafeAuthenticatedConnectionSharing = true,
        Credentials = credentialCache
    };

    return handler;
}

using (HttpClient client = new HttpClient(GetWebRequestHandler(), false))
{
}
</code>```

B)

```<code>using (HttpClient client = new HttpClient)
{
}
</code>```

C)

```<code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create("some uri string")
</code>```

I would appreciate any help in making me understand which approach I should  take so as to achieve max performance, minimizing connections and making sure security is not impacted.

答:
There is a problem in your implementation 'A'. The lifetime of the instance returned from GetWebRequestHandler() is shortlived (maybe just for the sake of the example?). If this was done on purpose, it negates the passing of false for the 2nd param of HttpClient constructor. The value of false tells the HttpClient to not dispose the underlying HttpMessageHandler (which helps with scaling since it does not close the port for the request). This is, of course, assuming that the lifetime of the HttpMessageHandler is long enough for you to take advantage of the benefit of not opening/closing ports (which is a big impact on the scalability of your server).  Thus, I have a recommendation below of option 'D'.

There is also an option 'D' that you do not list above - to make the Httpclient instance static and re-used across all api calls. This is much more efficient from a memory allocation and GC perspective - as well as the opening of ports on the client.  You don't have the overhead of allocating memory for and creating HttpClient instances (and all of its underlying objects) and thus avoid the cleanup via GC for them too.

Please refer to my answer provided about a similar question - What is the overhead of creating a new HttpClient per call in a WebAPI client?

Body:
I discovered that a single HttpClient could be shared by multiple requests. If shared, and  the requests are to the same destination, multiple requests could reuse the connections. WebRequest needs to recreate the connection for each request.

I also looked up some documentation on other ways to use HttpClient in examples.

The following article summarizes the high-speed NTLM-authenticated connection sharing: HttpWebRequest.UnsafeAuthenticatedConnectionSharing

Possible implementations that I tried out are shown below

A)

private WebRequestHandler GetWebRequestHandler()
{
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(ResourceUriCanBeAnyUri, "NTLM", CredentialCache.DefaultNetworkCredentials);
    WebRequestHandler handler = new WebRequestHandler
    {
        UnsafeAuthenticatedConnectionSharing = true,
        Credentials = credentialCache
    };

    return handler;
}

using (HttpClient client = new HttpClient(GetWebRequestHandler(), false))
{
}

B)

using (HttpClient client = new HttpClient)
{
}

C)

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("some uri string")

I would appreciate any help in making me understand which approach I should  take so as to achieve max performance, minimizing connections and making sure security is not impacted.


问:
OneNote page clientUrl uniqueness
I'm developing an add-in for OneNote and trying to store some data for each pages.

As page data from office.js doesn't have ID compatible with OneNote REST API, I used clientUrl to use REST API. ( Difference between notebook id by OfficeJS and OneNote API )

But I found multiple pages have same clientUrl.

Here is real example from me.

```<code>{
  id: "1-486e5b3666204a2d86c9394a83acd8b8!39-8b4a7756-1039-4ec5-b988-0734dbe02748",
  links: {
    oneNoteClientUrl: {
      href: "onenote:https://oneeducationorg-my.sharepoint.com/personal/dongseok_one-education_org/Documents/Class%20Notebooks/Biology/Rangan%20Srikhanta/Homework.one#Geo%20learn%201&section-id=8b4a7756-1039-4ec5-b988-0734dbe02748&page-id=200133b3-ec2f-4046-86eb-85979437c973&end"
    }
  }
}

{
  id: "1-2ca4377c872f4f99ab872de4876a1755!146-8b4a7756-1039-4ec5-b988-0734dbe02748",
  links: {
    oneNoteClientUrl: {
      href: "onenote:https://oneeducationorg-my.sharepoint.com/personal/dongseok_one-education_org/Documents/Class%20Notebooks/Biology/Rangan%20Srikhanta/Homework.one#Geo%20learn%201&section-id=8b4a7756-1039-4ec5-b988-0734dbe02748&page-id=200133b3-ec2f-4046-86eb-85979437c973&end"
    }
  }
}
</code>```

So my question is

Are these cases just something buggy or it can be happened as normally? ( I think I copied those pages by using 'copyToSection' method from add-in API - https://dev.office.com/reference/add-ins/onenote/page )

Can I keep use clientUrl as unique identifier for each page? If not, what can I use as an unique identifier from page data that retrieved from office.js?

答:
You can now use "GetRestApiId"

https://github.com/OfficeDev/office-js-docs/blob/master/reference/onenote/page.md#getRestApiId

Title: OneNote page clientUrl uniqueness

Body:
I'm developing an add-in for OneNote and trying to store some data for each pages.

As page data from office.js doesn't have ID compatible with OneNote REST API, I used clientUrl to use REST API. ( Difference between notebook id by OfficeJS and OneNote API )

But I found multiple pages have same clientUrl.

Here is real example from me.

{
  id: "1-486e5b3666204a2d86c9394a83acd8b8!39-8b4a7756-1039-4ec5-b988-0734dbe02748",
  links: {
    oneNoteClientUrl: {
      href: "onenote:https://oneeducationorg-my.sharepoint.com/personal/dongseok_one-education_org/Documents/Class%20Notebooks/Biology/Rangan%20Srikhanta/Homework.one#Geo%20learn%201&section-id=8b4a7756-1039-4ec5-b988-0734dbe02748&page-id=200133b3-ec2f-4046-86eb-85979437c973&end"
    }
  }
}

{
  id: "1-2ca4377c872f4f99ab872de4876a1755!146-8b4a7756-1039-4ec5-b988-0734dbe02748",
  links: {
    oneNoteClientUrl: {
      href: "onenote:https://oneeducationorg-my.sharepoint.com/personal/dongseok_one-education_org/Documents/Class%20Notebooks/Biology/Rangan%20Srikhanta/Homework.one#Geo%20learn%201&section-id=8b4a7756-1039-4ec5-b988-0734dbe02748&page-id=200133b3-ec2f-4046-86eb-85979437c973&end"
    }
  }
}

So my question is

Are these cases just something buggy or it can be happened as normally? ( I think I copied those pages by using 'copyToSection' method from add-in API - https://dev.office.com/reference/add-ins/onenote/page )

Can I keep use clientUrl as unique identifier for each page? If not, what can I use as an unique identifier from page data that retrieved from office.js?


问:
Cast object to non explicit implemented interface
It's somehow possible to cast an object to an interface which it doesnt inherit directly? In my sample code below, is there any way to convert an All instance to a Single one?</p>

```<code>public interface  IA
{
    void A();
}

public interface IB
{
    void B();
}

public interface IC : IA, IB
{
}

public class All : IA, IB
{
    public void A()
    {
        Console.Out.WriteLine("ALL A");
    }

    public void B()
    {
        Console.Out.WriteLine("ALL B");
    }
}

public class Single : IC
{
    public void A()
    {
        Console.Out.WriteLine("SINGLE A");
    }

    public void B()
    {
        Console.Out.WriteLine("SINGLE B");
    }
}

class Program
{
    static void Main()
    {
        All all = new All();
        Single single = (Single)(all as IC); // Always null
        single?.A();
    }
}
</code>```

答:
You will need to use the Adapter Pattern.

```<code>class AllIC : IC {
    private readonly All all;
    public AllIC(All all) {
        if( all == null ) throw new ArgumentNullException(nameof(all));
        this.all = all;
    }

    public void A() => this.all.A();
    public void B() => this.all.B();
}

static void Main()
{
    All all = new All();
    IC ic = new AllIC( all ); // Observe that `ic` is typed as interface `IC` instead of the concrete type `Single`.
    ic.A();
}
</code>```

Note that unlike interfaces you cannot coerce one concrete type to another (in this case, your casting to Single), you must change your local variable type from a concrete type (Single) to an interface (IC).

Body:
It's somehow possible to cast an object to an interface which it doesnt inherit directly? In my sample code below, is there any way to convert an All instance to a Single one?

public interface  IA
{
    void A();
}

public interface IB
{
    void B();
}

public interface IC : IA, IB
{
}

public class All : IA, IB
{
    public void A()
    {
        Console.Out.WriteLine("ALL A");
    }

    public void B()
    {
        Console.Out.WriteLine("ALL B");
    }
}

public class Single : IC
{
    public void A()
    {
        Console.Out.WriteLine("SINGLE A");
    }

    public void B()
    {
        Console.Out.WriteLine("SINGLE B");
    }
}

class Program
{
    static void Main()
    {
        All all = new All();
        Single single = (Single)(all as IC); // Always null
        single?.A();
    }
}

Body:
You will need to use the Adapter Pattern.

class AllIC : IC {
    private readonly All all;
    public AllIC(All all) {
        if( all == null ) throw new ArgumentNullException(nameof(all));
        this.all = all;
    }

    public void A() => this.all.A();
    public void B() => this.all.B();
}

static void Main()
{
    All all = new All();
    IC ic = new AllIC( all ); // Observe that `ic` is typed as interface `IC` instead of the concrete type `Single`.
    ic.A();
}

Note that unlike interfaces you cannot coerce one concrete type to another (in this case, your casting to Single), you must change your local variable type from a concrete type (Single) to an interface (IC).


问:
Javascript global variables and references to them and their parts
I'm writing little snippets to learn more about using Javascript with API's, and have stumbled onto another problem I can't figure out on my own. I have a global variable (object?) "coins", read in from the API, and its' data field "symbol". I can use "symbol" to reference the data held there, in part of my code, without any errors. Later in the code, I use it again, and I get an error about it being undefined, despite the fact that the values returned from using it, are both defined, and, what I expected. While we are at it, maybe someone can tell me why I assign values to global variables (declared outside of all of the functions), but the variables when called, are "undefined". To see it in action, visit www.mattox.space/XCR and open up dev tools.</p>

```<code>            /*

    FLOW:
    get ALL coins, store NAME and SYMBOL into an object.
    loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
    hit the API again, with the $NAME added to the URL.
    create a table row.
    insert data from second API hit, into table row
    SOMEWHERE in there, do the USD conversion from BTC.
    */

    //var name = getName();
    var bitcoinValue = 0;
    var coins = new Array;
    var form = ""; // Value pulled from the form
    var symbol = ""; // "id" on the table
    var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol

    var formSym = "";
    var formUSD = 0;
    var formBTC = 0;
    var form24h = 0;

    function run() {
      getFormData();
      allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
      testGlobal();
    }

    function testGlobal() {
      console.log("These are hopefully the values of the global variables");
      console.log(formSym + " testGlobal");
      console.log(formUSD + " testGlobal");
      console.log(formBTC + " testGlobal");
      console.log(form24h + " testGlobal");
    }

    function getFormData(){ //This function works GREAT!
      form = document.getElementById("symbol").value //THIS WORKS
      form = form.toUpperCase(); //THIS WORKS
    }

    function allTheCoins(URL) {
      var tickerRequest = new XMLHttpRequest();
      tickerRequest.open('GET', URL);
      tickerRequest.send();
      tickerRequest.onload = function() {
        if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
          var input = JSON.parse(tickerRequest.responseText);
          for(var i in input)
          coins.push(input[i]);
          testFunction(coins);
        }
        else {
          console.log("We connected to the server, but it returned an error.");
        }
        console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
        console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
      }
    }

    function testFunction(coins) {
      for (var i = 0; i < coins.length; i++) {

        if (coins[i].symbol == form) { // But right here, I get an error.
          formSym = coins[i].name;
          formUSD = coins[i].price_usd;
          formBTC = coins[i].price_btc;
          form24h = coins[i].percent_change_24h;
          console.log(formSym + " testFunction");
          console.log(formUSD + " testFunction");
          console.log(formBTC + " testFunction");
          console.log(form24h + " testFunction");
          //DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
        }
        else if (i > coins.length) {
          formSym = "Error";
          formUSD = 0;
          formBTC = 0;
          form24h = 0;
        }
      }
    }
    /*

    if (24h >= 0) {
    colorRED
    }
    else {
    colorGreen
    }

    */
</code>```

答:
here is a possible way of doing it that you can get inspired by. its based on a httpRequest promise that set the headers and method.</p>

```<code>    let allTheCoins = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || obj.method, obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};

allTheCoins({
    url: "https://api.coinmarketcap.com/v1/ticker/",
    method: "GET",
    headers: {"Accept-Encoding": "gzip"}
})
        .then(data => {
            ParseCoins(data);
        })
        .catch(error => {
            console.log("We connected to the server, but it returned an error.");
        });

function ParseCoins(data) {
    const coins = JSON.parse(data);
    const form = getFormVal();/*retrieve form val*/
    const id = getTableId(); /*retrieve table id*/
    const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
    const final_result = [];
    for (let i = 0, len = coins[0].length; i < len; i++) {
        const coin = coins[0][i];
        for (let ii in coin) {
            if (coin.hasOwnProperty(ii)) {
                if (coin[ii].symbol == form) {
                    let element = {
                        formSym: coin[ii].name,
                        formUSD: coin[ii].price_usd,
                        formBTC: coin[ii].price_btc,
                        form24h: coin[ii].percent_change_24h
                    };
                    final_result.push(element);
                }
            }
        }
    }
    coontinueElseWhere(final_result);
}
</code>```

Body:
I'm writing little snippets to learn more about using Javascript with API's, and have stumbled onto another problem I can't figure out on my own. I have a global variable (object?) "coins", read in from the API, and its' data field "symbol". I can use "symbol" to reference the data held there, in part of my code, without any errors. Later in the code, I use it again, and I get an error about it being undefined, despite the fact that the values returned from using it, are both defined, and, what I expected. While we are at it, maybe someone can tell me why I assign values to global variables (declared outside of all of the functions), but the variables when called, are "undefined". To see it in action, visit www.mattox.space/XCR and open up dev tools.

            /*

    FLOW:
    get ALL coins, store NAME and SYMBOL into an object.
    loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
    hit the API again, with the $NAME added to the URL.
    create a table row.
    insert data from second API hit, into table row
    SOMEWHERE in there, do the USD conversion from BTC.
    */

    //var name = getName();
    var bitcoinValue = 0;
    var coins = new Array;
    var form = ""; // Value pulled from the form
    var symbol = ""; // "id" on the table
    var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol

    var formSym = "";
    var formUSD = 0;
    var formBTC = 0;
    var form24h = 0;

    function run() {
      getFormData();
      allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
      testGlobal();
    }

    function testGlobal() {
      console.log("These are hopefully the values of the global variables");
      console.log(formSym + " testGlobal");
      console.log(formUSD + " testGlobal");
      console.log(formBTC + " testGlobal");
      console.log(form24h + " testGlobal");
    }

    function getFormData(){ //This function works GREAT!
      form = document.getElementById("symbol").value //THIS WORKS
      form = form.toUpperCase(); //THIS WORKS
    }

    function allTheCoins(URL) {
      var tickerRequest = new XMLHttpRequest();
      tickerRequest.open('GET', URL);
      tickerRequest.send();
      tickerRequest.onload = function() {
        if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
          var input = JSON.parse(tickerRequest.responseText);
          for(var i in input)
          coins.push(input[i]);
          testFunction(coins);
        }
        else {
          console.log("We connected to the server, but it returned an error.");
        }
        console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
        console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
      }
    }

    function testFunction(coins) {
      for (var i = 0; i < coins.length; i++) {

        if (coins[i].symbol == form) { // But right here, I get an error.
          formSym = coins[i].name;
          formUSD = coins[i].price_usd;
          formBTC = coins[i].price_btc;
          form24h = coins[i].percent_change_24h;
          console.log(formSym + " testFunction");
          console.log(formUSD + " testFunction");
          console.log(formBTC + " testFunction");
          console.log(form24h + " testFunction");
          //DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
        }
        else if (i > coins.length) {
          formSym = "Error";
          formUSD = 0;
          formBTC = 0;
          form24h = 0;
        }
      }
    }
    /*

    if (24h >= 0) {
    colorRED
    }
    else {
    colorGreen
    }

    */

Body:
here is a possible way of doing it that you can get inspired by. its based on a httpRequest promise that set the headers and method.

    let allTheCoins = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || obj.method, obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};

allTheCoins({
    url: "https://api.coinmarketcap.com/v1/ticker/",
    method: "GET",
    headers: {"Accept-Encoding": "gzip"}
})
        .then(data => {
            ParseCoins(data);
        })
        .catch(error => {
            console.log("We connected to the server, but it returned an error.");
        });

function ParseCoins(data) {
    const coins = JSON.parse(data);
    const form = getFormVal();/*retrieve form val*/
    const id = getTableId(); /*retrieve table id*/
    const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
    const final_result = [];
    for (let i = 0, len = coins[0].length; i < len; i++) {
        const coin = coins[0][i];
        for (let ii in coin) {
            if (coin.hasOwnProperty(ii)) {
                if (coin[ii].symbol == form) {
                    let element = {
                        formSym: coin[ii].name,
                        formUSD: coin[ii].price_usd,
                        formBTC: coin[ii].price_btc,
                        form24h: coin[ii].percent_change_24h
                    };
                    final_result.push(element);
                }
            }
        }
    }
    coontinueElseWhere(final_result);
}


问:
Modifying content of a text file in C
I understand that in C, if I have an existing text file "test.txt", calling fopen("test.txt","w") will overwrite the existing content of "test.txt".

I am trying to find an efficient way about my problem: Suppose that I have 10 rows in test.txt with each row containing a number. test.txt can refer to the values of the inputs to a PDE solver that I have. I want to do a sensitivity analysis on the last 3 parameters, i.e. keeping the first 7 numbers in test.txt fixed, I want to try different values for the last 3 rows.  Hence, I will be writing to test.txt in a for loop but I only intend to change the values of the last 3 rows at every iteration. The append of fopen does not work for me. Is there a more efficient way to go about this than storing the first seven values in an array and having to rewrite these values in the for loop through fopen?

Suggestions appreciated.

答:
Hence, I will be writing to test.txt in a for loop but I only intend
  to change the values of the last 3 rows at every iteration. The append
  of fopen does not work for me. Is there a more efficient way to go
  about this than storing the first seven values in an array and having
  to rewrite these values in the for loop through fopen?

It seems like you're going to need to read in and store the first seven values anyway.  You can, indeed, avoid rewriting them, however.  First, open the file in read / write mode without truncation:

```<code>FILE *input = fopen("test.txt", "r+");
</code>```

Read / write mode differs from append mode ("a" or "a+") in that in the former case, the file is initially positioned at the beginning and writes always go to the current file position, whereas in the latter case, the file is initially positioned at the end, and writes always go to the end.

Having opened the file in an appropriate mode, read it line by line, e.g. with fgets().  After the seventh line, use ftell() to record the current file position for later reference.  To overwrite the last lines, use fseek() to return to the recorded position, and just write the new values.  This may leave junk at the end of the file, after the last line; if that will be a problem then you can overwrite the tail (e.g. with space characters).  POSIX also has ftruncate() which you could use to clip any tail, but that's not part of standard C.

Title: Modifying content of a text file in C

Body:
Hence, I will be writing to test.txt in a for loop but I only intend
  to change the values of the last 3 rows at every iteration. The append
  of fopen does not work for me. Is there a more efficient way to go
  about this than storing the first seven values in an array and having
  to rewrite these values in the for loop through fopen?

It seems like you're going to need to read in and store the first seven values anyway.  You can, indeed, avoid rewriting them, however.  First, open the file in read / write mode without truncation:

FILE *input = fopen("test.txt", "r+");

Read / write mode differs from append mode ("a" or "a+") in that in the former case, the file is initially positioned at the beginning and writes always go to the current file position, whereas in the latter case, the file is initially positioned at the end, and writes always go to the end.

Having opened the file in an appropriate mode, read it line by line, e.g. with fgets().  After the seventh line, use ftell() to record the current file position for later reference.  To overwrite the last lines, use fseek() to return to the recorded position, and just write the new values.  This may leave junk at the end of the file, after the last line; if that will be a problem then you can overwrite the tail (e.g. with space characters).  POSIX also has ftruncate() which you could use to clip any tail, but that's not part of standard C.


答:
[Does this] violate the ISO c++14 standard?

Yes, you can not declare functions taking parameters using auto in C++14 (or C++17 for that matter). This code is ill-formed.

Will future versions of the standard allow code to be written like that?

The current Concepts TS does allow for this, it's usually referred to as terse function template syntax. In Concepts, the meaning is equivalent to:

```<code>template <class T, class U>
auto add(T a, U b) { return a + b; }
</code>```

That part of the Concepts proposal also allows concept names to be used, not just auto. It is an open question as to whether this will be part of a future C++ standard.

Update: The code will be valid in C++20, and have meaning equivalent to the function template I showed above (NB: a and b are deduced independently).

Title: Is use of `auto` for a function argument against the C++ standard?

Body:
Does code like this:

auto add(auto a, auto b) { return a + b; }

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

Body:
[Does this] violate the ISO c++14 standard?

Yes, you can not declare functions taking parameters using auto in C++14 (or C++17 for that matter). This code is ill-formed.

Will future versions of the standard allow code to be written like that?

The current Concepts TS does allow for this, it's usually referred to as terse function template syntax. In Concepts, the meaning is equivalent to:

template <class T, class U>
auto add(T a, U b) { return a + b; }

That part of the Concepts proposal also allows concept names to be used, not just auto. It is an open question as to whether this will be part of a future C++ standard.

Update: The code will be valid in C++20, and have meaning equivalent to the function template I showed above (NB: a and b are deduced independently).


问:
Dynamic column creation in react js
I have the following data in my code:

```<code>this.state.data = [
                   {"col0":"Service Port","col1":80,"col2":8080}
                   {"col0":"Service Name","col1":"--","col2":"--"}
                  ]
</code>```

render function:

```<code>............
............
<div className="row">
                    <div className="col-lg-12">
                        <CollapsiblePanel name="Services"
                                          bsStyle="info"
                                          open>
                            <BootstrapTable data={this.state.data}
                                            striped
                                            hover>
                                {/*{
                                    for(var i = 0; i < this.state.data.length; i++) {
                                        var col = 0;
                                        for(var j = 0; j < this.state.data[i].length; j)
                                        <TableHeaderColumn
                                            className="tableHeader"
                                            dataField={this.state.col++}
                                    }
                                }*/}
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col0"
                                    isKey
                                    width="40%"></TableHeaderColumn>
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col1"
                                    width="40%"></TableHeaderColumn>
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col2"
                                    width="40%"></TableHeaderColumn>
                            </BootstrapTable>
                        </CollapsiblePanel>
                    </div>
                </div>
</code>```

What i want to do is to dynamically create the TableHeaderColumns because there could be more or less col keys in my data array, such as col3, col4, etc. I tried to integrate a for-loop inside render but it didn't do the work (im not sure how to do that in react).

Could anyone suggest how to do that dynamically? Thanks!

答:
First, you would have to store your dynamic columns somewhere, I'll assume these columns are coming from a parent component, so I will set them as default props.

```<code>    class MyOwnComponent extends from React.Component{
        static defaultProps = {
            cols = [
                {
                    className: "tableHeader",
                    dataField: "col0",
                    width: "40%"
                },
                {
                    className: "tableHeader",
                    dataField: "col1",
                    width: "40%"
                },
                {
                    className: "tableHeader",
                    dataField: "col2",
                    width: "40%"
                }
            ]
        }

        render(){
            return(
                    <div className="row">
                        <div className="col-lg-12">
                            <CollapsiblePanel name="Services"
                                            bsStyle="info"
                                            open>
                                <BootstrapTable data={this.state.data}
                                                striped
                                                hover>
                                    {/*{
                                        for(var i = 0; i < this.state.data.length; i++) {
                                            var col = 0;
                                            for(var j = 0; j < this.state.data[i].length; j)
                                            <TableHeaderColumn
                                                className="tableHeader"
                                                dataField={this.state.col++}
                                        }
                                    }*/}
                                    {
                                        this.props.cols.map(function(item){
                                        return (
                                            <TableHeaderColumn className={item.className} dataField={item.dataField} width={item.width}/>
                                        )}
                                    )}
                                </BootstrapTable>
                            </CollapsiblePanel>
                        </div>
                    </div>
            )
        }
    }
</code>```

Regarding the key, React encourages you to have a unique ID for each instance of a component, sort of speak. If you don't have it you could work around it with an index when iterating using map function. Like this:

```<code>    this.props.cols.map(function(item, index){
    return (
        <TableHeaderColumn key={index} className={item.className} dataField={item.dataField} width={item.width}/>
    )}
</code>```

Please check documentation for more reference:

React Lits & Keys

Title: Dynamic column creation in react js

Body:
I have the following data in my code:

this.state.data = [
                   {"col0":"Service Port","col1":80,"col2":8080}
                   {"col0":"Service Name","col1":"--","col2":"--"}
                  ]

render function:

............
............

                        <CollapsiblePanel name="Services"
                                          bsStyle="info"
                                          open>
                            <BootstrapTable data={this.state.data}
                                            striped
                                            hover>
                                {/*{
                                    for(var i = 0; i < this.state.data.length; i++) {
                                        var col = 0;
                                        for(var j = 0; j < this.state.data[i].length; j)
                                        <TableHeaderColumn
                                            className="tableHeader"
                                            dataField={this.state.col++}
                                    }
                                }*/}
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col0"
                                    isKey
                                    width="40%"></TableHeaderColumn>
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col1"
                                    width="40%"></TableHeaderColumn>
                                <TableHeaderColumn
                                    className="tableHeader"
                                    dataField="col2"
                                    width="40%"></TableHeaderColumn>
                            </BootstrapTable>
                        </CollapsiblePanel>

What i want to do is to dynamically create the TableHeaderColumns because there could be more or less col keys in my data array, such as col3, col4, etc. I tried to integrate a for-loop inside render but it didn't do the work (im not sure how to do that in react).

Could anyone suggest how to do that dynamically? Thanks!

Body:
First, you would have to store your dynamic columns somewhere, I'll assume these columns are coming from a parent component, so I will set them as default props.

    class MyOwnComponent extends from React.Component{
        static defaultProps = {
            cols = [
                {
                    className: "tableHeader",
                    dataField: "col0",
                    width: "40%"
                },
                {
                    className: "tableHeader",
                    dataField: "col1",
                    width: "40%"
                },
                {
                    className: "tableHeader",
                    dataField: "col2",
                    width: "40%"
                }
            ]
        }

        render(){
            return(
                    <div className="row">
                        <div className="col-lg-12">
                            <CollapsiblePanel name="Services"
                                            bsStyle="info"
                                            open>
                                <BootstrapTable data={this.state.data}
                                                striped
                                                hover>
                                    {/*{
                                        for(var i = 0; i < this.state.data.length; i++) {
                                            var col = 0;
                                            for(var j = 0; j < this.state.data[i].length; j)
                                            <TableHeaderColumn
                                                className="tableHeader"
                                                dataField={this.state.col++}
                                        }
                                    }*/}
                                    {
                                        this.props.cols.map(function(item){
                                        return (
                                            <TableHeaderColumn className={item.className} dataField={item.dataField} width={item.width}/>
                                        )}
                                    )}
                                </BootstrapTable>
                            </CollapsiblePanel>
                        </div>
                    </div>
            )
        }
    }

Regarding the key, React encourages you to have a unique ID for each instance of a component, sort of speak. If you don't have it you could work around it with an index when iterating using map function. Like this:

    this.props.cols.map(function(item, index){
    return (
        <TableHeaderColumn key={index} className={item.className} dataField={item.dataField} width={item.width}/>
    )}

Please check documentation for more reference:

React Lits & Keys


问:
Replace xml tag using sed
We have a jenkins server with too many jobs and most of the jobs have Build trigger as Poll SCM. I want to remove that trigger for all the jobs. Looking for a easy way to do that. I see that whenever the build trigger property is set the config.xml has this-

```<code><triggers>
    <hudson.triggers.SCMTrigger>
      <spec>
        # poll infrequently and rely on Stash webhooks to trigger builds
        @daily
      </spec>
      <ignorePostCommitHooks>false</ignorePostCommitHooks>
    </hudson.triggers.SCMTrigger>
</triggers>
</code>```

Whenever the Poll SCM flag is set to false this same element in config.xml is as follows-

```<code> <triggers/>
</code>```

I am looking for an easy way using sed to replace the above triggers tag with this but am not able to get it using sed.

I tried this from the jobs folder and it does not work-

```<code>sudo find . -name "config.xml" -print0 | sudo xargs -0 sed -i '' -e 's|<triggers>.*<\/triggers|<triggers\/>|g'
</code>```

So basically I want to replace the entire contents of triggers element above along with start and end triggers tag with only this

```<code><triggers/>
</code>```

答:
sed is a stream editor and reads the file line by line. Your pattern spans multiple lines in the file, which is why it never matches.

You should either make sed read the whole file into the pattern space before attempting the substitution...

```<code>sed ':a;N;$!ba; s|<triggers>.*<\/triggers>|<triggers\/>|g' example.xml
</code>```

... or use another tool (preferably suited for XML files, like xmlstarlet):

```<code>xmlstarlet ed -O -u /triggers -v '' example.xml
</code>```

Title: Replace xml tag using sed

Body:
We have a jenkins server with too many jobs and most of the jobs have Build trigger as Poll SCM. I want to remove that trigger for all the jobs. Looking for a easy way to do that. I see that whenever the build trigger property is set the config.xml has this-

<triggers>
    <hudson.triggers.SCMTrigger>
      <spec>
        # poll infrequently and rely on Stash webhooks to trigger builds
        @daily
      </spec>
      <ignorePostCommitHooks>false</ignorePostCommitHooks>
    </hudson.triggers.SCMTrigger>
</triggers>

Whenever the Poll SCM flag is set to false this same element in config.xml is as follows-

 <triggers/>

I am looking for an easy way using sed to replace the above triggers tag with this but am not able to get it using sed.

I tried this from the jobs folder and it does not work-

sudo find . -name "config.xml" -print0 | sudo xargs -0 sed -i '' -e 's|<triggers>.*<\/triggers|<triggers\/>|g'

So basically I want to replace the entire contents of triggers element above along with start and end triggers tag with only this

<triggers/>

Body:
sed is a stream editor and reads the file line by line. Your pattern spans multiple lines in the file, which is why it never matches.

You should either make sed read the whole file into the pattern space before attempting the substitution...

sed ':a;N;$!ba; s|<triggers>.*<\/triggers>|<triggers\/>|g' example.xml

... or use another tool (preferably suited for XML files, like xmlstarlet):

xmlstarlet ed -O -u /triggers -v '' example.xml


问:
Change parent (div) height to the size of its child (p) after window resize
```<code>$(window).on("resize", function () {

    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight })
});
</code>```

I am trying to resize parent div to match the height of its child after windows resize. The problem I have is with this code that I get the height before the resize. How can I get the resulting height? Thanks!

答:
The code is executed when the resize event occurs...

And you want it to be executed after the event.

So what about a setTimeout() ?

I suppose that 100 milliseconds after the event is enought.

```<code>$(window).on("resize", function () {

  setTimeout(function(){
    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight });
  },100);
});
</code>```

Body:
$(window).on("resize", function () {

    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight })
});

I am trying to resize parent div to match the height of its child after windows resize. The problem I have is with this code that I get the height before the resize. How can I get the resulting height? Thanks!

Body:
The code is executed when the resize event occurs...

And you want it to be executed after the event.

So what about a setTimeout() ?

I suppose that 100 milliseconds after the event is enought.

$(window).on("resize", function () {

  setTimeout(function(){
    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight });
  },100);
});


问:
Expensive renderInContext memory usage on main thread
I am using the follow code that is executed on the main thread to take a screenshot of an off screen (not a subview of self.view) view that then is displayed in an UIImageView. Everything works fine in terms of functionality, however because this code is being run on an extension, there are much stricter memory bounds (I've read ~30 MB is the cap?),

```<code>UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.screenshotView.frame.size.width, self.screenshotView.frame.size.height-2), YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.screenshotView.layer renderInContext:context];
_generatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.previewImageView.image = _generatedImage;
</code>```

The method this code resides in gets called using performSelectorOnMainThread whenever a UIButton is pressed. A UIAlertController is also presented to handle the freezing of the UI, but if the button is pressed continuously (after dismissal of the UIAlertController), the first few times the memory usage will stay around the baseline (~15 MB), but then spike to ~30 MB and stay there until the method is called again a few seconds later and then when it is done rendering, it falls back to ~15 MB.

I'm unsure what is causing this behavior, why the memory usage doesn't stick around ~15 MB all the time, and I'm unsure as to what is the reason it spikes like that when the method is called continuously. It sounds like more that one thing is happening at once sometimes? How can I make sure this doesn't happen and only dismiss the UIAlertController when it is safe to render again without spiking memory usage.

答:
The memory spike is not due to the renderInContext: call despite everything including instruments pointing to it, it is however due to the subviews of the captured UIView. In my case it was a faulty constraint that caused a UITextView to set its height to 2000.

To whomever has a problem like this and cannot figure it out, move on from renderInContext: and look at your subviews to make sure they are proper.

Body:
I am using the follow code that is executed on the main thread to take a screenshot of an off screen (not a subview of self.view) view that then is displayed in an UIImageView. Everything works fine in terms of functionality, however because this code is being run on an extension, there are much stricter memory bounds (I've read ~30 MB is the cap?),

UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.screenshotView.frame.size.width, self.screenshotView.frame.size.height-2), YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.screenshotView.layer renderInContext:context];
_generatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.previewImageView.image = _generatedImage;

The method this code resides in gets called using performSelectorOnMainThread whenever a UIButton is pressed. A UIAlertController is also presented to handle the freezing of the UI, but if the button is pressed continuously (after dismissal of the UIAlertController), the first few times the memory usage will stay around the baseline (~15 MB), but then spike to ~30 MB and stay there until the method is called again a few seconds later and then when it is done rendering, it falls back to ~15 MB.

I'm unsure what is causing this behavior, why the memory usage doesn't stick around ~15 MB all the time, and I'm unsure as to what is the reason it spikes like that when the method is called continuously. It sounds like more that one thing is happening at once sometimes? How can I make sure this doesn't happen and only dismiss the UIAlertController when it is safe to render again without spiking memory usage.


问:
"Attach to Process" instead of "Local Windows Debugger"
I updated my version of Visual Studio Express 2012 and now I get "Attach to Process" instead of the "Local Windows Debugger" option which I had previously. So I can no longer run/debug my project. How can I resolve this?</p>

答: Go to %appdata% and delete the visual studios folder</p>