问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
Here's sort of compromise, if you want to keep the indentation as it is:

```<code>boolean valid = true;  // optimistic start

if (!valid || !condition1)
   valid = false;

if (!valid || !condition2)
   valid = false;

if (!valid || !condition3)
   valid = false;

if (valid)
   doSomething();
</code>```

The !valid in the first if statement is superflucious but doesn't harm, could be kept for readability. else/if is more elegant, to my opinion, but that's just an opinion.

But I really wouldn't (ab-)use the for loop and I never ever would find a cheap way to implement a pseudo-goto. There's always a better solution.

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
Here's sort of compromise, if you want to keep the indentation as it is:

boolean valid = true;  // optimistic start

if (!valid || !condition1)
   valid = false;

if (!valid || !condition2)
   valid = false;

if (!valid || !condition3)
   valid = false;

if (valid)
   doSomething();

The !valid in the first if statement is superflucious but doesn't harm, could be kept for readability. else/if is more elegant, to my opinion, but that's just an opinion.

But I really wouldn't (ab-)use the for loop and I never ever would find a cheap way to implement a pseudo-goto. There's always a better solution.


来源: stackexchange

问:
Remote Desktop Connection with MSTSCLib
I'm trying to code a Remote Desktop Application using C# .NET.

I followed some examples (listed below) and created a Windows Form, added references to MSTSLib, added Microsoft Terminal Service Control to the Form and code the following behavior:

```<code>namespace RDConnector
{
    public partial class Form1 : Form
    {
        const string server = "55.55.55.555";
        const string userNameBase = "username";
        const string passwordBase = "password";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                rdClient.Server = server;
                rdClient.UserName = userNameBase;

                /*IMsTscNonScriptable secured = (IMsTscNonScriptable)rdClient.GetOcx();
                secured.ClearTextPassword = passwordBase;*/

                rdClient.AdvancedSettings8.DisplayConnectionBar = true;
                rdClient.AdvancedSettings8.ClearTextPassword = passwordBase;
                rdClient.AdvancedSettings8.EncryptionEnabled = -1;

                //// Start connection
                rdClient.Connect();
                MessageBox.Show("Connection Status + " + rdClient.Connected.ToString());

            }
            catch (Exception Ex)
            {
                MessageBox.Show("Exception ocurred: " + Ex.Message);
            }
        }
    }
}
</code>```

However, it isn't working, the Connection status after calling rdClient.Connect() is 2 (0 before calling it), but nothing happens. I also ran the Example 1 and it doesn't work.

I'm using Windows 7 - 64 bit and Visual Studio C# Express. Visual Express Edition doesn't have a X64 compiler, Could be the problem related with that?

I'll really appreciate your help.

Examples:

http://www.codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx

Running COM component controls on multiple threads

答: I found the problem at last. When you want to choose COM Components, just select "Microsoft RDP Client Control - version x". I choose the 8 version that works perfectly for me.</p>

ContentLicense: CC BY-SA 3.0

Title: Remote Desktop Connection with MSTSCLib

Body:
I'm trying to code a Remote Desktop Application using C# .NET.

I followed some examples (listed below) and created a Windows Form, added references to MSTSLib, added Microsoft Terminal Service Control to the Form and code the following behavior:

namespace RDConnector
{
    public partial class Form1 : Form
    {
        const string server = "55.55.55.555";
        const string userNameBase = "username";
        const string passwordBase = "password";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                rdClient.Server = server;
                rdClient.UserName = userNameBase;

                /*IMsTscNonScriptable secured = (IMsTscNonScriptable)rdClient.GetOcx();
                secured.ClearTextPassword = passwordBase;*/

                rdClient.AdvancedSettings8.DisplayConnectionBar = true;
                rdClient.AdvancedSettings8.ClearTextPassword = passwordBase;
                rdClient.AdvancedSettings8.EncryptionEnabled = -1;

                //// Start connection
                rdClient.Connect();
                MessageBox.Show("Connection Status + " + rdClient.Connected.ToString());

            }
            catch (Exception Ex)
            {
                MessageBox.Show("Exception ocurred: " + Ex.Message);
            }
        }
    }
}

However, it isn't working, the Connection status after calling rdClient.Connect() is 2 (0 before calling it), but nothing happens. I also ran the Example 1 and it doesn't work.

I'm using Windows 7 - 64 bit and Visual Studio C# Express. Visual Express Edition doesn't have a X64 compiler, Could be the problem related with that?

I'll really appreciate your help.

Examples:

http://www.codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx

Running COM component controls on multiple threads


问:
How to change nnoremap for different file types?
When I hit <leader>r inside a PHP file, I want to do:

```<code> nnoremap <leader>r ifile_put_contents(ini_get('error_log'), '');<cr>error_log(print_r(, true));<esc>
</code>```

But when I do the <leader>r inside a JS file, I want to do:

```<code> nnoremap <leader>r iconsole.log();<esc>
</code>```

How could I do this?

I also want to position the cursor inside the console.log/print_r. Any idea how to do that as well?

答:
You can use autocomand and map to the buffer only. Here's an example:

```<code>augroup quick_debug
  autocmd!
  autocmd FileType php nnoremap <buffer> <leader>r ifile_put_contents(ini_get('error_log'), '');<cr>error_log(print_r(, true));<esc>
  autocmd FileType javascript nnoremap <buffer> <leader>r iconsole.log();<esc>

augroup END
</code>```

To move cursor around you can use <left> and <right> before <esc>. Like this: nnoremap <buffer> <leader>r iconsole.log();<left><left><esc>.

If you don't mind using plugins you could take a look at the UltiSnips and use snippets instead of mappings.

Body:
When I hit <leader>r inside a PHP file, I want to do:

 nnoremap <leader>r ifile_put_contents(ini_get('error_log'), '');<cr>error_log(print_r(, true));<esc>

But when I do the <leader>r inside a JS file, I want to do:

 nnoremap <leader>r iconsole.log();<esc>

How could I do this?

I also want to position the cursor inside the console.log/print_r. Any idea how to do that as well?

Body:
You can use autocomand and map to the buffer only. Here's an example:

augroup quick_debug
  autocmd!
  autocmd FileType php nnoremap <buffer> <leader>r ifile_put_contents(ini_get('error_log'), '');<cr>error_log(print_r(, true));<esc>
  autocmd FileType javascript nnoremap <buffer> <leader>r iconsole.log();<esc>

augroup END

To move cursor around you can use <left> and <right> before <esc>. Like this: nnoremap <buffer> <leader>r iconsole.log();<left><left><esc>.

If you don't mind using plugins you could take a look at the UltiSnips and use snippets instead of mappings.


问:
Creating multiple (15+) HTTP Response filters, Inheritance vs. Composition w/ Injection
First a little back story on what I am trying to accomplish.

I am in the process of creating a custom HTTP Module whose purposes is to intercept messages to multiple (15+) different ArcGIS REST web services. The intercepted requests and/or responses will be stripped of any restricted information based on the current user.

For instance, a call that returns multiple layers might have certain layers stripped out.

Unmodified Response:

```<code>"layers" : [
    {
      "id" : 0,
      "name" : "Facilities",
      "parentLayerId" : -1,
      "defaultVisibility" : true,
      "subLayerIds" : [1, 2, 3]
    },
    {
      "id" : 1,
      "name" : "Hazardous Sites",
      "parentLayerId" : 0,
      "defaultVisibility" : true,
      "subLayerIds" : null
    },
]
</code>```

Modified Response:

```<code>"layers" : [
    {
      "id" : 0,
      "name" : "Facilities",
      "parentLayerId" : -1,
      "defaultVisibility" : true,
      "subLayerIds" : [1, 2, 3]
    }
]
</code>```

There are numerous services available, all uniquely identified via a URL. Each service returns very different information and so needs to be filtered different.  Additionally, each service may return the data in a variety of formats (HTML, JSON, etc).

As such, I will need to create a multitude of different filters to apply to HttpRequest.Filters and/or HttpResponse.Filters.

Example:

```<code>// Request for layers and the format is JSON
IPolicy policy = GetPolicy(userContext);
Filter filter = new LayerJsonResponseFilter(Response.Filter, policy);
Response.Filter = filter;
</code>```

Request and response filters are implemented by inheriting from Stream (or another class that inherits from Stream such as MemoryStream). I want to be able to easily create new filters without reimplementing Stream for each filter.

A potential solution is described in here: http://www.west-wind.com/weblog/posts/72596.aspx

However, I want to simplify the solution without losing the flexibility of specifying many different transformations without reimplementing the stream.  I think that I can accomplish this by:

Inherit from MemoryStream so as to reduce the reimplementation of methods.

Always operate on full content, rather than chunked content.

Replace the events with an abstract method (e.g., Filter())

I have considered two potential solutions.

Solution 1: Create Multiple Filters Inheriting from ResponseFilter

In this scenario each filter contains the logic for performing the filtration. There would be 15+ filters created all inheriting from a common ResponseFilter abstract base class like so:

```<code>// All filters will inherit from ResponseFilter
public abstract class ResponseFilter : MemoryStream
{
    public ResponseFilter(Stream stream, Policy policy) { }

    // Must be overridden in a derived class with specific Filter logic.
    public abstract string Filter(string content);

    // Overridden to cache content.
    public override void Write(byte[] buffer, int offset, int count) { }

    // Overridden to perform the filter/transformation before the content is written.
    public override void Flush()
    {
         // Get stream content as a string

         string content = Filter(content);

         // Write new content to stream
    }
}
</code>```

This would be used in the following way.

```<code>// Example
var policy = GetPolicy();
var filter = new MapServiceJsonResponseFilter(response.Filter, policy);
response.Filter = filter;
</code>```

The advantage to this option is that the number of classes is kept to a minimum. However, it becomes difficult to reuse any filter logic anywhere else in the application should it become necessary. Additionally, unit testing the filters would require mocking the Stream, another disadvantage.

Solution 2: Create Multiple Filters, Inject into a Common ResponseFilter

In this scenario, a single response filter is created. The actual filter logic or algorithm is injected into the filter.  All filters inherit from an abstract base class FilterBase.

```<code>// Represents an HttpResponse Filter. Renamed to avoid confusion with
// the filter algorithm.
public class ResponseFilterStream : MemoryStream
{
    public ResponseFilterStream(Stream stream, FilterBase filter) { }

    // Overridden to cache content.
    public override void Write(byte[] buffer, int offset, int count) { }

    // Overridden to perform the filter/transformation before the content is written.
    public override void Flush()
    {
         // Get stream content as a string

         string content = _filter.Filter(content);

         // Write new content to stream
    }
}

// All filter algorithms inherit from FilterBase and must implement
// the filter method.
public abstract class FilterBase
{
    protected TransformBase(Policy policy) { }

    // Overridden to perform the filter/transformation.
    public abstract string Filter(string content);
}
</code>```

This would be used in the following way.

```<code>// Example
var policy = GetPolicy();
var filter = new MapServiceJsonResponseFilter(policy);
ResponseFilter responseFilter = new ResponseFilter(response.Filter, filter);
response.Filter = filter;
</code>```

The advantage to this solution is that the filtration logic is completely independent of any classes that implement stream. The logic can be more easily reused if necessary. Unit testing is a little simpler as well as I do not need to mock the stream.

However, there are more classes (exactly 1) and the usage is a little more complex, though not terribly so.

Note: I'll probably want to rename FilterBase as to avoid confusion with ResponseFilter.  Perhaps TransformBase.

I have several goals that I want to meet with either solution.

The solution must be highly testable. Unit testing will be used to check for correctness of the filters. It is imperative that testing is as simple as possible.

The solution must easily support the creation of multiple filters (15+).

The solution should be readable (i.e., easy to maintain).

I think that solution 2 is the best solution for this given scenario. I can test the filtration logic completely independently of Stream with minimal additional complexity.  Either solution will support #2 and #3, so testing gets the edge.

What other considerations might there be?  Are there better alternatives?

答: Solution 2 is obviously preferable.  However, it seems that the major crux of the problem lies in the construction of the Filters themselves.  Hopefully there is a lot of reusable composition within the Filter implementations.  Can a new filter be "configured" from composite parts?</p>

ContentLicense: CC BY-SA 2.5

Body:
First a little back story on what I am trying to accomplish.

I am in the process of creating a custom HTTP Module whose purposes is to intercept messages to multiple (15+) different ArcGIS REST web services. The intercepted requests and/or responses will be stripped of any restricted information based on the current user.

For instance, a call that returns multiple layers might have certain layers stripped out.

Unmodified Response:

"layers" : [
    {
      "id" : 0,
      "name" : "Facilities",
      "parentLayerId" : -1,
      "defaultVisibility" : true,
      "subLayerIds" : [1, 2, 3]
    },
    {
      "id" : 1,
      "name" : "Hazardous Sites",
      "parentLayerId" : 0,
      "defaultVisibility" : true,
      "subLayerIds" : null
    },
]

Modified Response:

"layers" : [
    {
      "id" : 0,
      "name" : "Facilities",
      "parentLayerId" : -1,
      "defaultVisibility" : true,
      "subLayerIds" : [1, 2, 3]
    }
]

There are numerous services available, all uniquely identified via a URL. Each service returns very different information and so needs to be filtered different.  Additionally, each service may return the data in a variety of formats (HTML, JSON, etc).

As such, I will need to create a multitude of different filters to apply to HttpRequest.Filters and/or HttpResponse.Filters.

Example:

// Request for layers and the format is JSON
IPolicy policy = GetPolicy(userContext);
Filter filter = new LayerJsonResponseFilter(Response.Filter, policy);
Response.Filter = filter;

Request and response filters are implemented by inheriting from Stream (or another class that inherits from Stream such as MemoryStream). I want to be able to easily create new filters without reimplementing Stream for each filter.

A potential solution is described in here: http://www.west-wind.com/weblog/posts/72596.aspx

However, I want to simplify the solution without losing the flexibility of specifying many different transformations without reimplementing the stream.  I think that I can accomplish this by:

Inherit from MemoryStream so as to reduce the reimplementation of methods.

Always operate on full content, rather than chunked content.

Replace the events with an abstract method (e.g., Filter())

I have considered two potential solutions.

Solution 1: Create Multiple Filters Inheriting from ResponseFilter

In this scenario each filter contains the logic for performing the filtration. There would be 15+ filters created all inheriting from a common ResponseFilter abstract base class like so:

// All filters will inherit from ResponseFilter
public abstract class ResponseFilter : MemoryStream
{
    public ResponseFilter(Stream stream, Policy policy) { }

    // Must be overridden in a derived class with specific Filter logic.
    public abstract string Filter(string content);

    // Overridden to cache content.
    public override void Write(byte[] buffer, int offset, int count) { }

    // Overridden to perform the filter/transformation before the content is written.
    public override void Flush()
    {
         // Get stream content as a string

         string content = Filter(content);

         // Write new content to stream
    }
}

This would be used in the following way.

// Example
var policy = GetPolicy();
var filter = new MapServiceJsonResponseFilter(response.Filter, policy);
response.Filter = filter;

The advantage to this option is that the number of classes is kept to a minimum. However, it becomes difficult to reuse any filter logic anywhere else in the application should it become necessary. Additionally, unit testing the filters would require mocking the Stream, another disadvantage.

Solution 2: Create Multiple Filters, Inject into a Common ResponseFilter

In this scenario, a single response filter is created. The actual filter logic or algorithm is injected into the filter.  All filters inherit from an abstract base class FilterBase.

// Represents an HttpResponse Filter. Renamed to avoid confusion with
// the filter algorithm.
public class ResponseFilterStream : MemoryStream
{
    public ResponseFilterStream(Stream stream, FilterBase filter) { }

    // Overridden to cache content.
    public override void Write(byte[] buffer, int offset, int count) { }

    // Overridden to perform the filter/transformation before the content is written.
    public override void Flush()
    {
         // Get stream content as a string

         string content = _filter.Filter(content);

         // Write new content to stream
    }
}

// All filter algorithms inherit from FilterBase and must implement
// the filter method.
public abstract class FilterBase
{
    protected TransformBase(Policy policy) { }

    // Overridden to perform the filter/transformation.
    public abstract string Filter(string content);
}

This would be used in the following way.

// Example
var policy = GetPolicy();
var filter = new MapServiceJsonResponseFilter(policy);
ResponseFilter responseFilter = new ResponseFilter(response.Filter, filter);
response.Filter = filter;

The advantage to this solution is that the filtration logic is completely independent of any classes that implement stream. The logic can be more easily reused if necessary. Unit testing is a little simpler as well as I do not need to mock the stream.

However, there are more classes (exactly 1) and the usage is a little more complex, though not terribly so.

Note: I'll probably want to rename FilterBase as to avoid confusion with ResponseFilter.  Perhaps TransformBase.

I have several goals that I want to meet with either solution.

The solution must be highly testable. Unit testing will be used to check for correctness of the filters. It is imperative that testing is as simple as possible.

The solution must easily support the creation of multiple filters (15+).

The solution should be readable (i.e., easy to maintain).

I think that solution 2 is the best solution for this given scenario. I can test the filtration logic completely independently of Stream with minimal additional complexity.  Either solution will support #2 and #3, so testing gets the edge.

What other considerations might there be?  Are there better alternatives?


问:
Android WVMExtractor: Failed to open libwvm.so
I am developing game in android using cocos2d-x plateform. I include game .so file in android code. Game working fine in marshmallow and below version devices but when i run this app in android 7 nougat getting unknown error.

```<code>E/WVMExtractor: Failed to open libwvm.so: dlopen failed: library "libstlport.so" not found
</code>```

I am sure that problem is in .so file. in .so file following line creating problem. sounds not working in android 7 Nougat.

```<code>CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(writable);
</code>```

is it any alternate method to play sound in cocos2d-x plateform.

答:
For Sound Effects, .mp3 only supports on iOS, According to cocos2d-x wiki :

Sound Effects

```<code>|    Platform     |   supported sound effects formats   |
|-----------------|:-----------------------------------:|
| Android Supports|         .ogg , .wav format.         |
| iOS             |          .mp3, .wav, .caf           |
| Windows Desktop |         .mid and .wav only          |
</code>```

May be wiki is outdated so some OS of Android start supporting .mp3 file for Sound Effect.  But from your test still android 7 nougat version not supporting .mp3 file.

Body:
I am developing game in android using cocos2d-x plateform. I include game .so file in android code. Game working fine in marshmallow and below version devices but when i run this app in android 7 nougat getting unknown error.

E/WVMExtractor: Failed to open libwvm.so: dlopen failed: library "libstlport.so" not found

I am sure that problem is in .so file. in .so file following line creating problem. sounds not working in android 7 Nougat.

CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(writable);

is it any alternate method to play sound in cocos2d-x plateform.

Body:
For Sound Effects, .mp3 only supports on iOS, According to cocos2d-x wiki :

Sound Effects

|    Platform     |   supported sound effects formats   |
|-----------------|:-----------------------------------:|
| Android Supports|         .ogg , .wav format.         |
| iOS             |          .mp3, .wav, .caf           |
| Windows Desktop |         .mid and .wav only          |

May be wiki is outdated so some OS of Android start supporting .mp3 file for Sound Effect.  But from your test still android 7 nougat version not supporting .mp3 file.


问:
Reloading jquery tab causes duplicate event firing
I have some jquery tabs where some are loaded via ajax. When first loaded they are fine, the events fire once as required but when I click to a different tab and then go back to the tab loaded by ajax, the jquery events are fired twice, subsequent loads of the tab, add another event fire.. It seems the jquery is getting loaded again and again but when I inspect on chrome I can only see it once so I don't know whats going on. Any help would be appreciated..
Here is an example..

outerTabs.jsp

```<code><html>
<head>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/jquery-ui.css">
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery.js"></script>
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-ui.js"></script>
    <script>var contextPath = "${pageContext.request.contextPath}";</script>
    <script type="text/javascript">
        $( document ).ready(function() {
            $("#outerTabs").tabs();
        });
    </script>
</head>
<body>
    <div id="outerTabs">
        <ul>
            <li><a href="#outerTab1">outerTab1</a></li>
            <li><a href="${pageContext.servletContext.contextPath}/getTab2?param=param1">outerTab2</a></li>
        </ul>
    </div>
    <div id="outerTab1"></div>
</body>
</html>
</code>```

tab2.jsp

```<code><html>
  <head>
<script type="text/javascript">
    $( document ).ready(function() {
        $("body").on("click", "#link1", function(e) {
            alert("clicked");
        });
    });
</script>
  </head>
<body>
    <a id="return">return</a>
    <div id="tab1">
        <a id="link1">
        link1
        </a>
   </div>
</body>
</html>
</code>```

controller

```<code>@Controller
public class Controller {
@RequestMapping(value = { "/loadTabs" }, method = RequestMethod.GET)
public ModelAndView loadTabs() {
    ModelAndView model = new ModelAndView();
    model.setViewName("outerTabs");
    return model;
}

@RequestMapping(value = { "/getTab2" }, method = RequestMethod.GET)
public ModelAndView getTab1(@RequestParam("param") String param) {
    ModelAndView model = new ModelAndView();
    model.addObject("tab2Content", null);
    model.setViewName("tab2");
    return model;
}
}
</code>```

So in this example when I load tab 2 and then click back to tab1 and then click tab 2 again, clicking the link1 link causes alert to display twice.

答:
You give the element #link1 the click-event again on every reload. You could use the http://api.jquery.com/off/ of the jquery-lib to avoid the second alert.
Here is an example:</p>

```<code>$( document ).ready(function() {
    $("#link1").off("click").on("click", function(e) {
        alert("clicked");
    });
});
</code>```

Body:
I have some jquery tabs where some are loaded via ajax. When first loaded they are fine, the events fire once as required but when I click to a different tab and then go back to the tab loaded by ajax, the jquery events are fired twice, subsequent loads of the tab, add another event fire.. It seems the jquery is getting loaded again and again but when I inspect on chrome I can only see it once so I don't know whats going on. Any help would be appreciated..
Here is an example..

outerTabs.jsp

    <link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/jquery-ui.css">

outerTab1

outerTab2

tab2.jsp

    return

        link1

controller

@Controller
public class Controller {
@RequestMapping(value = { "/loadTabs" }, method = RequestMethod.GET)
public ModelAndView loadTabs() {
    ModelAndView model = new ModelAndView();
    model.setViewName("outerTabs");
    return model;
}

@RequestMapping(value = { "/getTab2" }, method = RequestMethod.GET)
public ModelAndView getTab1(@RequestParam("param") String param) {
    ModelAndView model = new ModelAndView();
    model.addObject("tab2Content", null);
    model.setViewName("tab2");
    return model;
}
}

So in this example when I load tab 2 and then click back to tab1 and then click tab 2 again, clicking the link1 link causes alert to display twice.

Body:
You give the element #link1 the click-event again on every reload. You could use the http://api.jquery.com/off/ of the jquery-lib to avoid the second alert.
Here is an example:

$( document ).ready(function() {
    $("#link1").off("click").on("click", function(e) {
        alert("clicked");
    });
});


问:
Split Netcdf variable and re-write the file
I have a netcdf file that contains air quality data. There are 4 dimensions:

```<code>time : 24 hours (midnight to midnight)
level : 1 to 8 (this is the height in meters (0, 50, 250, 500, 1000, 2000, 3000, 5000 m))
latitude : 1 to 400
longitude : 1 to 700
</code>```

I want to make a new netcdf file retaining only level 1, deleting the other levels, as I only need the surface.

How can I do that ?

I tried to do this with nccopy command line but it reproduces the dataset. I don't know how can I delete the other levels.

答:
You can do this in cdo using

```<code>cdo sellevel,lev in.nc out.nc
</code>```

Selects all fields with levels as required in a user given list, or

```<code>cdo sellevidx,idx in.nc out.nc
</code>```

allows you to select by level index instead. Further details here:

https://code.mpimet.mpg.de/projects/cdo/embedded/index.html#x1-1360002.3.3

Body:
I have a netcdf file that contains air quality data. There are 4 dimensions:

time : 24 hours (midnight to midnight)
level : 1 to 8 (this is the height in meters (0, 50, 250, 500, 1000, 2000, 3000, 5000 m))
latitude : 1 to 400
longitude : 1 to 700

I want to make a new netcdf file retaining only level 1, deleting the other levels, as I only need the surface.

How can I do that ?

I tried to do this with nccopy command line but it reproduces the dataset. I don't know how can I delete the other levels.

Body:
You can do this in cdo using

cdo sellevel,lev in.nc out.nc

Selects all fields with levels as required in a user given list, or

cdo sellevidx,idx in.nc out.nc

allows you to select by level index instead. Further details here:

https://code.mpimet.mpg.de/projects/cdo/embedded/index.html#x1-1360002.3.3


问:
Recognizing a link on a website to click on it in a using screen visual only

What I want to do is to write a Python script to recognize a specific link and make a left-click on it. To be more explanatory, here are two images from websites:

Page 1

and

Page 2

I want the script to click on "enter site" in page 1 and "try again" on page 2. If possible I want to use machine learning having only the screen image input. It is probably easier to go through the site source, but I want to be further challenged. I gave this a thought but couldn't figure out where to start.

答:
you can use selenium:

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

driver = webdriver.Firefox()
driver.get("http://www.youradress.org")#put here the adress of your page
elem = driver.find_elements_by_xpath("//*[@type='submit']")#put here the content you have put in Notepad, ie the XPath
print(elem .get_attribute("class"))
driver.close()
</code>```

you can get the class of the html element, or its id, and then pass it to the script and do whatever you want.

Body:
you can use selenium:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.youradress.org")#put here the adress of your page
elem = driver.find_elements_by_xpath("//*[@type='submit']")#put here the content you have put in Notepad, ie the XPath
print(elem .get_attribute("class"))
driver.close()

you can get the class of the html element, or its id, and then pass it to the script and do whatever you want.


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答:
You can remove margin left & right and use flexbox on .center like this :

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;
}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.bg05Off, .bg04Off, .bg03Off, .bg02Off, .bg01Off {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.center {
  display: flex;
  justify-content: space-around;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

Body:
You can remove margin left & right and use flexbox on .center like this :

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;
}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.bg05Off, .bg04Off, .bg03Off, .bg02Off, .bg01Off {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.center {
  display: flex;
  justify-content: space-around;
}

<div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div>


问:
Do offline ARM cores in Linux still consume power?
In Fedora24 if a ARM core is set to offline, is it still consuming power?  e.g. running at lowest clock (400MHz) but not scheduled for any tasks by the kernel?  Or is the core actually powered off or in a deep sleep state?

My current measurements of a quad core ARM do not indicate any decrease when cores 1,2,3 are set to offline.

```<code>echo "0" > /sys/devices/system/cpu/cpu1/online
echo "0" > /sys/devices/system/cpu/cpu2/online
echo "0" > /sys/devices/system/cpu/cpu3/online

cat /sys/devices/system/cpu/online   < returns 0 >
</code>```

答: It is still consuming power because you set it on a clock speed that is more than zero.</p>

Body:
In Fedora24 if a ARM core is set to offline, is it still consuming power?  e.g. running at lowest clock (400MHz) but not scheduled for any tasks by the kernel?  Or is the core actually powered off or in a deep sleep state?

My current measurements of a quad core ARM do not indicate any decrease when cores 1,2,3 are set to offline.

echo "0" > /sys/devices/system/cpu/cpu1/online
echo "0" > /sys/devices/system/cpu/cpu2/online
echo "0" > /sys/devices/system/cpu/cpu3/online

cat /sys/devices/system/cpu/online   < returns 0 >


问:
how to know how many times its a value in the databes? and for all values?
This can be aplied to tags, to coments, ...

My question its to obtain for example, top 20 repetitions for an atribute in  a table..

I mean, i know i can ask for a selected atribute with the mysql_num_rows, but how do i do it to know all of them?

For example,

Most popular colors:
Red -100000
blue -5000
white -200
and so on...

if anyone can give me a clue.. thanks!

答:
```<code>SELECT `name`, count(*) as `count` FROM `colors`
GROUP BY `name`
ORDER BY `count` DESC
</code>```


问:
Parse HTML string in Angular 2 and extract and update values
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

```<code><div [innerHTML]="displayString"></div>
</code>```

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

答:
You can use DomSanitizer from platform-browser module

```<code>import {DomSanitizer} from '@angular/platform-browser';
</code>```

Inject DomSanitizer in your component by initializing it in your constructor

```<code>  constructor(private domSanitizer: DomSanitizer)
</code>```

use bypassSecurityTrustHtml()  of DomSanitizer  and pass your raw html content:

```<code>this.displayString= this.domSanitizer.bypassSecurityTrustHtml("<svg><text data-card-text>Value I want to update</text></svg>");
</code>```

I hope this will solve your problem.

Body:
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

Body:
You can use DomSanitizer from platform-browser module

import {DomSanitizer} from '@angular/platform-browser';

Inject DomSanitizer in your component by initializing it in your constructor

  constructor(private domSanitizer: DomSanitizer)

use bypassSecurityTrustHtml()  of DomSanitizer  and pass your raw html content:

this.displayString= this.domSanitizer.bypassSecurityTrustHtml("<svg><text data-card-text>Value I want to update</text></svg>");

I hope this will solve your problem.


问:
C1 Tab Control leaving gaps if tabs are hidden
I am in the process of migrating my accounting software's usage of Farpoint's Tab Pro 2.0 to the ComponentOne Tab control.  The only problem I'm having so far is that some of my tabs will be hidden in some scenarios, like if the user has a certain combination of packages (A/R, G/L, A/P, etc.) that affect data entry.

On Tab Pro, when I made a tab not visible, it would then adjust the presentation of the tabs in a multiple-row setup such that there were no gaps, but the C1 Tab leaves the gaps, which looks bad.

Is there a way to tell the C1 Tab to not display a tab and move the subsequent tab(s) to the left to fill-in the gap(s)?

答: I decided to alter the program to work around this short-coming by arranging the tabs such that if there were only one boolean scenario, that tab or tabs would be moved to the end of the list and would then be flagged as not visible.  In cases where this was not possible or would not make sense, I had to settle for making the tabs disabled.  The reason I prefer to avoid this is because there are circumstances where there are custom variations of my software that would enable tabs, but other users might be confused with their presence.  There are also situations where the tabs could become valid/invalid based on the entry in other tabs, so they also have to be disabled.</p>


答:
It is not JQuery being loaded, but the event being rebind over and over.
One option would be having an 'is-bound' flag.
Such as:

```<code>    $("body").on("click", "#link1:not(.is-bound)", function(e) {
        alert("clicked");
        $(this).addClass('is-bound');
    });
</code>```

This way your function will trigger only if the element was not previously bound.

Title: Reloading jquery tab causes duplicate event firing

Body:
It is not JQuery being loaded, but the event being rebind over and over.
One option would be having an 'is-bound' flag.
Such as:

    $("body").on("click", "#link1:not(.is-bound)", function(e) {
        alert("clicked");
        $(this).addClass('is-bound');
    });

This way your function will trigger only if the element was not previously bound.


问:
How to create Most Recently Used list in android studio
Im new to app building and im building an application which stores a profile and data. i want to add an activity where i can display a list of the most recently viewed profiles. Where do i start???</p>

答: When viewing profile add timestamp to it. And when displaying profiles sort them by timestamp you created.</p>


问:
Add Image to an Apple Watch Button
I want to do is add an image to one of my buttons. I uploaded an image to my Assets folder and whenever I add it as a background it comes out blank. I even tried adding a group with a background and it still doesn't work. I don't know why its not working. When I set a color to the button it shows but a background image won't show up. It seems so simple but when I run it the background is black. Please help.

答: The Images worked after I moved the images to the Assets folder of the WatchKit App instead of the WatchKit App Extension. Also, I changed the names to make sure they were correct. </p>

Title: Add Image to an Apple Watch Button


问:
Angular 2 Hover event
In the new Angular2 framework, does anyone know the proper way to do a hover like an event?

In Angular1 there was ng-Mouseover, but that doesn't seem to have been carried over.

I've looked through the docs and haven't found anything.

答:
If you are interested in the mouse entering or leaving one of your components you can use the @HostListener decorator:

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

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  @HostListener('mouseenter')
  onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.highlight(null);
  }

...

}
</code>```

As explained in the link in @Brandon comment to OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html)

ContentLicense: CC BY-SA 4.0

Title: Angular 2 Hover event

Body:
If you are interested in the mouse entering or leaving one of your components you can use the @HostListener decorator:

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

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  @HostListener('mouseenter')
  onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.highlight(null);
  }

...

}

As explained in the link in @Brandon comment to OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html)


Title: How to get indices of outliers in a dataframe boxplot?

Body:
I have a dataframe and I want to get each columns of outliers indices.

Here is part of my dataframe;

mediamarkt[,48]

[1]  7126  4012  3711  3237  3432  2671  2861  7065  3158  4023  4770  3861
[13]  4108  7408  9071  3596  3889  4093  4446  6059  8345 10291  5546  5129
[25]  4683  4670  5694  8619 11047  5743  5775  5216  5283  4854  7871  9944
[37]  3797  3821  3834  3999  4577  8898 11396  4508  5459  3668  3885  4021
[49]  7491  8831  3513  3606  3332  3189  3656  6859  9167  3306  3305  3379
[61]  3507  3912  6562  8245  3420  3445  3530  3404  3847  7187  9128  3623
[73]  3581  3401  2784  3024  6342  7835  2766  2718  2578  2591  2737  5479
[85]  7064  2528  2550  2287  1893  1846

First of all I have tried to get value of outliers with this codes:

boxplot(mediamarkt[,48])$out  and  I get 2 outliers;

[1] 11047 11396

Everything is okey so far but when I need to get indices of outliers with these code below:

which(mediamarkt[,48] %in% boxplot_mediamarkt$out)

[1]  5 18 29 43 59

I get more than 2 outliers, it does not match these results

What is wrong with my codes

Could anyone help me about solve my problem?

Body:
@G5W has asked a question that remains open. This code shows how to do easy input for your data and suggests that your boxplot_mediamarkt is not the output of boxplot or boxplot.stats from your data.

 dat <- scan()
1:   7126  4012  3711  3237  3432  2671  2861  7065  3158  4023  4770  3861
13:  4108  7408  9071  3596  3889  4093  4446  6059  8345 10291  5546  5129
25:  4683  4670  5694  8619 11047  5743  5775  5216  5283  4854  7871  9944
37:  3797  3821  3834  3999  4577  8898 11396  4508  5459  3668  3885  4021
49:  7491  8831  3513  3606  3332  3189  3656  6859  9167  3306  3305  3379
61:  3507  3912  6562  8245  3420  3445  3530  3404  3847  7187  9128  3623
73:  3581  3401  2784  3024  6342  7835  2766  2718  2578  2591  2737  5479
85:  7064  2528  2550  2287  1893  1846
91:
Read 90 items
> boxplot(dat)$out
[1] 11047 11396
> which(dat %in% boxplot(dat)$out)
[1] 29 43


问:
php not getting back to line in file
well, here is my PHP code:

```<code> $file = fopen("mon_fichier.txt","a+");
    fputs($file, "\n");
    fputs($file, "kodsi");
    fputs($file, "\n");
    fclose($file);
</code>```

then I go the file to see that there was no getting back to line: the \n is not working.

答:
You should have a look at what are line endings depending on OS
https://en.wikipedia.org/wiki/Newline

In fact, you would have to replace your \n by \r\n

Title: php not getting back to line in file

Body:
well, here is my PHP code:

 $file = fopen("mon_fichier.txt","a+");
    fputs($file, "\n");
    fputs($file, "kodsi");
    fputs($file, "\n");
    fclose($file);

then I go the file to see that there was no getting back to line: the \n is not working.


问:
shouldperformSegueWithIdentifier does not work properly
I am trying to understand how "shouldperformSegueWithIdentifier".
in the storyBoard, I created three scenes "scene1, scene2,scene3". Scene1 is linked to scene2 via a segue called "scene1To2", scene2 is linked to scene3 via a segue called "scene2To3" and scene3 is linked to scene1 via a segue called "scene3To1".

As shown in the code below, I called "shouldPerformSegueWithIdentifier" and it returned NO if the segue's identifier is "scene3To1".

At run time, I expected when I try to transit from scene3 to scene1 via "scene3To1", the transition will not occur, but it occurred normally…so what is the purpose of "shouldperformSegueWithIdentifier"

code:

```<code>#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a
 nib.
 }

 - (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
 }

 - (IBAction)from1To2:(id)sender {
    NSLog(@"in 1st scene");

       [self performSegueWithIdentifier:@"scene1To2" sender:self];
  }

   - (IBAction)from2To3:(id)sender {
    NSLog(@"in 2nd scene");

    [self performSegueWithIdentifier:@"scene2To3" sender:self];
    }

   - (IBAction)from3To1:(id)sender {
   [self performSegueWithIdentifier:@"scene3To1" sender:self];

   NSLog(@"in 3rd scene");
  }

  -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  {
    NSLog(@"prepareForSegue");

     if ([segue.identifier isEqualToString:@"scene1To2"])
      {
      NSLog(@"transiting from scene1To2");

     } else if ([segue.identifier isEqualToString:@"scene2To3"])
     {
     NSLog(@"transiting from scene2To3");

     } else if ([segue.identifier isEqualToString:@"scene3To1"])

    {
    NSLog(@"transition from scene 3 back to scene 1");
    }

    }

  -(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier
   sender:(id)sender
   {
   NSLog(@"shouldPerformSegueWithIdentifier");

   if ([identifier isEqualToString:@"scene3To1"])
   {
    return NO;
    }

  return YES;
   }

  @end
</code>```

output:

```<code>2017-06-06 16:02:07.301 UnwindSegue-1[699:19450] in 1st scene
2017-06-06 16:02:07.315 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:07.316 UnwindSegue-1[699:19450] transiting from
scene1To2
2017-06-06 16:02:07.320 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier
2017-06-06 16:02:08.245 UnwindSegue-1[699:19450] in 2nd scene

2017-06-06 16:02:08.260 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:08.260 UnwindSegue-1[699:19450] transiting from
scene2To3

2017-06-06 16:02:08.265 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier
2017-06-06 16:02:09.165 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:09.165 UnwindSegue-1[699:19450] transition from
scene 3 back to scene 1
2017-06-06 16:02:09.167 UnwindSegue-1[699:19450] in 3rd scene
2017-06-06 16:02:09.167 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier
</code>```

*StoryBoard**:

答:
The issue is that you have your Segue connected to a button, but you also have an IBAction connected to that button... and in your IBAction code you are manually calling performSegueWithIdentifier for that same Segue.

To create a Segue that you want to call manually, instead of ctrl-dragging from the button, ctrl-drag from the Controller icon:

Now, instead of using shouldPerformSegueWithIdentifier to determine whether or not to proceed, you can put that logic inside your IBAction method.

Body:
I am trying to understand how "shouldperformSegueWithIdentifier".
in the storyBoard, I created three scenes "scene1, scene2,scene3". Scene1 is linked to scene2 via a segue called "scene1To2", scene2 is linked to scene3 via a segue called "scene2To3" and scene3 is linked to scene1 via a segue called "scene3To1".

As shown in the code below, I called "shouldPerformSegueWithIdentifier" and it returned NO if the segue's identifier is "scene3To1".

At run time, I expected when I try to transit from scene3 to scene1 via "scene3To1", the transition will not occur, but it occurred normally…so what is the purpose of "shouldperformSegueWithIdentifier"

code:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a
 nib.
 }

 - (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
 }

 - (IBAction)from1To2:(id)sender {
    NSLog(@"in 1st scene");

       [self performSegueWithIdentifier:@"scene1To2" sender:self];
  }

   - (IBAction)from2To3:(id)sender {
    NSLog(@"in 2nd scene");

    [self performSegueWithIdentifier:@"scene2To3" sender:self];
    }

   - (IBAction)from3To1:(id)sender {
   [self performSegueWithIdentifier:@"scene3To1" sender:self];

   NSLog(@"in 3rd scene");
  }

  -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  {
    NSLog(@"prepareForSegue");

     if ([segue.identifier isEqualToString:@"scene1To2"])
      {
      NSLog(@"transiting from scene1To2");

     } else if ([segue.identifier isEqualToString:@"scene2To3"])
     {
     NSLog(@"transiting from scene2To3");

     } else if ([segue.identifier isEqualToString:@"scene3To1"])

    {
    NSLog(@"transition from scene 3 back to scene 1");
    }

    }

  -(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier
   sender:(id)sender
   {
   NSLog(@"shouldPerformSegueWithIdentifier");

   if ([identifier isEqualToString:@"scene3To1"])
   {
    return NO;
    }

  return YES;
   }

  @end

output:

2017-06-06 16:02:07.301 UnwindSegue-1[699:19450] in 1st scene
2017-06-06 16:02:07.315 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:07.316 UnwindSegue-1[699:19450] transiting from
scene1To2
2017-06-06 16:02:07.320 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier
2017-06-06 16:02:08.245 UnwindSegue-1[699:19450] in 2nd scene

2017-06-06 16:02:08.260 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:08.260 UnwindSegue-1[699:19450] transiting from
scene2To3

2017-06-06 16:02:08.265 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier
2017-06-06 16:02:09.165 UnwindSegue-1[699:19450] prepareForSegue
2017-06-06 16:02:09.165 UnwindSegue-1[699:19450] transition from
scene 3 back to scene 1
2017-06-06 16:02:09.167 UnwindSegue-1[699:19450] in 3rd scene
2017-06-06 16:02:09.167 UnwindSegue-1[699:19450]
shouldPerformSegueWithIdentifier

*StoryBoard**:


问:
How to collect a Observable<ResultSet> to Map
I'm trying to collect a Observable<ResultSet> from Vertex AsyncSqlClient
to HashMap.

```<code>Map<String, Integer> map = Maps.newHashMap();
asyncSQLClient
        .getConnectionObservable()
        .flatMap(sqlConnection -> sqlConnection.queryObservable("select a, b from table")
                .doOnCompleted(sqlConnection::close)
                .doOnError(throwable -> log.error("Error while querying.", throwable)))
        .flatMap(resultSet -> Observable.from(resultSet.getRows()))
        .toBlocking()
        .forEach(row -> map.put(row.getString("a"), row.getInteger("b")));
</code>```

but this seems to block forever.

After searching a while without any result, would you mind lending me a hand?

答:
as @Phoenix Wang commented, the forEach() method will block until Observable will completes.  meaning it will block forever if you have Observable that emit infinite items or you have an Observable that incorrectly do not emit onCompleted to signal Observable complete.

That might caused by your getConnectionObservable() method implementation, if it's creates a custom Observable, using Observable.create() for instance, you must call onCompleted() after all items were emitted.

Anyhow, you should be aware that toBlocking() will block and wait, that might not be appropriate with production code (as it's breaking all the purpose of reactiveness), you can achieve the same purpose using reduce():

```<code> asyncSQLClient
            .getConnectionObservable()
            .flatMap(sqlConnection -> sqlConnection.queryObservable("select a, b from table")
                    .doOnCompleted(sqlConnection::close)
                    .doOnError(throwable -> log.error("Error while querying.", throwable)))
            .flatMap(resultSet -> Observable.from(resultSet.getRows()))
            .reduce(Maps.newHashMap(), (map, o) -> map.put(row.getString("a"), row.getInteger("b")))
            .subscribe(map -> {
                        //do something with map
                    }
            );
</code>```

note, you still need to solve the onCompleted issue as reduce will also expect Observable completion and will emit signal item when source Observable completes.

Additional option is to use scan() (just replacing reduce with scan), with scan you will get emission for each item emitted with source Observable, meaning you will accumulate items to map over time.

Body:
I'm trying to collect a Observable<ResultSet> from Vertex AsyncSqlClient
to HashMap.

Map<String, Integer> map = Maps.newHashMap();
asyncSQLClient
        .getConnectionObservable()
        .flatMap(sqlConnection -> sqlConnection.queryObservable("select a, b from table")
                .doOnCompleted(sqlConnection::close)
                .doOnError(throwable -> log.error("Error while querying.", throwable)))
        .flatMap(resultSet -> Observable.from(resultSet.getRows()))
        .toBlocking()
        .forEach(row -> map.put(row.getString("a"), row.getInteger("b")));

but this seems to block forever.

After searching a while without any result, would you mind lending me a hand?

Body:
as @Phoenix Wang commented, the forEach() method will block until Observable will completes.  meaning it will block forever if you have Observable that emit infinite items or you have an Observable that incorrectly do not emit onCompleted to signal Observable complete.

That might caused by your getConnectionObservable() method implementation, if it's creates a custom Observable, using Observable.create() for instance, you must call onCompleted() after all items were emitted.

Anyhow, you should be aware that toBlocking() will block and wait, that might not be appropriate with production code (as it's breaking all the purpose of reactiveness), you can achieve the same purpose using reduce():

 asyncSQLClient
            .getConnectionObservable()
            .flatMap(sqlConnection -> sqlConnection.queryObservable("select a, b from table")
                    .doOnCompleted(sqlConnection::close)
                    .doOnError(throwable -> log.error("Error while querying.", throwable)))
            .flatMap(resultSet -> Observable.from(resultSet.getRows()))
            .reduce(Maps.newHashMap(), (map, o) -> map.put(row.getString("a"), row.getInteger("b")))
            .subscribe(map -> {
                        //do something with map
                    }
            );

note, you still need to solve the onCompleted issue as reduce will also expect Observable completion and will emit signal item when source Observable completes.

Additional option is to use scan() (just replacing reduce with scan), with scan you will get emission for each item emitted with source Observable, meaning you will accumulate items to map over time.


问:
How to programmatically trigger document generation in EA
Is it possible to trigger a Document generation programmatically in EA similar to HTML generation?

Is there any way to do like below "RunHTMLReport" for document generation?

"RunHTMLReport(PackageGUID,ExportPath ,ImageFormat,Style,Extension)"

答:
As Thomas said, you can use Repository.CreateDocumentGenerator. However, this is a whole facility for generating a report (the best way to describe it would be like if you are doing virtual documents, but in code).

This is really used to define a report template from model fragments.
Here's the documentation on using the Document Generator

To run a report on an already defined template, use Project.RunReport. You can find the documentation here.

You get your Project object with Repository.GetProjectInterface


问:
How select only all first child of another div
Suppose to have this html code:

```<code><div class="colora_riga">
     <!--only this div-->
     <div>
         <div>...</div>
     </div>
     <!--only this div-->
     <div>
        <div>...</div>
     </div>
</div>
</code>```

I want take the all only first child directly of div with colora_riga like class. I dont' want the div another div. This is my css:

```<code>.colora_riga > div:first-child {
    border:1px ridge #999999;
}
</code>```

This rule works only for the first child of div with "colora-riga" like class, for the second directly child the rule is not applied. Anyone can help me?

答:
If I understood you correctly, you want every div directly under .colora_riga, you don't need :first-child then :

```<code>.colora_riga > div {
    border:1px ridge #999999;
}
</code>```

Body:
Suppose to have this html code:

...

...

I want take the all only first child directly of div with colora_riga like class. I dont' want the div another div. This is my css:

.colora_riga > div:first-child {
    border:1px ridge #999999;
}

This rule works only for the first child of div with "colora-riga" like class, for the second directly child the rule is not applied. Anyone can help me?

Body:
If I understood you correctly, you want every div directly under .colora_riga, you don't need :first-child then :

.colora_riga > div {
    border:1px ridge #999999;
}


问:
How to write a policy for a bucket in cloud template
I have prepared a cloud template that creates AWS::IAM::Role with arn:aws:iam::aws:policy/AmazonS3FullAccess policy.

After the template runs successfully, I execute a python script to create two buckets with prefix foobar-bucket1 and foobar-bucket2.

At the moment this is how the above section of my template looks:

```<code>Resources:
  MyRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ssm.amazonaws.com
            - ec2.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/AmazonS3FullAccess
      Path: "/"
</code>```

Question

I am wondering if there is a need for the IAM::Role created via cloud template to have AmazonS3FullAccess in order to create the two buckets?

Is it possible for me to give the role ONLY permission to create buckets and then FULLS3 permission ONLY on the buckets with prefix foobar-bucket1 and foobar-bucket2.

答:
As long as the bucket name is dynamic you cannot create a policy within you cloudformation template with the correct name in it.

In descending order of practicality:

option 1: Create the bucket within your cloudformation template and then create the IAM role accordingly within that same template (see sample below).

```<code>AWSTemplateFormatVersion: '2010-09-09'
Resources:
  foobarBucket1:
    Type: AWS::S3::Bucket
  foobarBucket2:
    Type: AWS::S3::Bucket
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: LambdaRolePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket1 ]]
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket2 ]]
</code>```

option 2: Another possibility could be that you incorporate your fixed prefix into a policy and therefore partially restrict access.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::foobarbucket1-*",
            "Effect": "Allow"
        }
    ]
}
</code>```

option 3: use the bucket name as cloudformation parameter and update the existing template with the newly created name.

Body:
I have prepared a cloud template that creates AWS::IAM::Role with arn:aws:iam::aws:policy/AmazonS3FullAccess policy.

After the template runs successfully, I execute a python script to create two buckets with prefix foobar-bucket1 and foobar-bucket2.

At the moment this is how the above section of my template looks:

Resources:
  MyRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ssm.amazonaws.com
            - ec2.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/AmazonS3FullAccess
      Path: "/"

Question

I am wondering if there is a need for the IAM::Role created via cloud template to have AmazonS3FullAccess in order to create the two buckets?

Is it possible for me to give the role ONLY permission to create buckets and then FULLS3 permission ONLY on the buckets with prefix foobar-bucket1 and foobar-bucket2.

Body:
As long as the bucket name is dynamic you cannot create a policy within you cloudformation template with the correct name in it.

In descending order of practicality:

option 1: Create the bucket within your cloudformation template and then create the IAM role accordingly within that same template (see sample below).

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  foobarBucket1:
    Type: AWS::S3::Bucket
  foobarBucket2:
    Type: AWS::S3::Bucket
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: LambdaRolePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket1 ]]
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket2 ]]

option 2: Another possibility could be that you incorporate your fixed prefix into a policy and therefore partially restrict access.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::foobarbucket1-*",
            "Effect": "Allow"
        }
    ]
}

option 3: use the bucket name as cloudformation parameter and update the existing template with the newly created name.


问:
Time series aggregation efficiency
I commonly need to summarize a time series with irregular timing with a given aggregation function (i.e., sum, average, etc.). However, the current solution that I have seems inefficient and slow.

Take the aggregation function:

```<code>function aggArray = aggregate(array, groupIndex, collapseFn)

groups = unique(groupIndex, 'rows');
aggArray = nan(size(groups, 1), size(array, 2));

for iGr = 1:size(groups,1)
    grIdx = all(groupIndex == repmat(groups(iGr,:), [size(groupIndex,1), 1]), 2);
    for iSer = 1:size(array, 2)
      aggArray(iGr,iSer) = collapseFn(array(grIdx,iSer));
    end
end

end
</code>```

Note that both array and groupIndex can be 2D. Every column in array is an independent series to be aggregated, but the columns of groupIndex should be taken together (as a row) to specify a period.

Then when we bring an irregular time series to it (note the second period is one base period longer), the timing results are poor:

```<code>a = rand(20006,10);
b = transpose([ones(1,5) 2*ones(1,6) sort(repmat((3:4001), [1 5]))]);

tic; aggregate(a, b, @sum); toc
Elapsed time is 1.370001 seconds.
</code>```

Using the profiler, we can find out that the grpIdx line takes about 1/4 of the execution time (.28 s) and the iSer loop takes about 3/4 (1.17 s) of the total (1.48 s).

Compare this with the period-indifferent case:

```<code>tic; cumsum(a); toc
Elapsed time is 0.000930 seconds.
</code>```

Is there a more efficient way to aggregate this data?

Timing Results

Taking each response and putting it in a separate function, here are the timing results I get with timeit with Matlab 2015b on Windows 7 with an Intel i7:

```<code>    original | 1.32451
      felix1 | 0.35446
      felix2 | 0.16432
    divakar1 | 0.41905
    divakar2 | 0.30509
    divakar3 | 0.16738
matthewGunn1 | 0.02678
matthewGunn2 | 0.01977
</code>```

Clarification on groupIndex

An example of a 2D groupIndex would be where both the year number and week number are specified for a set of daily data covering 1980-2015:

```<code>a2 = rand(36*52*5, 10);
b2 = [sort(repmat(1980:2015, [1 52*5]))' repmat(1:52, [1 36*5])'];
</code>```

Thus a "year-week" period are uniquely identified by a row of groupIndex. This is effectively handled through calling unique(groupIndex, 'rows') and taking the third output, so feel free to disregard this portion of the question.

答:
A little late to the party, but a single loop using accumarray makes a huge difference:

```<code>function aggArray = aggregate_gnovice(array, groupIndex, collapseFn)

  [groups, ~, index] = unique(groupIndex, 'rows');
  numCols = size(array, 2);
  aggArray = nan(numel(groups), numCols);
  for col = 1:numCols
    aggArray(:, col) = accumarray(index, array(:, col), [], collapseFn);
  end

end
</code>```

Timing this using timeit in MATLAB R2016b for the sample data in the question gives the following:

```<code>original | 1.127141
 gnovice | 0.002205
</code>```

Over a 500x speedup!

Title: Time series aggregation efficiency

Body:
I commonly need to summarize a time series with irregular timing with a given aggregation function (i.e., sum, average, etc.). However, the current solution that I have seems inefficient and slow.

Take the aggregation function:

function aggArray = aggregate(array, groupIndex, collapseFn)

groups = unique(groupIndex, 'rows');
aggArray = nan(size(groups, 1), size(array, 2));

for iGr = 1:size(groups,1)
    grIdx = all(groupIndex == repmat(groups(iGr,:), [size(groupIndex,1), 1]), 2);
    for iSer = 1:size(array, 2)
      aggArray(iGr,iSer) = collapseFn(array(grIdx,iSer));
    end
end

end

Note that both array and groupIndex can be 2D. Every column in array is an independent series to be aggregated, but the columns of groupIndex should be taken together (as a row) to specify a period.

Then when we bring an irregular time series to it (note the second period is one base period longer), the timing results are poor:

a = rand(20006,10);
b = transpose([ones(1,5) 2*ones(1,6) sort(repmat((3:4001), [1 5]))]);

tic; aggregate(a, b, @sum); toc
Elapsed time is 1.370001 seconds.

Using the profiler, we can find out that the grpIdx line takes about 1/4 of the execution time (.28 s) and the iSer loop takes about 3/4 (1.17 s) of the total (1.48 s).

Compare this with the period-indifferent case:

tic; cumsum(a); toc
Elapsed time is 0.000930 seconds.

Is there a more efficient way to aggregate this data?

Timing Results

Taking each response and putting it in a separate function, here are the timing results I get with timeit with Matlab 2015b on Windows 7 with an Intel i7:

    original | 1.32451
      felix1 | 0.35446
      felix2 | 0.16432
    divakar1 | 0.41905
    divakar2 | 0.30509
    divakar3 | 0.16738
matthewGunn1 | 0.02678
matthewGunn2 | 0.01977

Clarification on groupIndex

An example of a 2D groupIndex would be where both the year number and week number are specified for a set of daily data covering 1980-2015:

a2 = rand(36*52*5, 10);
b2 = [sort(repmat(1980:2015, [1 52*5]))' repmat(1:52, [1 36*5])'];

Thus a "year-week" period are uniquely identified by a row of groupIndex. This is effectively handled through calling unique(groupIndex, 'rows') and taking the third output, so feel free to disregard this portion of the question.

Body:
A little late to the party, but a single loop using accumarray makes a huge difference:

function aggArray = aggregate_gnovice(array, groupIndex, collapseFn)

  [groups, ~, index] = unique(groupIndex, 'rows');
  numCols = size(array, 2);
  aggArray = nan(numel(groups), numCols);
  for col = 1:numCols
    aggArray(:, col) = accumarray(index, array(:, col), [], collapseFn);
  end

end

Timing this using timeit in MATLAB R2016b for the sample data in the question gives the following:

original | 1.127141
 gnovice | 0.002205

Over a 500x speedup!


问:
Why is it impossible to call static methods on Nullable<T> shorthands?
I thought T? is just a compiler shorthand for Nullable<T>. According to MSDN:

The syntax T? is shorthand for Nullable<T>, where T is a value type.
  The two forms are interchangeable.

However, there is a little (insignificant) difference: Visual Studio doesn't allow me to call static methods on shorthands:

```<code>bool b1 = Nullable<int>.Equals(1, 2); //no error
bool b2 = int?.Equals(1, 2); //syntax error "Invalid expression term 'int'"
</code>```

Why? Is there any reason for this limitation?

答:
While you're right about the syntax, the Equals method can be called from the default type using Nullable type as parameters.

You can try this unit test with whatever value you want :

```<code>int? i = 4;
int? j = null;
Assert.AreEqual(Nullable<int>.Equals(i, j), int.Equals(i, j));
</code>```

Body:
I thought T? is just a compiler shorthand for Nullable<T>. According to MSDN:

The syntax T? is shorthand for Nullable<T>, where T is a value type.
  The two forms are interchangeable.

However, there is a little (insignificant) difference: Visual Studio doesn't allow me to call static methods on shorthands:

bool b1 = Nullable<int>.Equals(1, 2); //no error
bool b2 = int?.Equals(1, 2); //syntax error "Invalid expression term 'int'"

Why? Is there any reason for this limitation?

Body:
While you're right about the syntax, the Equals method can be called from the default type using Nullable type as parameters.

You can try this unit test with whatever value you want :

int? i = 4;
int? j = null;
Assert.AreEqual(Nullable<int>.Equals(i, j), int.Equals(i, j));


问:
Twitter4j.Getting users from country
I am using twitter4j, but I have not found a solution to the API.
I need to get a list of users with specified country.

How can I do that?

答:
As of Twitter4J version 4.0.x there is no known method to query Twitter users via a given country parameter (on a global scale).

For reference, see the current Twitter4J API documentation, here and here:

Title: Twitter4j.Getting users from country


问:
404 Not Found: Requested route ('theo-larissa.mybluemix.net') does not exist
I am new in Bluemix. So far I created web app,got its code and run this app in localhost. Everything works good. The app uses AngularJs and json-server. Later on I will Node.js too. To run it I use 'json-server --watch db.json'. The json file contains various json arrays and objects. And this is my list of links.

```<code>http://localhost:3000/news
http://localhost:3000/events
http://localhost:3000/city
http://localhost:3000/administration
http://localhost:3000/deputy_mayors
http://localhost:3000/alcazar_park
http://localhost:3000/feedback
</code>```

My guess is that all those links should be changed to a live route instead of using localhost. In my dashboard I can see the name's app the route(theo-larissa.mybluemix.net) and it's state with is stopped. Now when I am trying to start the app,I get this message

404 Not Found: Requested route ('theo-larissa.mybluemix.net') does not exist.

Any ideas how to fix this?

Thanks in advance,

Theo.

答:
What do your console logs for theo-larissa.mybluemix.net show? One of the really common deployment mistakes is to leave the port hard-coded in your application when you deploy it to Bluemix. You can't do that; you have to allow Bluemix to specify the port your application will use. You would do that, for example, by encoding something like the following when you create the server: </p>

```<code>var server = app.listen(app.get('port'), function()
  {console.log('Listening on port %d', server.address().port);});
</code>```

<p>If you wanted to make this fully automated, you could include code like the following: </p>

```<code>app.set('port', appEnv.port);
app.set('appName', 'theo-larissa');

if (cfenv.getAppEnv().isLocal == true)
   {http.createServer(app).listen(app.get('port'),
     function(req, res) {console.log(app.get('appName')+' is listening locally on port: ' + app.get('port'));});
  }
  else
  {
    var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
  }
</code>```

Body:
I am new in Bluemix. So far I created web app,got its code and run this app in localhost. Everything works good. The app uses AngularJs and json-server. Later on I will Node.js too. To run it I use 'json-server --watch db.json'. The json file contains various json arrays and objects. And this is my list of links.

http://localhost:3000/news
http://localhost:3000/events
http://localhost:3000/city
http://localhost:3000/administration
http://localhost:3000/deputy_mayors
http://localhost:3000/alcazar_park
http://localhost:3000/feedback

My guess is that all those links should be changed to a live route instead of using localhost. In my dashboard I can see the name's app the route(theo-larissa.mybluemix.net) and it's state with is stopped. Now when I am trying to start the app,I get this message

404 Not Found: Requested route ('theo-larissa.mybluemix.net') does not exist.

Any ideas how to fix this?

Thanks in advance,

Theo.

Body:
What do your console logs for theo-larissa.mybluemix.net show? One of the really common deployment mistakes is to leave the port hard-coded in your application when you deploy it to Bluemix. You can't do that; you have to allow Bluemix to specify the port your application will use. You would do that, for example, by encoding something like the following when you create the server:

var server = app.listen(app.get('port'), function()
  {console.log('Listening on port %d', server.address().port);});

If you wanted to make this fully automated, you could include code like the following:

app.set('port', appEnv.port);
app.set('appName', 'theo-larissa');

if (cfenv.getAppEnv().isLocal == true)
   {http.createServer(app).listen(app.get('port'),
     function(req, res) {console.log(app.get('appName')+' is listening locally on port: ' + app.get('port'));});
  }
  else
  {
    var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
  }


问:
Cannot delete sqlite3 database file after closing connection
I am trying to delete a sqlite3 database file. After I close the connection and try to delete the file, I receive and error stating that the file is being used by another process. I've  been searching for an answer for a little while, but I feel like a lot of the solutions seem way more convoluted than should be necessary. This solution seems like exactly what I'm looking for, but I'm not sure what it means by "Once you have your Context". Here is my code:</p>

```<code>import sqlite3
import os.path

db = "data.db"
con = sqlite3.connect(db)
c = con.cursor()

c.execute('''CREATE TABLE my_table (a TEXT, b TEXT, c TEXT)''')
c.execute('''INSERT INTO my_table VALUES(?,?,?)''',("test1","test2","test3"))

con.close
os.remove(db)
</code>```

答: You are not really calling con.close (missing parentheses)

Body:
I am trying to delete a sqlite3 database file. After I close the connection and try to delete the file, I receive and error stating that the file is being used by another process. I've  been searching for an answer for a little while, but I feel like a lot of the solutions seem way more convoluted than should be necessary. This solution seems like exactly what I'm looking for, but I'm not sure what it means by "Once you have your Context". Here is my code:

import sqlite3
import os.path

db = "data.db"
con = sqlite3.connect(db)
c = con.cursor()

c.execute('''CREATE TABLE my_table (a TEXT, b TEXT, c TEXT)''')
c.execute('''INSERT INTO my_table VALUES(?,?,?)''',("test1","test2","test3"))

con.close
os.remove(db)


问:
Will DateTime.UtcNow return different values within the same method?
Say that I have a long loop of simple math in between two calls to DateTime.UtcNow in a single method.

Does DateTime.UtcNow return two different values inside the same method if the code in between took more than the system's timer resolution of, say, 10 milliseconds?

By extension, is it possible, if the code runs right at the moment that the date turns over into a new day, that DateTime.UtcNow.Date will result in two different dates inside the same method?

答: DateTime.UtcNow is not evaluated nor its value is captured at method start.  It is evaluated at the time when execution reaches it, and every time the execution reaches it.  So yes, if function takes long enough, you will get to different values between two executions.


答:
In one word: Yes.

If you want to have the same value you need to call this function before and store the value on a variable, then use this variable.

Title: Will DateTime.UtcNow return different values within the same method?

Body:
Say that I have a long loop of simple math in between two calls to DateTime.UtcNow in a single method.

Does DateTime.UtcNow return two different values inside the same method if the code in between took more than the system's timer resolution of, say, 10 milliseconds?

By extension, is it possible, if the code runs right at the moment that the date turns over into a new day, that DateTime.UtcNow.Date will result in two different dates inside the same method?


问:
Jira attach file to issue with PHP and CURL
I have found several examples on how to upload an attachment to an issue in jira, however I have not been able to make any of them work. I posted this question on the Jira Community Help Forums but it has been over a week with 0 replies so hoping the community here can help.

Here is my current attempt:

```<code> $Jirausername = 'myUsername';
    $Jirapassword = 'myPassword';

    $ch=curl_init();
$headers = array(
    'X-Atlassian-Token: nocheck',
    'Content-Type: multipart/form-data'
);
$data = array('file' => "testing.txt");

curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL=>'https://myCompany.net/rest/api/latest/issue/TAG-78/attachments',
        CURLOPT_POST=>true,
        CURLOPT_VERBOSE=>1,
        CURLOPT_POSTFIELDS=>$data,
        CURLOPT_SSL_VERIFYHOST=> 0,
        CURLOPT_SSL_VERIFYPEER=> 0,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HEADER=>false,
        CURLOPT_HTTPHEADER=> $headers,
        CURLOPT_USERPWD=>"$Jirausername:$Jirapassword"
    )
);
$result=curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
    echo "cURL Error: $ch_error";
} else {
    var_dump($result);
}
curl_close($ch);
</code>```

testing.txt is in the same directory as this file. I have curl installed on the webserver where this is hosted, can create issues in jira fine, just cant seem to upload attahcments...

When I run this page it displays:

```<code>string(0) ""
</code>```

No attachment is uploaded as well needless to say. Any ideas what I am doing wrong?

EDIT: Adding a bounty, here are some things I have tried:

trying both nocheck and no-check

trying both @testing.txt and testing.txt

removing 'Content-Type: multipart/form-data'

Full paths as such: $data = array('file'=>"@C:\xampp\htdocs\Website\testing.txt ,'filename'=>'testing.txt');

Tried like this too because of a known curl error: $data = array('file'=>"@C:\xampp\htdocs\Website\testing.txt" ';filename=testing.txt');

And every combination of those above. No matter what I try it does not work though. Have also ensured I am an admin level user in Jira. I feel like my code should work... but clearly not.

答:
My initial assumption was wrong: it works with both no-check and nocheck -- it doesn't matter.

Instead of putting a file name as a parameter for file, you have first create a curl file object like this:

```<code>$cfile = curl_file_create('testing.txt');
</code>```

And then put it into array:

```<code>$data = array('file' => $cfile);
</code>```

Here is the full solution, which worked for me:

```<code><?php
 $Jirausername = '<username>';
 $Jirapassword = '<password>';

$ch=curl_init();
$headers = array(
    'X-Atlassian-Token: nocheck',
    'Content-Type: multipart/form-data'
);

$cfile = curl_file_create('testing.txt');
$data = array('file' => $cfile);

curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL=>'https://<JIRA-SERVER>/rest/api/latest/issue/<ISSUE-KEY>/attachments',
        CURLOPT_POST=>true,
        CURLOPT_VERBOSE=>1,
        CURLOPT_POSTFIELDS=>$data,
        CURLOPT_INFILESIZE => 5,
        CURLOPT_SSL_VERIFYHOST=> 0,
        CURLOPT_SSL_VERIFYPEER=> 0,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HEADER=>true,
        CURLOPT_HTTPHEADER=> $headers,
        CURLOPT_USERPWD=>"$Jirausername:$Jirapassword"
    )
);
$result=curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
    echo "cURL Error: $ch_error";
} else {
    var_dump($result);
}
curl_close($ch);
?>
</code>```

Body:
I have found several examples on how to upload an attachment to an issue in jira, however I have not been able to make any of them work. I posted this question on the Jira Community Help Forums but it has been over a week with 0 replies so hoping the community here can help.

Here is my current attempt:

 $Jirausername = 'myUsername';
    $Jirapassword = 'myPassword';

    $ch=curl_init();
$headers = array(
    'X-Atlassian-Token: nocheck',
    'Content-Type: multipart/form-data'
);
$data = array('file' => "testing.txt");

curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL=>'https://myCompany.net/rest/api/latest/issue/TAG-78/attachments',
        CURLOPT_POST=>true,
        CURLOPT_VERBOSE=>1,
        CURLOPT_POSTFIELDS=>$data,
        CURLOPT_SSL_VERIFYHOST=> 0,
        CURLOPT_SSL_VERIFYPEER=> 0,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HEADER=>false,
        CURLOPT_HTTPHEADER=> $headers,
        CURLOPT_USERPWD=>"$Jirausername:$Jirapassword"
    )
);
$result=curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
    echo "cURL Error: $ch_error";
} else {
    var_dump($result);
}
curl_close($ch);

testing.txt is in the same directory as this file. I have curl installed on the webserver where this is hosted, can create issues in jira fine, just cant seem to upload attahcments...

When I run this page it displays:

string(0) ""

No attachment is uploaded as well needless to say. Any ideas what I am doing wrong?

EDIT: Adding a bounty, here are some things I have tried:

trying both nocheck and no-check

trying both @testing.txt and testing.txt

removing 'Content-Type: multipart/form-data'

Full paths as such: $data = array('file'=>"@C:\xampp\htdocs\Website\testing.txt ,'filename'=>'testing.txt');

Tried like this too because of a known curl error: $data = array('file'=>"@C:\xampp\htdocs\Website\testing.txt" ';filename=testing.txt');

And every combination of those above. No matter what I try it does not work though. Have also ensured I am an admin level user in Jira. I feel like my code should work... but clearly not.

Body:
My initial assumption was wrong: it works with both no-check and nocheck -- it doesn't matter.

Instead of putting a file name as a parameter for file, you have first create a curl file object like this:

$cfile = curl_file_create('testing.txt');

And then put it into array:

$data = array('file' => $cfile);

Here is the full solution, which worked for me:

<?php
 $Jirausername = '<username>';
 $Jirapassword = '<password>';

$ch=curl_init();
$headers = array(
    'X-Atlassian-Token: nocheck',
    'Content-Type: multipart/form-data'
);

$cfile = curl_file_create('testing.txt');
$data = array('file' => $cfile);

curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL=>'https://<JIRA-SERVER>/rest/api/latest/issue/<ISSUE-KEY>/attachments',
        CURLOPT_POST=>true,
        CURLOPT_VERBOSE=>1,
        CURLOPT_POSTFIELDS=>$data,
        CURLOPT_INFILESIZE => 5,
        CURLOPT_SSL_VERIFYHOST=> 0,
        CURLOPT_SSL_VERIFYPEER=> 0,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HEADER=>true,
        CURLOPT_HTTPHEADER=> $headers,
        CURLOPT_USERPWD=>"$Jirausername:$Jirapassword"
    )
);
$result=curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
    echo "cURL Error: $ch_error";
} else {
    var_dump($result);
}
curl_close($ch);
?>


答:
Start with df1:

```<code>df1.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 4 entries, 2016-05-13 to 2016-05-18
Data columns (total 7 columns):
Stock        4 non-null object
Open         4 non-null float64
High         4 non-null float64
Low          4 non-null float64
Close        4 non-null float64
Adj Close    4 non-null float64
Volume       4 non-null int64
dtypes: float64(5), int64(1), object(1)
memory usage: 256.0+ bytes

print(df1)

           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2016-05-18   AAD  5.20  5.25  5.20   5.25       5.25    3000
</code>```

today appears to be a series with one row datatype datetime.

```<code>today
Out[36]:
0   2017-06-05
dtype: datetime64[ns]
</code>```

Let's replace last index with first row of today:

```<code>df2 = df1.rename({df1.index[-1]: today.iloc[0]})
print(df2)

           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2017-06-05   AAD  5.20  5.25  5.20   5.25       5.25    3000
</code>```

Title: Python: How to change a date in pandas which set as index

Body:
I need to set the last date to today date. Example: 2016-05-18 to 2017-06-05.
However when I do df.index[-1] = today, it return this error
TypeError: Index does not support mutable operations

>>> today
0   2017-06-05
Name: trading_day, dtype: datetime64[ns]

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2016-05-18   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

>>> df.index[-1] = today
TypeError: Index does not support mutable operations

What I needed is

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2017-06-05   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

Only the last date is change.

Body:
Start with df1:

df1.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 4 entries, 2016-05-13 to 2016-05-18
Data columns (total 7 columns):
Stock        4 non-null object
Open         4 non-null float64
High         4 non-null float64
Low          4 non-null float64
Close        4 non-null float64
Adj Close    4 non-null float64
Volume       4 non-null int64
dtypes: float64(5), int64(1), object(1)
memory usage: 256.0+ bytes

print(df1)

           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2016-05-18   AAD  5.20  5.25  5.20   5.25       5.25    3000

today appears to be a series with one row datatype datetime.

today
Out[36]:
0   2017-06-05
dtype: datetime64[ns]

Let's replace last index with first row of today:

df2 = df1.rename({df1.index[-1]: today.iloc[0]})
print(df2)

           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2017-06-05   AAD  5.20  5.25  5.20   5.25       5.25    3000