问:
React grid elements, show details about specified element after clicking it
i have created gird of elements (something like gallery) AllElements Component where i am mapping SingleElement Component

```<code>renderAllElements = () => (
            this.state.myData.map(se => (
                <SingleElement key={se.id} name={se.name} tagline={se.tagline} image_url={se.image_url}/>
        )
    )
)
</code>```

And my SingleElement renders this, as below

```<code>render() {
    return (
        <div className="singleElement">
            <img src={this.props.image_url} alt={this.props.name} />
            <h4>{this.props.name}</h4>
            <h5>{this.props.tagline}</h5>
        </div>
    )
}
</code>```

To the point, what I want achieve? ---> After clicking on one of the elements (specyfied SingleElement) the details is shown in front of the screen (hovering over whole grid). Let's name this Component SingleElementDetails. What is the best way to achieve it? Should SingleElementDetails Component be sibling of SingleElement Component or it's child ?

答:
You could use the AllElements state and an method to handle when/what to show.
Something like this:

```<code>class AllElements extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myData: {},
      viewingElement: null,
    };
    this.see = this.see.bind(this);
    this.close = this.close.bind(this);
  }

  see(id) {
    this.setState({
      viewingElement: id,
    });
  }

  close() {
    this.setState({
      viewingElement: null,
    });
  }

  render() {
    const { myData, viewingElement } = this.state;
    return (
      <div>
        {myData.map(se => (
          <SingleElement
            key={se.id}
            name={se.name}
            tagline={se.tagline}
            image_url={se.image_url}
            see={this.see}
            close={this.close}
          />
        ))}
        {viewingElement && (
          <SingleElementDetails element={myData[this.state]} />
        )}
      </div>
    );
  }
}
</code>```

Then you need to fire this.props.see on the onClick event from SingleElement and use CSS to visually position SingleElementDetails over the rest of the contest.

Body:
i have created gird of elements (something like gallery) AllElements Component where i am mapping SingleElement Component

renderAllElements = () => (
            this.state.myData.map(se => (
                <SingleElement key={se.id} name={se.name} tagline={se.tagline} image_url={se.image_url}/>
        )
    )
)

And my SingleElement renders this, as below

render() {
    return (

{this.props.name}

{this.props.tagline}

    )
}

To the point, what I want achieve? ---> After clicking on one of the elements (specyfied SingleElement) the details is shown in front of the screen (hovering over whole grid). Let's name this Component SingleElementDetails. What is the best way to achieve it? Should SingleElementDetails Component be sibling of SingleElement Component or it's child ?

Body:
You could use the AllElements state and an method to handle when/what to show.
Something like this:

class AllElements extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myData: {},
      viewingElement: null,
    };
    this.see = this.see.bind(this);
    this.close = this.close.bind(this);
  }

  see(id) {
    this.setState({
      viewingElement: id,
    });
  }

  close() {
    this.setState({
      viewingElement: null,
    });
  }

  render() {
    const { myData, viewingElement } = this.state;
    return (
      <div>
        {myData.map(se => (
          <SingleElement
            key={se.id}
            name={se.name}
            tagline={se.tagline}
            image_url={se.image_url}
            see={this.see}
            close={this.close}
          />
        ))}
        {viewingElement && (
          <SingleElementDetails element={myData[this.state]} />
        )}
      </div>
    );
  }
}

Then you need to fire this.props.see on the onClick event from SingleElement and use CSS to visually position SingleElementDetails over the rest of the contest.


来源: stackexchange

问:
Do HttpClient and HttpClientHandler have to be disposed between requests?
System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The using statement documentation says:

As a rule, when you use an IDisposable object, you should declare and
  instantiate it in a using statement.

This answer uses this pattern:

```<code>var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}
</code>```

But the most visible examples from Microsoft don't call Dispose() either explicitly or implicitly. For instance:

The original blog article announcing the relase of HttpClient.

The actual MSDN documentation for HttpClient.

BingTranslateSample

GoogleMapsSample

WorldBankSample

In the announcement's comments, someone asked the Microsoft employee:

After checking your samples, I saw that you didn't perform the dispose
  action on HttpClient instance. I have used all instances of HttpClient
  with using statement on my app and I thought that it is the right way
  since HttpClient  implements the IDisposable interface. Am I on the
  right path?

His answer was:

In general that is correct although you have to be careful with
  "using" and async as they dont' really mix in .Net 4, In .Net 4.5 you
  can use "await" inside a "using" statement.

Btw, you can reuse the same HttpClient as many times are [as] you like so
  typically you won't create/dispose them all the time.

The second paragraph is superfluous to this question, which is not concerned about how many times you can use an HttpClient instance, but about if it is necessary to dispose it after you no longer need it.

(Update: in fact that second paragraph is the key to the answer, as provided below by @DPeden.)

So my questions are:

Is it necessary, given the current implementation (.NET Framework 4.5), to call Dispose() on HttpClient and HttpClientHandler instances? Clarification: by "necessary" I mean if there are any negative consequences for not disposing, such as resource leakage or data corruption risks.

If it's not necessary, would it be a "good practice" anyway, since they implement IDisposable?

If it's necessary (or recommended), is this code mentioned above implementing it safely (for .NET Framework 4.5)?

If these classes don't require calling Dispose(), why were they implemented as IDisposable?

If they require, or if it's a recommended practice, are the Microsoft examples misleading or unsafe?

答:
If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

```<code>// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}
</code>```

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

HttpClient, as an interface, can't call Dispose().

Dispose() will be called in a delayed fashion by the Garbage Collector.
Or when the program cleans up the object through its destructor.

Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.

It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.

HttpClientHandle allows for Mocking in tests

ContentLicense: CC BY-SA 4.0

Body:
System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The using statement documentation says:

As a rule, when you use an IDisposable object, you should declare and
  instantiate it in a using statement.

This answer uses this pattern:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}

But the most visible examples from Microsoft don't call Dispose() either explicitly or implicitly. For instance:

The original blog article announcing the relase of HttpClient.

The actual MSDN documentation for HttpClient.

BingTranslateSample

GoogleMapsSample

WorldBankSample

In the announcement's comments, someone asked the Microsoft employee:

After checking your samples, I saw that you didn't perform the dispose
  action on HttpClient instance. I have used all instances of HttpClient
  with using statement on my app and I thought that it is the right way
  since HttpClient  implements the IDisposable interface. Am I on the
  right path?

His answer was:

In general that is correct although you have to be careful with
  "using" and async as they dont' really mix in .Net 4, In .Net 4.5 you
  can use "await" inside a "using" statement.

Btw, you can reuse the same HttpClient as many times are [as] you like so
  typically you won't create/dispose them all the time.

The second paragraph is superfluous to this question, which is not concerned about how many times you can use an HttpClient instance, but about if it is necessary to dispose it after you no longer need it.

(Update: in fact that second paragraph is the key to the answer, as provided below by @DPeden.)

So my questions are:

Is it necessary, given the current implementation (.NET Framework 4.5), to call Dispose() on HttpClient and HttpClientHandler instances? Clarification: by "necessary" I mean if there are any negative consequences for not disposing, such as resource leakage or data corruption risks.

If it's not necessary, would it be a "good practice" anyway, since they implement IDisposable?

If it's necessary (or recommended), is this code mentioned above implementing it safely (for .NET Framework 4.5)?

If these classes don't require calling Dispose(), why were they implemented as IDisposable?

If they require, or if it's a recommended practice, are the Microsoft examples misleading or unsafe?

Body:
If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

HttpClient, as an interface, can't call Dispose().

Dispose() will be called in a delayed fashion by the Garbage Collector.
Or when the program cleans up the object through its destructor.

Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.

It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.

HttpClientHandle allows for Mocking in tests

ContentLicense: CC BY-SA 3.0


问:
Symfony can't set locale to undefined
i'm trying to work with locale on a Symfony 2.7 project.
I want to set the locale to the $request->getPreferredLanguage() if the user is not authenticated and to set it to $user->getLocale() if the user is authenticated and has set his prefered locale.

I read different posts like this one: https://gist.github.com/Dattaya/1670163/450a8054d84b30c16174a75eb60f139e2602cdea
but I have a problem in the setLocaleForUnauthenticatedUser() because i can't set the locale to undefined.

Here is my config.yml file:

```<code>parameters:
locale: "undefined"
session:
    storage:
        options:
            name: app_sess
framework:
    translator:      { fallback: "undefined" }
    default_locale:  "%locale%"
    secret:          "%secret%"
</code>```

I defined the services:

```<code>acme.locale.interactive_login_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    calls:
        - [ setSession, [@session] ]
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }

acme.locale.kernel_request_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: setLocaleForUnauthenticatedUser, priority: 17 }
</code>```

Here is the method:

```<code>public function setLocaleForUnauthenticatedUser(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();
    file_put_contents('test.txt', $request->getLocale(), FILE_APPEND);
    if ($request->getLocale() === 'undefined' ) {
        $request->setLocale($request->getPreferredLanguage());
    }
}
</code>```

In this code $request->getLocale() is not undefined, it's en.
I don't understand why. Can anybody help me please ?

答:
Finally i found a solution:
config.yml file

```<code>parameters:
    locale: "undefined"

framework:
    translator:      { fallback: "en" }
    default_locale:  "%locale%"
</code>```

services.yml file

```<code>acme.locale.interactive_login_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    calls:
        - [ setSession, [@session] ]
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }

acme.locale.kernel_request_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: setLocaleForUnauthenticatedUser, priority: 10 }
</code>```

LocaleListener file

```<code>class LocaleListener {

public function setSession(Session $session)
{
    $this->session = $session;
}

public function setLocaleForUnauthenticatedUser(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();
    $sessionLocale = $request->getSession()->get('_locale');
    if ($sessionLocale == '') {
        $request->setLocale(substr($request->getPreferredLanguage(), 0, 2));
    } else {
        $request->setLocale(substr($sessionLocale, 0, 2));
    }
}

public
function setLocaleForAuthenticatedUser(InteractiveLoginEvent $event)
{
    $user = $event->getAuthenticationToken()->getUser();
    $preferences = $user->getPreferences();

    if ($preferences !== null && gettype($preferences) === 'array' && isset($preferences['language'])) {
        $event->getRequest()->setLocale(substr($preferences['language'], 0, 2));
        $this->session->set('_locale', substr($preferences['language'], 0, 2));
    }
}
</code>```

}

The aim of this solution is to check if $request->getSession()->get('_locale'); is empty. This is the case when user is still not logged in. When the users log in, the setLocaleForAuthenticatedUser method is called and we set the session locale to the user preferred locale.
Note that substring are used to prevent problems with accurate locales such as fr_FR
It could be better, but this is a working solution

Title: Symfony can't set locale to undefined

Body:
i'm trying to work with locale on a Symfony 2.7 project.
I want to set the locale to the $request->getPreferredLanguage() if the user is not authenticated and to set it to $user->getLocale() if the user is authenticated and has set his prefered locale.

I read different posts like this one: https://gist.github.com/Dattaya/1670163/450a8054d84b30c16174a75eb60f139e2602cdea
but I have a problem in the setLocaleForUnauthenticatedUser() because i can't set the locale to undefined.

Here is my config.yml file:

parameters:
locale: "undefined"
session:
    storage:
        options:
            name: app_sess
framework:
    translator:      { fallback: "undefined" }
    default_locale:  "%locale%"
    secret:          "%secret%"

I defined the services:

acme.locale.interactive_login_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    calls:
        - [ setSession, [@session] ]
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }

acme.locale.kernel_request_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: setLocaleForUnauthenticatedUser, priority: 17 }

Here is the method:

public function setLocaleForUnauthenticatedUser(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();
    file_put_contents('test.txt', $request->getLocale(), FILE_APPEND);
    if ($request->getLocale() === 'undefined' ) {
        $request->setLocale($request->getPreferredLanguage());
    }
}

In this code $request->getLocale() is not undefined, it's en.
I don't understand why. Can anybody help me please ?

Body:
Finally i found a solution:
config.yml file

parameters:
    locale: "undefined"

framework:
    translator:      { fallback: "en" }
    default_locale:  "%locale%"

services.yml file

acme.locale.interactive_login_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    calls:
        - [ setSession, [@session] ]
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }

acme.locale.kernel_request_listener:
    class: acme\GeneralBundle\EventListener\LocaleListener
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: setLocaleForUnauthenticatedUser, priority: 10 }

LocaleListener file

class LocaleListener {

public function setSession(Session $session)
{
    $this->session = $session;
}

public function setLocaleForUnauthenticatedUser(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();
    $sessionLocale = $request->getSession()->get('_locale');
    if ($sessionLocale == '') {
        $request->setLocale(substr($request->getPreferredLanguage(), 0, 2));
    } else {
        $request->setLocale(substr($sessionLocale, 0, 2));
    }
}

public
function setLocaleForAuthenticatedUser(InteractiveLoginEvent $event)
{
    $user = $event->getAuthenticationToken()->getUser();
    $preferences = $user->getPreferences();

    if ($preferences !== null && gettype($preferences) === 'array' && isset($preferences['language'])) {
        $event->getRequest()->setLocale(substr($preferences['language'], 0, 2));
        $this->session->set('_locale', substr($preferences['language'], 0, 2));
    }
}

}

The aim of this solution is to check if $request->getSession()->get('_locale'); is empty. This is the case when user is still not logged in. When the users log in, the setLocaleForAuthenticatedUser method is called and we set the session locale to the user preferred locale.
Note that substring are used to prevent problems with accurate locales such as fr_FR
It could be better, but this is a working solution


问:
How do you skip over a list comprehension in Python's debugger (pdb)?
In pdb the next instruction does not step over list comprehensions, instead it steps through each iteration. Is there a way to step over them so debugging will continue at the next line after the list comprehension?

I've had to resort to listing the code, setting a breakpoint at the next line, and then continuing execution to the next breakpoint. This is annoying and I figured there must be a better way.

答:
Elaborating on Sven's reply as I had to describe until and next to a colleague recently. It is not specific for the list comprehension that is stuck with next but for loops in general.:

The until command is like next, except that it explicitly continues until execution reaches a line in the same function with a line number higher than the current value.

Which means that you can step over loops with until

Just to cover step and next for completeness:

The step command is used to execute the current line and then stop at the next execution point

Which means that it will go instruction by instruction. Note concatenating instrucitons with ; will be handled as one instruction.

```<code>var A=0; var B=0 #Note: that will count as one instruction
</code>```

The next command is like step, but does not enter functions called from the statement being executed. In effect, it steps all the way through the function call to the next statement in the current function in a single operation.

The next helps to jump over multiple instructions, in a function of multiple variable definitions it will jump over all of them.

Here is an example that demonstrates the scenario:

Example: pdb_until.py

```<code>aVar = 3
x = [i for i in range(0,30)]
bVar = 5
</code>```

Running this with Pdb:

```<code>python -m pdb pdb_until.py
</code>```

Starts our interactive session:

```<code>> pdb_until.py(1)<module>()
-> aVar = 3
(Pdb) step                #our Input, we step
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) next                #our Input, next
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) next                #our Input, we are now stuck on line 2
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) until               #our Input, until steps over (runs list comp)
</code>```

Source: The Python Standard Library by Example, Doug Hellmann

Body:
Elaborating on Sven's reply as I had to describe until and next to a colleague recently. It is not specific for the list comprehension that is stuck with next but for loops in general.:

The until command is like next, except that it explicitly continues until execution reaches a line in the same function with a line number higher than the current value.

Which means that you can step over loops with until

Just to cover step and next for completeness:

The step command is used to execute the current line and then stop at the next execution point

Which means that it will go instruction by instruction. Note concatenating instrucitons with ; will be handled as one instruction.

var A=0; var B=0 #Note: that will count as one instruction

The next command is like step, but does not enter functions called from the statement being executed. In effect, it steps all the way through the function call to the next statement in the current function in a single operation.

The next helps to jump over multiple instructions, in a function of multiple variable definitions it will jump over all of them.

Here is an example that demonstrates the scenario:

Example: pdb_until.py

aVar = 3
x = [i for i in range(0,30)]
bVar = 5

Running this with Pdb:

python -m pdb pdb_until.py

Starts our interactive session:

> pdb_until.py(1)<module>()
-> aVar = 3
(Pdb) step                #our Input, we step
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) next                #our Input, next
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) next                #our Input, we are now stuck on line 2
> pdb_until.py(2)<module>()
-> x = [i for i in range(0,10)]
(Pdb) until               #our Input, until steps over (runs list comp)

Source: The Python Standard Library by Example, Doug Hellmann


问:
Segmented textbox in WPF
Is anyone aware of a free or commercial WPF control that would do something like this:

X character per box, and auto-tabbing to the next box as you complete each box?  Similar to the way that license keys are entered for Microsoft products.

I don't think it would be particularly hard to do from scratch, but I'd like to avoid reinventing the wheel if a good example of this already exists.

答:
WPF provides all you need except auto-tabbing to the next control.  A behavior can provide that functionality and the result looks like this:

```<code><Grid>
    <Grid.Resources>
        <local:KeyTextCollection x:Key="keys"/>
    </Grid.Resources>
    <StackPanel>
        <ItemsControl ItemsSource="{StaticResource keys}" Focusable="False">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" Background="AliceBlue"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Text}" Margin="5" MaxLength="4" Width="40">
                        <i:Interaction.Behaviors>
                            <local:TextBoxBehavior AutoTab="True" SelectOnFocus="True"/>
                        </i:Interaction.Behaviors>
                    </TextBox>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</Grid>
</code>```

Here are the KeyText and KeyTextCollection classes (adjust to taste):

```<code>class KeyText
{
    public string Text { get; set; }
}

class KeyTextCollection : List<KeyText>
{
    public KeyTextCollection()
    {
        for (int i = 0; i < 4; i++) Add(new KeyText { Text = "" });
    }
}
</code>```

And here is the behavior that implements auto-tab and select-on-focus:

```<code>public class TextBoxBehavior : Behavior<TextBox>
{
    public bool SelectOnFocus
    {
        get { return (bool)GetValue(SelectOnFocusProperty); }
        set { SetValue(SelectOnFocusProperty, value); }
    }

    public static readonly DependencyProperty SelectOnFocusProperty =
        DependencyProperty.Register("SelectOnFocus", typeof(bool), typeof(TextBoxBehavior), new UIPropertyMetadata(false));

    public bool AutoTab
    {
        get { return (bool)GetValue(AutoTabProperty); }
        set { SetValue(AutoTabProperty, value); }
    }

    public static readonly DependencyProperty AutoTabProperty =
        DependencyProperty.Register("AutoTab", typeof(bool), typeof(TextBoxBase), new UIPropertyMetadata(false));

    protected override void OnAttached()
    {
        AssociatedObject.PreviewGotKeyboardFocus += (s, e) =>
        {
            if (SelectOnFocus)
            {
                Action action = () => AssociatedObject.SelectAll();
                AssociatedObject.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
            }
        };
        AssociatedObject.TextChanged += (s, e) =>
        {
            if (AutoTab)
            {
                if (AssociatedObject.Text.Length == AssociatedObject.MaxLength &&
                    AssociatedObject.SelectionStart == AssociatedObject.MaxLength)
                {
                    AssociatedObject.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        };
    }
}
</code>```

If you are not familiar with behaviors, Install the Expression Blend 4 SDK and add this namespaces:

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
</code>```

and add System.Windows.Interactivity to your project.

ContentLicense: CC BY-SA 2.5

Title: Segmented textbox in WPF

Body:
WPF provides all you need except auto-tabbing to the next control.  A behavior can provide that functionality and the result looks like this:

<Grid>
    <Grid.Resources>
        <local:KeyTextCollection x:Key="keys"/>
    </Grid.Resources>
    <StackPanel>
        <ItemsControl ItemsSource="{StaticResource keys}" Focusable="False">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" Background="AliceBlue"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Text}" Margin="5" MaxLength="4" Width="40">
                        <i:Interaction.Behaviors>
                            <local:TextBoxBehavior AutoTab="True" SelectOnFocus="True"/>
                        </i:Interaction.Behaviors>
                    </TextBox>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</Grid>

Here are the KeyText and KeyTextCollection classes (adjust to taste):

class KeyText
{
    public string Text { get; set; }
}

class KeyTextCollection : List<KeyText>
{
    public KeyTextCollection()
    {
        for (int i = 0; i < 4; i++) Add(new KeyText { Text = "" });
    }
}

And here is the behavior that implements auto-tab and select-on-focus:

public class TextBoxBehavior : Behavior<TextBox>
{
    public bool SelectOnFocus
    {
        get { return (bool)GetValue(SelectOnFocusProperty); }
        set { SetValue(SelectOnFocusProperty, value); }
    }

    public static readonly DependencyProperty SelectOnFocusProperty =
        DependencyProperty.Register("SelectOnFocus", typeof(bool), typeof(TextBoxBehavior), new UIPropertyMetadata(false));

    public bool AutoTab
    {
        get { return (bool)GetValue(AutoTabProperty); }
        set { SetValue(AutoTabProperty, value); }
    }

    public static readonly DependencyProperty AutoTabProperty =
        DependencyProperty.Register("AutoTab", typeof(bool), typeof(TextBoxBase), new UIPropertyMetadata(false));

    protected override void OnAttached()
    {
        AssociatedObject.PreviewGotKeyboardFocus += (s, e) =>
        {
            if (SelectOnFocus)
            {
                Action action = () => AssociatedObject.SelectAll();
                AssociatedObject.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
            }
        };
        AssociatedObject.TextChanged += (s, e) =>
        {
            if (AutoTab)
            {
                if (AssociatedObject.Text.Length == AssociatedObject.MaxLength &&
                    AssociatedObject.SelectionStart == AssociatedObject.MaxLength)
                {
                    AssociatedObject.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        };
    }
}

If you are not familiar with behaviors, Install the Expression Blend 4 SDK and add this namespaces:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and add System.Windows.Interactivity to your project.


问:
Webpack3 don't recompile vendor bundle if only application code is changed
Currently I am utilizing the CommonsChunkPlugin to separate my vendor bundle (/node_modules/), from my main application bundle.  This works great.

I was originally hoping this would mean that if a change is made to my application code, a 're-packing' would be faster as the vendor bundle is separate and would not re-pack (and rarely changing).

It looks like a change to my application code also creates a new vendor bundle (when I am using watch mode or the dev server).  Is there a way to configure things to be smart and detect only application bundle changes were made and not re-pack the vendor bundle?

答:
Please have a look at the configuration in here. Try it out and see if thats what you intend to achieve.

Honestly, there is not much i had to think through. Its very well documented here.


问:
I can run docker in a directory?
Have a docker binaries, i run dockerd in /home/user/docker/ using a specific pid path in /home/user/docker/docker.pid but have an error: mkdir /var/lib/docker: permission denied. Howto set use specific lib directory? by example /home/user/docker/lib/. Need execute a docker instance without root privilegies and only write all files in specific directory. Need execute the docker without linux files structure in main host.

答: Docker requires root to run, it is modifying mount points, networking stacks, and other namespaces that cannot be done without root access. It's also a sysadmin level too that effectively gives root access to users that have access to the daemon.</p>

Title: I can run docker in a directory?


问:
sensu client subscriptions non-responding
I have setup sensu-server and client successfully and all is working except one thing . in this image

you can see that there are alerts for mysql and web ports.but I have given only "mysql" subscription right now in my client.json file in my client system. I have removed the "webserver" subscription from client.json (which I added initially before replacing it with "mysql" ) but still the checks associated with the "webserver" subscription are displayed. why is this? and how to display only the checks associated with the given subcription. here is my client.json

```<code>    {
      "client": {
       "name": "sensuclient2",
       "address": "127.0.0.1",
       "keepalive": {
      "thresholds": {
       "warning": 60,
       "critical": 120
  },

   "handlers": ["default", "mailer", "sns"]
},
  "subscriptions": [
      "mysql"
   ]

}
}
</code>```

答:
It's possible Uchiwa is showing older checks, prior to the change you made to your client configuration file (at least I went through that once!). Try deleting the events. If the API is not running the checks anymore, the events won't come up again.

You can either use sensu-cli to delete the events:

```<code>sensu-cli event delete sensuclient2 check_http
</code>```

https://github.com/agent462/sensu-cli

Or make an API call...

```<code>curl -s -i -X DELETE http://yourhost:yourport/events/sensuclient2/check_http
</code>```

https://sensuapp.org/docs/1.1/api/events-api.html#eventsclientcheck-delete

If the checks do come back you should check both server and and client side checks and client configuration.

Also, the simplest is the best, @vishal.k himself reminded me:
you can always delete the  events using Uchiwa's interface. :)

Body:
I have setup sensu-server and client successfully and all is working except one thing . in this image

you can see that there are alerts for mysql and web ports.but I have given only "mysql" subscription right now in my client.json file in my client system. I have removed the "webserver" subscription from client.json (which I added initially before replacing it with "mysql" ) but still the checks associated with the "webserver" subscription are displayed. why is this? and how to display only the checks associated with the given subcription. here is my client.json

    {
      "client": {
       "name": "sensuclient2",
       "address": "127.0.0.1",
       "keepalive": {
      "thresholds": {
       "warning": 60,
       "critical": 120
  },

   "handlers": ["default", "mailer", "sns"]
},
  "subscriptions": [
      "mysql"
   ]

}
}

Body:
It's possible Uchiwa is showing older checks, prior to the change you made to your client configuration file (at least I went through that once!). Try deleting the events. If the API is not running the checks anymore, the events won't come up again.

You can either use sensu-cli to delete the events:

sensu-cli event delete sensuclient2 check_http

https://github.com/agent462/sensu-cli

Or make an API call...

curl -s -i -X DELETE http://yourhost:yourport/events/sensuclient2/check_http

https://sensuapp.org/docs/1.1/api/events-api.html#eventsclientcheck-delete

If the checks do come back you should check both server and and client side checks and client configuration.

Also, the simplest is the best, @vishal.k himself reminded me:
you can always delete the  events using Uchiwa's interface. :)


问:
GWT - show/hide
 in a HTMLPanel
I have a HTMLPanel with a
 inside.
I want to show/hide a
 from the the java code.

I tried to put the
 inside other HTMLPanel and to hide the Panel. Something like this:

```<code>...
<tr>
  ...
</tr>
<g:HTMLPanel ui:field="name">
    <tr>
    ...
    </tr>
</g:HTMLPanel>
<tr>
  ...
</tr>
</code>```

code:

```<code>name.setVisible(false);
</code>```

and it works, but it causes a strange behaviour in the presentation.

How could I do this???

Thx a lot!!!

答:
Use an @UiField TreeRowElement rowName with the HTML being ...
...
.... Then use the TreeRowElement to show/hide that row.

Title: GWT - show/hide <tr> in a HTMLPanel

Body:
I have a HTMLPanel with a
 inside.
I want to show/hide a
 from the the java code.

I tried to put the
 inside other HTMLPanel and to hide the Panel. Something like this:

...

  ...

<g:HTMLPanel ui:field="name">

    ...

</g:HTMLPanel>

  ...

code:

name.setVisible(false);

and it works, but it causes a strange behaviour in the presentation.

How could I do this???

Thx a lot!!!

Body: Use an @UiField TreeRowElement rowName with the HTML being ...<tr ui:field="rowName">...</tr>.... Then use the TreeRowElement to show/hide that row.


问:
gulp sass: merge folders with file inheritance
I have a folder structure like this (simplified):

```<code>|-project1
|--_file1.scss
|--_file2.scss
|--_file3.scss
|
|-project2
|--_file2.scss
|
|-css
|--project1.css
|--project2.css
</code>```

I am looking for a way to compile the sass files with inheritance. The idea behind this is, that I have a base project (project1) and project 2 only contains those files that need to be changed.

So upon compilation gulp should render 2 css files:

project1.css
This contains only the files from project1/scss/ folder

project2.css
This one should contain file1 and file3 from project 1 and file2 from project 2.

Is this possible? What modules would be needed?

Thank you

答:
Here is something that should work for you.  I note that you have all and only partials in your project folders, i.e. _file1.scss, _file2.scss, etc.  You will have to have at least one file that is not a partial that imports those partials for sass to work.

```<code>const gulp = require('gulp');
const fs = require('fs');
const path = require('path');

const filter = require('gulp-filter');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const addsrc = require('gulp-add-src');

// const glob = require("glob");

const sources = ['project1', 'project2', 'project3'];
    //  could glob your sourceFolders with something like
    // const sources = glob.sync("project*");
const filterSources = Object.keys(sources);

function isUnique(file, index) {

  console.log(path.basename(file.path));  // file1.scss, file2.scss, etc.  all from project1

  baseName = path.basename(file.path);
  folder = sources[index];  // project

  //  does that basename exist in thecurrent  project (sources[index] )
  return !fs.existsSync(folder + path.sep + baseName);
}

gulp.task('default', function () {

      //  loop through all the project folders
  filterSources.forEach(function (project, index) {

    const f = filter(function (file) {
      return isUnique(file, index);
    });

    //  always using project1 files as basis
    const stream = gulp.src('./project1/*.scss')

      //  filter out from the source stream (project1 files) any files that appear in the current project directory
      .pipe(f)

      //  add all files from the current project directory, i.e., project2, project3, etc.
      .pipe(addsrc.append('./' + sources[index] + '/*.scss'))

      .pipe(sass().on('error', sass.logError))

      //  give the concat the filename of the current project
      .pipe(concat(sources[index] + '.css'))

      .pipe(gulp.dest('css'));

    return stream;
  });
</code>```

This works for any number of project folders, just make sure that your non-partial scss file that imports the others is not one that is filtered out.

But it looks like you don't really want any partials anyway since you want to concat all files in each project so remove those leading underscores from each file name.

Body:
I have a folder structure like this (simplified):

|-project1
|--_file1.scss
|--_file2.scss
|--_file3.scss
|
|-project2
|--_file2.scss
|
|-css
|--project1.css
|--project2.css

I am looking for a way to compile the sass files with inheritance. The idea behind this is, that I have a base project (project1) and project 2 only contains those files that need to be changed.

So upon compilation gulp should render 2 css files:

project1.css
This contains only the files from project1/scss/ folder

project2.css
This one should contain file1 and file3 from project 1 and file2 from project 2.

Is this possible? What modules would be needed?

Thank you

Body:
Here is something that should work for you.  I note that you have all and only partials in your project folders, i.e. _file1.scss, _file2.scss, etc.  You will have to have at least one file that is not a partial that imports those partials for sass to work.

const gulp = require('gulp');
const fs = require('fs');
const path = require('path');

const filter = require('gulp-filter');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const addsrc = require('gulp-add-src');

// const glob = require("glob");

const sources = ['project1', 'project2', 'project3'];
    //  could glob your sourceFolders with something like
    // const sources = glob.sync("project*");
const filterSources = Object.keys(sources);

function isUnique(file, index) {

  console.log(path.basename(file.path));  // file1.scss, file2.scss, etc.  all from project1

  baseName = path.basename(file.path);
  folder = sources[index];  // project

  //  does that basename exist in thecurrent  project (sources[index] )
  return !fs.existsSync(folder + path.sep + baseName);
}

gulp.task('default', function () {

      //  loop through all the project folders
  filterSources.forEach(function (project, index) {

    const f = filter(function (file) {
      return isUnique(file, index);
    });

    //  always using project1 files as basis
    const stream = gulp.src('./project1/*.scss')

      //  filter out from the source stream (project1 files) any files that appear in the current project directory
      .pipe(f)

      //  add all files from the current project directory, i.e., project2, project3, etc.
      .pipe(addsrc.append('./' + sources[index] + '/*.scss'))

      .pipe(sass().on('error', sass.logError))

      //  give the concat the filename of the current project
      .pipe(concat(sources[index] + '.css'))

      .pipe(gulp.dest('css'));

    return stream;
  });

This works for any number of project folders, just make sure that your non-partial scss file that imports the others is not one that is filtered out.

But it looks like you don't really want any partials anyway since you want to concat all files in each project so remove those leading underscores from each file name.


问:
values overwriting each other in object in setState reactjs
I am trying to pre-populate filter values that I have saved in the redux store when a user navigates back to that page where they set the filters. However, when I am going to set the state, I'm having trouble with the last set value overwriting the existing one. This is how I set the state in the constructor:

```<code>this.state = {
  hierarchyTableFilters: {
    hierarchy: null,
    signOffStatus: null,
  },
};
</code>```

and then this is how I'm going to set the state in the called function with the stored data from redux:

```<code>const {userState} = this.props.userInfo;
const previouslySelectedFilter = userState.state.hierarchyTableFilters;

if (previouslySelectedFilter) {
  this.setState({
    hierarchyTableFilters: {
      hierarchy: previouslySelectedFilter.hierarchy,
      signOffStatus: previouslySelectedFilter.signOffStatus,
    },
  });
</code>```

Whatever state gets set last is the only filter that appears pre-filtered. Is there a way to set state for two different values in an object or do I have to go about this in a different way?

答:
could you flatten your data structure to take advantage of the setState merging functionality?

```<code>this.state = {
   filtersHierarchy: null
   filtersSignOffStatus: null
 };
</code>```

with the latter piece being:

```<code>if (previouslySelectedFilter) {
  const { hierarchy, signOffStatus } = previouslySelectedFilter;
  let newState = {};
  if (hierarchy) newState.filtersHierarchy = hierarchy;
  if (signOffStatus) newState.filtersSignOffStatus = signOffStatus;
  this.setState(newState);
}
</code>```

Body:
I am trying to pre-populate filter values that I have saved in the redux store when a user navigates back to that page where they set the filters. However, when I am going to set the state, I'm having trouble with the last set value overwriting the existing one. This is how I set the state in the constructor:

this.state = {
  hierarchyTableFilters: {
    hierarchy: null,
    signOffStatus: null,
  },
};

and then this is how I'm going to set the state in the called function with the stored data from redux:

const {userState} = this.props.userInfo;
const previouslySelectedFilter = userState.state.hierarchyTableFilters;

if (previouslySelectedFilter) {
  this.setState({
    hierarchyTableFilters: {
      hierarchy: previouslySelectedFilter.hierarchy,
      signOffStatus: previouslySelectedFilter.signOffStatus,
    },
  });

Whatever state gets set last is the only filter that appears pre-filtered. Is there a way to set state for two different values in an object or do I have to go about this in a different way?

Body:
could you flatten your data structure to take advantage of the setState merging functionality?

this.state = {
   filtersHierarchy: null
   filtersSignOffStatus: null
 };

with the latter piece being:

if (previouslySelectedFilter) {
  const { hierarchy, signOffStatus } = previouslySelectedFilter;
  let newState = {};
  if (hierarchy) newState.filtersHierarchy = hierarchy;
  if (signOffStatus) newState.filtersSignOffStatus = signOffStatus;
  this.setState(newState);
}


问:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled
I, for the life of me, can't get rid of this error message. I have tried almost everything that I can.

MyDBContext.cs

```<code>        public MyDBContext() : base("ConnStr_Dev")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, DbMigrationsConfiguration<MyDBContext>>());
        //Database.SetInitializer<MyDBContext>(null);
        base.OnModelCreating(modelBuilder);
    }
</code>```

GenericRepository.cs

```<code>        public void Insert(T obj)
    {
        table.Add(obj);      //this is where it throws the error, inserting first time.
    }
</code>```

Tried all of these in different combinations

Enable-Migrations -EnableAutomaticMigrations -Force

Add-migration Initial -IgnoreChanges

Update-Database

I have tried deleting the Migrations table, deleting the entire database, everything.

Any Migrations experts please?

Edit: the DAL contains the GenericRepository and the context class.

答:
I fought with this error too. I added the migration and then made what I thought was a trivial change.

This property: IMigrationMetadata.Target in your migration isn't random. It's computed based on the state of the model at the time the migration was completed. (That may be an oversimplification.)

So if you make additional changes, it looks as there are additional pending changes that require yet another migration.

In my case, because the changes hadn't been committed to source control, the fix was to delete and re-add the migration. It took a while to figure out the cause because the error message is unclear unless you already know what's causing it. But the lesson I learned (being relatively new to EF) is that changes to the models require either a new migration or re-doing the migration that I'm working on.

Body:
I, for the life of me, can't get rid of this error message. I have tried almost everything that I can.

MyDBContext.cs

        public MyDBContext() : base("ConnStr_Dev")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, DbMigrationsConfiguration<MyDBContext>>());
        //Database.SetInitializer<MyDBContext>(null);
        base.OnModelCreating(modelBuilder);
    }

GenericRepository.cs

        public void Insert(T obj)
    {
        table.Add(obj);      //this is where it throws the error, inserting first time.
    }

Tried all of these in different combinations

Enable-Migrations -EnableAutomaticMigrations -Force

Add-migration Initial -IgnoreChanges

Update-Database

I have tried deleting the Migrations table, deleting the entire database, everything.

Any Migrations experts please?

Edit: the DAL contains the GenericRepository and the context class.


问:
Azure Cloud Service Package - Cant find Physical/Virtual Path on hosted VSTS build server
I am using a hosted build agent on VSTS, to build and deploy a Cloud Service.

When packaging the Cloud Service, cspack.exe complains that it cannot find the physical directory for a virtual path.

```<code>....
  <WebRole name="MySite" vmsize="Small">
    <Sites>
      <Site name="Web">
        <VirtualDirectory name="media" physicalDirectory="Z:\MySiteMedia" />
        <Bindings>
....
</code>```

ServiceDefinition.csdef: Error  CloudServices079 : Cannot find the
  physical directory 'Z:\MySiteMedia' for virtual path
  Web/media/.

It is true that the physical directory does not exist on the build server, but it exists on the server that the Cloud Service is going to be deployed to. It's an Azure File Share.

Is there a workaround?

Update

It is possible to create a virtual drive on the build agent, which has the required drive letter and folder. The drive could be pointing to another local drive. For intance, Z:\ could be pointing at C:\

Example:

```<code>net use Z: \\localhost\c$\MySiteMedia
</code>```

This fixes the build issue, however, it doesnt solve the actual problem.

After some digging, I found out that cspack does not work as I originally thought. When adding a

```<code><VirtualDirectory>
</code>```

to the ServiceDefition, it takes the contents of that folder and packages it in the cspkg file. Then it creates a new folder, which it places in the siteroot folder, and then creates a virtual directory to that new folder.

Example:

Becomes

Which means that the Azure File Share on Z:\ will not be used.

The workaround is to create add the virtual directory to IIS after the role has been deployed, by using a RoleEntryPoint.

答:
According to Azure Docs, this attribute defines the directory where the contents exists on the development machine - or the build machine in your scenario - not the directory where the files will be placed on production environment.

https://msdn.microsoft.com/en-us/library/azure/gg557553.aspx#Site

Required. Specifies the path on the development machine that contains
  the website or Virtual directory contents. In the compute emulator,
  IIS is configured to retrieve content from this location. When
  deploying to the Azure, the contents of the physical directory are
  packaged along with the rest of the service. When the service package
  is deployed to Azure, IIS is configured with the location of the
  unpacked contents.

Body:
I am using a hosted build agent on VSTS, to build and deploy a Cloud Service.

When packaging the Cloud Service, cspack.exe complains that it cannot find the physical directory for a virtual path.

....
  <WebRole name="MySite" vmsize="Small">
    <Sites>
      <Site name="Web">
        <VirtualDirectory name="media" physicalDirectory="Z:\MySiteMedia" />
        <Bindings>
....

ServiceDefinition.csdef: Error  CloudServices079 : Cannot find the
  physical directory 'Z:\MySiteMedia' for virtual path
  Web/media/.

It is true that the physical directory does not exist on the build server, but it exists on the server that the Cloud Service is going to be deployed to. It's an Azure File Share.

Is there a workaround?

Update

It is possible to create a virtual drive on the build agent, which has the required drive letter and folder. The drive could be pointing to another local drive. For intance, Z:\ could be pointing at C:\

Example:

net use Z: \\localhost\c$\MySiteMedia

This fixes the build issue, however, it doesnt solve the actual problem.

After some digging, I found out that cspack does not work as I originally thought. When adding a

<VirtualDirectory>

to the ServiceDefition, it takes the contents of that folder and packages it in the cspkg file. Then it creates a new folder, which it places in the siteroot folder, and then creates a virtual directory to that new folder.

Example:

Becomes

Which means that the Azure File Share on Z:\ will not be used.

The workaround is to create add the virtual directory to IIS after the role has been deployed, by using a RoleEntryPoint.


问:
How to write a BOOL predicate in Core Data?
I have an attribute of type BOOL and I want to perform a search for all managed objects where this attribute is YES.

For string attributes it is straightforward. I create a predicate like this:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName];
</code>```

But how do I do this, if I have a bool attribute called selected and I want to make a predicate for this? Could I just do something like this?

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber];
</code>```

Or do I need other format specifiers and just pass YES?

答:
Swift 4

```<code>request.predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
</code>```

Swift 3

```<code>request.predicate = NSPredicate(format: "field = %@", value as CVarArg)
</code>```

Body:
I have an attribute of type BOOL and I want to perform a search for all managed objects where this attribute is YES.

For string attributes it is straightforward. I create a predicate like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName];

But how do I do this, if I have a bool attribute called selected and I want to make a predicate for this? Could I just do something like this?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber];

Or do I need other format specifiers and just pass YES?

Body:
Swift 4

request.predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))

Swift 3

request.predicate = NSPredicate(format: "field = %@", value as CVarArg)


问:
Error while trying to compile in TinyOS
I was trying to run Blink application in TinyOS installed in Ubuntu16.06.

```<code>`make telosb reinstallbsl,/dev/ttyUSB0`
</code>```

It is showing that

```<code>../../support/make/Makerules:56:  Old TinyOS environment variables detected.

This version of the TinyOS make system has deprecated the TOSDIR, TOSROOT,
and MAKERULES environment variables. Generally, you shouldn't need
environment variables with this version of the TinyOS make system, and if
you are not using any older versions of TinyOS on your system you should
delete these environment variables. If you wish to leave these variables
but hide this warning, set the TINYOS_NO_DEPRECATION_WARNING environment
variable. If you are looking to compile against a different TinyOS tree,
configure the makefiles used when compiling, or setup an external TinyOS
tree with additional source files, please visit
https://github.com/tinyos/tinyos-main/blob/master/support/make/README.md
for more information about the TinyOS make system.
</code>```

Further down it showed:

```<code>`<JAVA_HOME> /lib/ext exists, extensions mechanism no longer supported;
Use -classpath instead.
.Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
../../support/make/Makerules:362: recipe for target 'wiring_check' failed
make: *** [wiring_check] Error 1`
</code>```

when I checked the java -version, it showed,

```<code><JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; Use -classpath instead.
.Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

Please tell me how to correct this.

答: You installed the tinyOS 3. Different from tinyOS 2-<em>, It won't use TOSDIR, TOSROOT AND MAKERULES environment variables. You should install the tinyos 2-1-2 and use that environment variables. Or you should follow the installation guide of tinyOS 3-</em> and delete all that older version environment variables. </p>

Title: Error while trying to compile in TinyOS

Body:
I was trying to run Blink application in TinyOS installed in Ubuntu16.06.

`make telosb reinstallbsl,/dev/ttyUSB0`

It is showing that

../../support/make/Makerules:56:  Old TinyOS environment variables detected.

This version of the TinyOS make system has deprecated the TOSDIR, TOSROOT,
and MAKERULES environment variables. Generally, you shouldn't need
environment variables with this version of the TinyOS make system, and if
you are not using any older versions of TinyOS on your system you should
delete these environment variables. If you wish to leave these variables
but hide this warning, set the TINYOS_NO_DEPRECATION_WARNING environment
variable. If you are looking to compile against a different TinyOS tree,
configure the makefiles used when compiling, or setup an external TinyOS
tree with additional source files, please visit
https://github.com/tinyos/tinyos-main/blob/master/support/make/README.md
for more information about the TinyOS make system.

Further down it showed:

`<JAVA_HOME> /lib/ext exists, extensions mechanism no longer supported;
Use -classpath instead.
.Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
../../support/make/Makerules:362: recipe for target 'wiring_check' failed
make: *** [wiring_check] Error 1`

when I checked the java -version, it showed,

<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; Use -classpath instead.
.Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Please tell me how to correct this.

Body: You installed the tinyOS 3. Different from tinyOS 2-, It won't use TOSDIR, TOSROOT AND MAKERULES environment variables. You should install the tinyos 2-1-2 and use that environment variables. Or you should follow the installation guide of tinyOS 3- and delete all that older version environment variables.


问:
My batch script doesn't work. Can anyone tell me why?
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?</p>

```<code>@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit
</code>```

答: Are you typing the full answer Yes or No in response to the prompts?  If you abbreviate to Y and N, only those initial characters will get stored.</p>

Body:
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?

@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit


答:
Set precision in Inkscape:

Newer version: Menubar | Edit | Preferences | Input/Output | SVG Output | Numbers

Older version: Menubar | Edit | Inkscape Preferences | SVG Output | Numbers

Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.


问:
Javascript: Loop Through Object By Number Index Rather Than Key-Value
While looping through an object is simple using for(key in object), I'd like to access an object via an index (like an array) rather than its value.

I have a "days of the week" object composed of:

```<code>days: { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y",
thursday: "N", friday: "Y", saturday: "N" }
</code>```

I want to use a for-loop which cycles through the seven days of the week (0-6) and checks whether the object is "Y" or "N" for that day (checking the "days" object for the value at key 0 (sunday), 1 (monday), 2, 3, etc.)

```<code>for (var i = 0; i < 7; i++) { }
</code>```

My problem could be solved with a bunch of if statements if i == 0 { //check sunday } else if i == 1 { //check monday } or manipulating my object into multiple arrays and going from there, however neither of these are very elegant.  Is there a way to loop through the days object and access each value by a key (0 for first, 1 for second, etc.)?

答:
You can use Map - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

const days = { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y",
thursday: "N", friday: "Y", saturday: "N" }

const map = new Map(Object.entries(days));
var mapIter = map.entries();

x = 0;
while(x < Object.keys(days).length) {
  let next = mapIter.next().value
  if(next[1] == 'Y') {
    console.log(next[0] + " is Y");
  }
  else if(next[1] == 'N') {
    console.log(next[0] + " is N");
  }
  x++;
}```

Body:
While looping through an object is simple using for(key in object), I'd like to access an object via an index (like an array) rather than its value.

I have a "days of the week" object composed of:

days: { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y",
thursday: "N", friday: "Y", saturday: "N" }

I want to use a for-loop which cycles through the seven days of the week (0-6) and checks whether the object is "Y" or "N" for that day (checking the "days" object for the value at key 0 (sunday), 1 (monday), 2, 3, etc.)

for (var i = 0; i < 7; i++) { }

My problem could be solved with a bunch of if statements if i == 0 { //check sunday } else if i == 1 { //check monday } or manipulating my object into multiple arrays and going from there, however neither of these are very elegant.  Is there a way to loop through the days object and access each value by a key (0 for first, 1 for second, etc.)?


问:
JavaScript functions help needed
I'm practicing JavaScript and have come up with a little project ... get the diameters of various bodies in our solar system when I click on corresponding buttons.

I've been able to do this, but not very efficiently. Currently, the only way my code works is with 11 functions. I also have two objects (one for the body names and the other for the body diameters).

Any feedback to make my code more efficient is very welcome. Thank you! :-)

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function suInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.su;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.su;
}

function meInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.me;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.me;
}

function veInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ve;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ve;
}

function eaInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ea;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ea;
}

function moInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.mo;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.mo;
}

function maInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ma;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ma;
}

function juInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ju;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ju;
}

function saInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.sa;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.sa;
}

function urInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ur;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ur;
}

function neInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ne;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ne;
}

function plInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.pl;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.pl;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code><!--CSS-->

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}</code>```

<button type="button" class="button" id="suButton" onclick="suInfo()">Sun</button>
<button type="button" class="button" id="meButton" onclick="meInfo()">Mercury</button>
<button type="button" class="button" id="veButton" onclick="veInfo()">Venus</button>
<button type="button" class="button" id="eaButton" onclick="eaInfo()">Earth</button>
<button type="button" class="button" id="moButton" onclick="moInfo()">Moon</button>
<button type="button" class="button" id="maButton" onclick="maInfo()">Mars</button>
<button type="button" class="button" id="juButton" onclick="juInfo()">Jupiter</button>
<button type="button" class="button" id="saButton" onclick="saInfo()">Saturn</button>
<button type="button" class="button" id="urButton" onclick="urInfo()">Uranus</button>
<button type="button" class="button" id="neButton" onclick="neInfo()">Neptune</button>
<button type="button" class="button" id="plButton" onclick="plInfo()">Pluto</button>

The diameter of this body is this many miles.
 ```

答:
Instead of using seperate functions for each button, you can pass an argument to the functions

```<code>function info(planet) {
    document.getElementById("bodyNameDisplay").innerText = bodyName[planet];
    document.getElementById("bodyDiamDisplay").innerText = bodyDiam[planet];
}
</code>```

Then in the button, you can pass the argument onclick

<button type="button" class="button" id="plButton" onclick="info('pl')">Pluto</button>

If you also want to generate the buttons automatically, you can use javascript for that as well:

html:

```<code><div id="buttons"></div>
</code>```

js:

```<code>var buttonsContainer = document.body.getElementById("buttons");
for(var planetId in bodyName){ // Loop over every planet
    var button = document.createElement("button"); // Creates <button></button>
    button.setAttribute("onclick", "info('"+planetId+"')") // Add onclick=info('id');
    button.innerText = bodyName[planetId] // Add the text inside <button>PlanetName</button>
    button.classList.add("button"); // Add the class="button" class
    button.setAttribute("id", planetId+"Button"); // Add the id="idButton"
    button.setAttribute("type", "button"); // Add the type="button"
    buttonsContainer.appendChild(button); // Add the button to the div of buttons
}
</code>```

Example:

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function info(planet) {
  document.getElementById("bodyNameDisplay").innerText = bodyName[planet];
  document.getElementById("bodyDiamDisplay").innerText = bodyDiam[planet];
}

var buttonsContainer = document.getElementById("buttons");
for(var planetId in bodyName){ // Loop over every planet
  var button = document.createElement("button"); // Creates <button></button>
  button.setAttribute("onclick", "info('"+planetId+"')") // Add onclick=info(id);
  button.innerText = bodyName[planetId] // Add the text inside <button>PlanetName</button>
  button.classList.add("button"); // Add the class="button" class
  button.setAttribute("id", planetId+"Button"); // Add the id="idButton"
  button.setAttribute("type", "button"); // Add the type="button"
  buttonsContainer.appendChild(button); // Add the button to the div of buttions
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}</code>```

The diameter of this body is this many miles.
```

Title: JavaScript functions help needed

Body:
I'm practicing JavaScript and have come up with a little project ... get the diameters of various bodies in our solar system when I click on corresponding buttons.

I've been able to do this, but not very efficiently. Currently, the only way my code works is with 11 functions. I also have two objects (one for the body names and the other for the body diameters).

Any feedback to make my code more efficient is very welcome. Thank you! :-)

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function suInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.su;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.su;
}

function meInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.me;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.me;
}

function veInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ve;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ve;
}

function eaInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ea;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ea;
}

function moInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.mo;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.mo;
}

function maInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ma;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ma;
}

function juInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ju;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ju;
}

function saInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.sa;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.sa;
}

function urInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ur;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ur;
}

function neInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ne;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ne;
}

function plInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.pl;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.pl;
}

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}

<button type="button" class="button" id="suButton" onclick="suInfo()">Sun</button>
<button type="button" class="button" id="meButton" onclick="meInfo()">Mercury</button>
<button type="button" class="button" id="veButton" onclick="veInfo()">Venus</button>
<button type="button" class="button" id="eaButton" onclick="eaInfo()">Earth</button>
<button type="button" class="button" id="moButton" onclick="moInfo()">Moon</button>
<button type="button" class="button" id="maButton" onclick="maInfo()">Mars</button>
<button type="button" class="button" id="juButton" onclick="juInfo()">Jupiter</button>
<button type="button" class="button" id="saButton" onclick="saInfo()">Saturn</button>
<button type="button" class="button" id="urButton" onclick="urInfo()">Uranus</button>
<button type="button" class="button" id="neButton" onclick="neInfo()">Neptune</button>
<button type="button" class="button" id="plButton" onclick="plInfo()">Pluto</button>

The diameter of this body is this many miles.

Body:
Instead of using seperate functions for each button, you can pass an argument to the functions

function info(planet) {
    document.getElementById("bodyNameDisplay").innerText = bodyName[planet];
    document.getElementById("bodyDiamDisplay").innerText = bodyDiam[planet];
}

Then in the button, you can pass the argument onclick

<button type="button" class="button" id="plButton" onclick="info('pl')">Pluto</button>

If you also want to generate the buttons automatically, you can use javascript for that as well:

html:

<div id="buttons"></div>

js:

var buttonsContainer = document.body.getElementById("buttons");
for(var planetId in bodyName){ // Loop over every planet
    var button = document.createElement("button"); // Creates <button></button>
    button.setAttribute("onclick", "info('"+planetId+"')") // Add onclick=info('id');
    button.innerText = bodyName[planetId] // Add the text inside <button>PlanetName</button>
    button.classList.add("button"); // Add the class="button" class
    button.setAttribute("id", planetId+"Button"); // Add the id="idButton"
    button.setAttribute("type", "button"); // Add the type="button"
    buttonsContainer.appendChild(button); // Add the button to the div of buttons
}

Example:

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function info(planet) {
  document.getElementById("bodyNameDisplay").innerText = bodyName[planet];
  document.getElementById("bodyDiamDisplay").innerText = bodyDiam[planet];
}

var buttonsContainer = document.getElementById("buttons");
for(var planetId in bodyName){ // Loop over every planet
  var button = document.createElement("button"); // Creates <button></button>
  button.setAttribute("onclick", "info('"+planetId+"')") // Add onclick=info(id);
  button.innerText = bodyName[planetId] // Add the text inside <button>PlanetName</button>
  button.classList.add("button"); // Add the class="button" class
  button.setAttribute("id", planetId+"Button"); // Add the id="idButton"
  button.setAttribute("type", "button"); // Add the type="button"
  buttonsContainer.appendChild(button); // Add the button to the div of buttions
}

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}

<!--html-->

<!--buttons-->

<div id="buttons"></div>

<!--Information Display-->

<p>The diameter of <span class="result" id="bodyNameDisplay">this body</span> is <span class="result" id="bodyDiamDisplay">this many</span> miles.</p>


答:
You can pass the planet identifier as an argument to the info() function:

```<code>function info(id) {
    document.getElementById("bodyNameDisplay").innerHTML = bodyName[id];
    document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam[id];
}
</code>```

This way one function is enough.

The HTML:

```<code><button type="button" class="button" id="suButton" onclick="info('su')">Sun</button>
</code>```

Title: JavaScript functions help needed

Body:
You can pass the planet identifier as an argument to the info() function:

function info(id) {
    document.getElementById("bodyNameDisplay").innerHTML = bodyName[id];
    document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam[id];
}

This way one function is enough.

The HTML:

<button type="button" class="button" id="suButton" onclick="info('su')">Sun</button>


问:
TomEE multiple hosts with the same app deployment issues
I am trying to set up TomEE (7.0.2) with multiple virtual hosts for development and testing environments, the same applications will usually be deployed to all hosts. I discovered from this post how to avoid the JNDI naming conflicts, which largely solved the problem of failed deployments, but I have several other issues now.

The first problem is that I still get the following severe errors in the log, although they don't seem to affect the running apps, I'm not sure how to get rid of them:

```<code>SCHWERWIEGEND - Jndi(name=global/webspi/DefaultStoredProcedureResolver) cannot be bound to Ejb(deployment-id=1774342742/ger400-q/2-webspi/webspi/DefaultDatasourceConnectorService).  Name already taken by Ejb(deployment-id=-1143530541/ger400-t/1-webspi/webspi/DefaultStoredProcedureResolver
</code>```

The second problem is that one WAR file will not deploy to one of the hosts (ger400-d below) unless it is renamed first. It will deploy to all the others with no problem. The log message generated is this:

```<code>SCHWERWIEGEND - Error merging Java EE JNDI entries in to war /webspi: Exception: null java.lang.NullPointerException
</code>```

Appending an "x" or whatever to the WAR file name makes it deploy correctly, albeit to the wrong path name.

The final issue is that stopping or undeploying one instance of the app, breaks all the other running instances, it seems that the Jax RS filters are being disturbed somehow:

```<code>    javax.servlet.ServletException: Error processing webservice request
        org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
        org.webspi.CORSFilter.doFilter(CORSFilter.java:61)
root cause
java.lang.NullPointerException
        org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:252)
        org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:251)
        org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
        org.webspi.CORSFilter.doFilter(CORSFilter.java:61)
</code>```

The relevant part of server.xml is

```<code>  <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
  </Host>
  <Host name="ger400-d"  appBase="/usr/tomee-webapps/d" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-d.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-t"  appBase="/usr/tomee-webapps/t" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-t.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-q"  appBase="/usr/tomee-webapps/q" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-q.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-r"  appBase="/usr/tomee-webapps/r" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-r.ourcompany.com</Alias>
  </Host>
</code>```

Any ideas what could be wrong?

答: I also had this problem, but being new to Tomee, I didn't know that there is a simple solution. When I deployed my web app to the webapps folder, the app worked fine, but when I deployed it to a service folder, I got the same abort. The problem was that the folder name did not match the war name (minus the .war). Once I fixed that, the app worked fine. Make sure the war name, folder name and service name are identical.</p>

Body:
I am trying to set up TomEE (7.0.2) with multiple virtual hosts for development and testing environments, the same applications will usually be deployed to all hosts. I discovered from this post how to avoid the JNDI naming conflicts, which largely solved the problem of failed deployments, but I have several other issues now.

The first problem is that I still get the following severe errors in the log, although they don't seem to affect the running apps, I'm not sure how to get rid of them:

SCHWERWIEGEND - Jndi(name=global/webspi/DefaultStoredProcedureResolver) cannot be bound to Ejb(deployment-id=1774342742/ger400-q/2-webspi/webspi/DefaultDatasourceConnectorService).  Name already taken by Ejb(deployment-id=-1143530541/ger400-t/1-webspi/webspi/DefaultStoredProcedureResolver

The second problem is that one WAR file will not deploy to one of the hosts (ger400-d below) unless it is renamed first. It will deploy to all the others with no problem. The log message generated is this:

SCHWERWIEGEND - Error merging Java EE JNDI entries in to war /webspi: Exception: null java.lang.NullPointerException

Appending an "x" or whatever to the WAR file name makes it deploy correctly, albeit to the wrong path name.

The final issue is that stopping or undeploying one instance of the app, breaks all the other running instances, it seems that the Jax RS filters are being disturbed somehow:

    javax.servlet.ServletException: Error processing webservice request
        org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
        org.webspi.CORSFilter.doFilter(CORSFilter.java:61)
root cause
java.lang.NullPointerException
        org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:252)
        org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:251)
        org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
        org.webspi.CORSFilter.doFilter(CORSFilter.java:61)

The relevant part of server.xml is

  <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
  </Host>
  <Host name="ger400-d"  appBase="/usr/tomee-webapps/d" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-d.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-t"  appBase="/usr/tomee-webapps/t" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-t.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-q"  appBase="/usr/tomee-webapps/q" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-q.ourcompany.com</Alias>
  </Host>
  <Host name="ger400-r"  appBase="/usr/tomee-webapps/r" unpackWARs="true" autoDeploy="true">
    <Alias>ger400-r.ourcompany.com</Alias>
  </Host>

Any ideas what could be wrong?


问:
How does this thing work this way,just explain
```<code>import pygame

pygame.init()
Display = pygame.display.set_mode((800,600))
pygame.display.set_caption("Blocky")

red = (157, 139, 215)
black = (0,0,0)

Display.fill(red)
pygame.draw.rect(Display,black,(400,300,200,80))

pygame.display.update()

excape = False

while not excape:
    for dork in pygame.event.get():
        print (dork)
</code>```

[

Works correctly But When I copy and paste red to pygame.draw under the update function it doesn't work.. Why doesn't ?

答:
Because (157, 139, 215) is not the color red. It's the same purple color as your background.

Replace it with red = (255, 0, 0)

and set the background display to a different fill color.

So something like this:

```<code>purple = (157, 139, 215)
red = (255, 0, 0)
black = (0,0,0)

Display.fill(purple)
pygame.draw.rect(Display,red,(400,300,200,80))
</code>```

Body:
import pygame

pygame.init()
Display = pygame.display.set_mode((800,600))
pygame.display.set_caption("Blocky")

red = (157, 139, 215)
black = (0,0,0)

Display.fill(red)
pygame.draw.rect(Display,black,(400,300,200,80))

pygame.display.update()

excape = False

while not excape:
    for dork in pygame.event.get():
        print (dork)

[

Works correctly But When I copy and paste red to pygame.draw under the update function it doesn't work.. Why doesn't ?

Body:
Because (157, 139, 215) is not the color red. It's the same purple color as your background.

Replace it with red = (255, 0, 0)

and set the background display to a different fill color.

So something like this:

purple = (157, 139, 215)
red = (255, 0, 0)
black = (0,0,0)

Display.fill(purple)
pygame.draw.rect(Display,red,(400,300,200,80))


问:
Socket read and unknown length data
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

```<code>static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}
</code>```

fd in this case is FILENO_STDIN

答: It is unusual to not have ANY way of knowing how many bytes to expect.  Most protocols have SOME way of specifying either the data length or the data terminator.  What kind of protocol are you implementing exactly?</p>

Title: Socket read and unknown length data

Body:
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}

fd in this case is FILENO_STDIN


问:
Taylor Series of ln(x) in Matlab
I am trying to compute the taylor series of ln(x) for any value of x.

What I have so far is:

```<code> clear
 clc
 n = input('Enter number of iiterations (n): ' );
 x = input('enter value of x (x): ');
 y = zeros(1,n);
 for i = 0:n
  y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end
</code>```

But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?

答:
Try this:</p>

```<code>clear
clc

n = input('Enter number of iterations (n): ' );
x = input('enter value of x with abs value < 1 (x): ');
y = zeros(1,n+1);

y(1)=0;

for i = 1:n
    y(i+1)= y(i) + ((-1)^(i+1)*(x-1)^i/i);
end

txt = sprintf('The output is: %f', y(n+1))
</code>```

Title: Taylor Series of ln(x) in Matlab

Body:
I am trying to compute the taylor series of ln(x) for any value of x.

What I have so far is:

 clear
 clc
 n = input('Enter number of iiterations (n): ' );
 x = input('enter value of x (x): ');
 y = zeros(1,n);
 for i = 0:n
  y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end

But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?

Body:
Try this:

clear
clc

n = input('Enter number of iterations (n): ' );
x = input('enter value of x with abs value < 1 (x): ');
y = zeros(1,n+1);

y(1)=0;

for i = 1:n
    y(i+1)= y(i) + ((-1)^(i+1)*(x-1)^i/i);
end

txt = sprintf('The output is: %f', y(n+1))