问:
How to add an extra assert after the test methods run using python unittest?
I have 92 tests and I want to make sure that no silent errors occurred during the calls.
Unfortunately error handing in OpenGL is not quite good. I want to test if glGetError() returns other then GL_NO_ERROR It is enough if I test it once per TestCase. It would be better if I could add an assert after every test methods. (I don't want to add it manually in 92 methods)

I made an example snippet that shows a solution that is not acceptable since the assert is done in the tearDownClass(cls) method and tearDownClass should not do any testing logic.

How can I add an extra assert after my tests?

The lines with comments show what I wan't to achieve.

```<code>import struct
import unittest

import ModernGL

class TestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

    @classmethod
    def tearDownClass(cls):
        error = cls.ctx.error                   # Store error in a variable
        cls.ctx.release()                       # Then release the context
        cls.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release

    def test_1(self):
        ...

    def test_2(self):
        ...

    def test_3(self):
        ...

if __name__ == '__main__':
    unittest.main()
</code>```

NOTE:

cls.ctx.error is a property (glGetError() as a string) and the possible values are:

```<code>"GL_NO_ERROR"
"GL_INVALID_ENUM"
"GL_INVALID_VALUE"
"GL_INVALID_OPERATION"
"GL_INVALID_FRAMEBUFFER_OPERATION"
"GL_OUT_OF_MEMORY"
"GL_STACK_UNDERFLOW"
"GL_STACK_OVERFLOW"
"GL_UNKNOWN_ERROR"
</code>```

答:
You could do the test in the tearDown (as opposed to tearDownClass) method, as this is a regular instance method:</p>

```<code>class TestCase(unittest.TestCase):

    def setUp(self):
        self.ctx = ModernGL.create_standalone_context()

    def tearDown(self):
        error = self.ctx.error                   # Store error in a variable
        self.ctx.release()                       # Then release the context
        self.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release
</code>```

Body:
I have 92 tests and I want to make sure that no silent errors occurred during the calls.
Unfortunately error handing in OpenGL is not quite good. I want to test if glGetError() returns other then GL_NO_ERROR It is enough if I test it once per TestCase. It would be better if I could add an assert after every test methods. (I don't want to add it manually in 92 methods)

I made an example snippet that shows a solution that is not acceptable since the assert is done in the tearDownClass(cls) method and tearDownClass should not do any testing logic.

How can I add an extra assert after my tests?

The lines with comments show what I wan't to achieve.

import struct
import unittest

import ModernGL

class TestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

    @classmethod
    def tearDownClass(cls):
        error = cls.ctx.error                   # Store error in a variable
        cls.ctx.release()                       # Then release the context
        cls.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release

    def test_1(self):
        ...

    def test_2(self):
        ...

    def test_3(self):
        ...

if __name__ == '__main__':
    unittest.main()

NOTE:

cls.ctx.error is a property (glGetError() as a string) and the possible values are:

"GL_NO_ERROR"
"GL_INVALID_ENUM"
"GL_INVALID_VALUE"
"GL_INVALID_OPERATION"
"GL_INVALID_FRAMEBUFFER_OPERATION"
"GL_OUT_OF_MEMORY"
"GL_STACK_UNDERFLOW"
"GL_STACK_OVERFLOW"
"GL_UNKNOWN_ERROR"

Body:
You could do the test in the tearDown (as opposed to tearDownClass) method, as this is a regular instance method:

class TestCase(unittest.TestCase):

    def setUp(self):
        self.ctx = ModernGL.create_standalone_context()

    def tearDown(self):
        error = self.ctx.error                   # Store error in a variable
        self.ctx.release()                       # Then release the context
        self.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release


来源: stackexchange

问:
Djangocms users don't have permission to add or edit plugins
I have a website, currently running with Django==1.8.6 and Django-CMS 3.0.x (running through upgrades at the moment).

My users can not edit any of the frontend plugins. At the moment I am sure that this is not only true for my custom made plugins, but for ones that come with Django-CMS as well. As a test I have made a new User with all rights and staff status (no superuser). But also this user can't edit or add plugins.

For my search I have found this: https://github.com/divio/djangocms-text-ckeditor/issues/78

I also tested the solution given there as I am using ckeditor, but I don't have an entry for text, so this:

```<code> sqlite3> select * from django_content_type where app_label = 'text';
 id | name | app_label | model
 ----+------+-----------+-------
 23 | text | text      | text
</code>```

For results to

```<code> sqlite3> select * from django_content_type where app_label = 'text';
 sqlite3>
</code>```

I tried to figure out how to debug permission errors. I have also looked through auth_permission, but everything seems to be alright. Is there anyway to debug the permission process in order to find whats preventing my users from using the frontend editing?

Update

My current installed packages:

```<code>Django==1.8.6
Django-Select2==4.3.1
Pillow==3.0.0
South==1.0.2
Unidecode==0.04.18
YURL==0.13
aldryn-apphooks-config==0.2.6
aldryn-boilerplates==0.7.3
aldryn-categories==1.0.1
aldryn-common==1.0.0
aldryn-newsblog==1.0.9
aldryn-people==1.1.2
aldryn-reversion==1.0.1
aldryn-translation-tools==0.2.1
argparse==1.4.0
backport-collections==0.1
cmsplugin-filer==1.0.0
dj-database-url==0.3.0
django-admin-sortable==1.8.4
django-appconf==1.0.1
django-appdata==0.1.4
django-autoslug==1.8.0
django-ckeditor-filebrowser-filer==0.1.1
django-classy-tags==0.6.2
django-cms==3.1.3
django-durationfield==0.5.2
django-easy-select2==1.3
django-filer==1.0.2
django-mptt==0.7.4
django-parler==1.5.1
django-phonenumber-field==0.7.2
django-polymorphic==0.7.2
django-reversion==1.8.7
django-sekizai==0.8.2
django-sortedm2m==1.3.2
django-taggit==0.17.3
django-treebeard==3.0
djangocms-admin-style==1.0.5
djangocms-column==1.5
djangocms-file==0.1
djangocms-flash==0.2.0
djangocms-googlemap==0.3
djangocms-inherit==0.1
djangocms-installer==0.7.9
djangocms-link==1.6.2
djangocms-picture==0.1
djangocms-style==1.5
djangocms-teaser==0.1
djangocms-text-ckeditor==2.7.0
djangocms-video==0.1
easy-thumbnails==2.2.1
gunicorn==19.4.3
html5lib==0.9999999
lxml==3.5.0
phonenumbers==7.1.1
python-dateutil==2.4.2
python-slugify==1.1.4
pytz==2015.7
simplejson==3.8.0
six==1.10.0
tzlocal==1.2
vobject==0.6.6
wheel==0.24.0
wsgiref==0.1.2
</code>```

答: The answer is after some debugging the permissions.py of the cms, that my sitepermissions where not set properly in the database. Resetting thos in the backend solved the problem.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a website, currently running with Django==1.8.6 and Django-CMS 3.0.x (running through upgrades at the moment).

My users can not edit any of the frontend plugins. At the moment I am sure that this is not only true for my custom made plugins, but for ones that come with Django-CMS as well. As a test I have made a new User with all rights and staff status (no superuser). But also this user can't edit or add plugins.

For my search I have found this: https://github.com/divio/djangocms-text-ckeditor/issues/78

I also tested the solution given there as I am using ckeditor, but I don't have an entry for text, so this:

 sqlite3> select * from django_content_type where app_label = 'text';
 id | name | app_label | model
 ----+------+-----------+-------
 23 | text | text      | text

For results to

 sqlite3> select * from django_content_type where app_label = 'text';
 sqlite3>

I tried to figure out how to debug permission errors. I have also looked through auth_permission, but everything seems to be alright. Is there anyway to debug the permission process in order to find whats preventing my users from using the frontend editing?

Update

My current installed packages:

Django==1.8.6
Django-Select2==4.3.1
Pillow==3.0.0
South==1.0.2
Unidecode==0.04.18
YURL==0.13
aldryn-apphooks-config==0.2.6
aldryn-boilerplates==0.7.3
aldryn-categories==1.0.1
aldryn-common==1.0.0
aldryn-newsblog==1.0.9
aldryn-people==1.1.2
aldryn-reversion==1.0.1
aldryn-translation-tools==0.2.1
argparse==1.4.0
backport-collections==0.1
cmsplugin-filer==1.0.0
dj-database-url==0.3.0
django-admin-sortable==1.8.4
django-appconf==1.0.1
django-appdata==0.1.4
django-autoslug==1.8.0
django-ckeditor-filebrowser-filer==0.1.1
django-classy-tags==0.6.2
django-cms==3.1.3
django-durationfield==0.5.2
django-easy-select2==1.3
django-filer==1.0.2
django-mptt==0.7.4
django-parler==1.5.1
django-phonenumber-field==0.7.2
django-polymorphic==0.7.2
django-reversion==1.8.7
django-sekizai==0.8.2
django-sortedm2m==1.3.2
django-taggit==0.17.3
django-treebeard==3.0
djangocms-admin-style==1.0.5
djangocms-column==1.5
djangocms-file==0.1
djangocms-flash==0.2.0
djangocms-googlemap==0.3
djangocms-inherit==0.1
djangocms-installer==0.7.9
djangocms-link==1.6.2
djangocms-picture==0.1
djangocms-style==1.5
djangocms-teaser==0.1
djangocms-text-ckeditor==2.7.0
djangocms-video==0.1
easy-thumbnails==2.2.1
gunicorn==19.4.3
html5lib==0.9999999
lxml==3.5.0
phonenumbers==7.1.1
python-dateutil==2.4.2
python-slugify==1.1.4
pytz==2015.7
simplejson==3.8.0
six==1.10.0
tzlocal==1.2
vobject==0.6.6
wheel==0.24.0
wsgiref==0.1.2


问:
CreateDocumentQuery crashes my app running local only
I have a ASP.Net Core MVC web app that is connecting to Azure Cosmos DB. I have a couple of CreateDocumentQuery statements that when I run my app locally, causes an exception and the running app to stop. When I publish the same code to my Azure site, it works just fine.

The line it seems to fail on is

```<code>var applicantJobs = client.CreateDocumentQuery<ApplicantJob>(documentCollectionUri).Where(x => x.UserId == userId).ToList();
</code>```

The exception I get is

Locally I can run CreateDocumentAsync and ReadDocumentAsync just fine with no issues.

I have read online about 64 vs 32 and have followed that guidance, but I assume I am missing something.

答: Removing the reference to Microsoft.Azure.DocumentDB 1.14.1 allows it to run successfully on my development machine.</p>

Body:
I have a ASP.Net Core MVC web app that is connecting to Azure Cosmos DB. I have a couple of CreateDocumentQuery statements that when I run my app locally, causes an exception and the running app to stop. When I publish the same code to my Azure site, it works just fine.

The line it seems to fail on is

var applicantJobs = client.CreateDocumentQuery<ApplicantJob>(documentCollectionUri).Where(x => x.UserId == userId).ToList();

The exception I get is

Locally I can run CreateDocumentAsync and ReadDocumentAsync just fine with no issues.

I have read online about 64 vs 32 and have followed that guidance, but I assume I am missing something.


问:
JUnit test - asset or verify (or both) on a mock object?
I am playing around writing a JUnit test for some beans I have defined in my code, in order to learn about spring configuration via java annotations. The test code looks like this:

```<code>public class FooTest {

    @MockBean
    private Baz baz; //injected

    @MockBean
    private Qux qux; //injected

    public void testBar() {
        Foo foo = new Foo(baz);
        Qux reponse = foo.bar();
        // verify or assert?
    }

}
</code>```

And the other classes are defined like this:

```<code>@Component
class Foo {

    Baz baz;

    @Autowired
    Foo(Baz baz) {
        this.baz = baz
    }

    Qux bar() {
        baz.waldo();
        baz.fred();
        return baz.newQux();
    }
}

@Component
class Baz {
    //...
}
</code>```

As you can see in my JUnit test, I return a Qux response from the mocked Qux bean in the FooTest class. It got me thinking about testing the bar method in class Foo. I see 3 options here and was wondering what would be considered best practice?

Do an assertEquals on the response in test method testBar on the qux instance variable in FooTest.

Do the above but also do a verify on the baz instance in FooTest that waldo and fred were also called? Or are these verify calls superfluous, since the baz is returned, I assume they were called?

Do 1 and 2?

答:
Firstly, you need to define what happens when these statements are executed.

```<code> baz.waldo();
 baz.fred();
 baz.newQux();
</code>```

Since baz is a mock.

Secondly you have to do verify to make sure all the methods are called. You can also do assert. But first you need to define what has to be retuened when baz.newQux() is called. And check the response of foo.bar() if this is same as what you have defined.

Body:
I am playing around writing a JUnit test for some beans I have defined in my code, in order to learn about spring configuration via java annotations. The test code looks like this:

public class FooTest {

    @MockBean
    private Baz baz; //injected

    @MockBean
    private Qux qux; //injected

    public void testBar() {
        Foo foo = new Foo(baz);
        Qux reponse = foo.bar();
        // verify or assert?
    }

}

And the other classes are defined like this:

@Component
class Foo {

    Baz baz;

    @Autowired
    Foo(Baz baz) {
        this.baz = baz
    }

    Qux bar() {
        baz.waldo();
        baz.fred();
        return baz.newQux();
    }
}

@Component
class Baz {
    //...
}

As you can see in my JUnit test, I return a Qux response from the mocked Qux bean in the FooTest class. It got me thinking about testing the bar method in class Foo. I see 3 options here and was wondering what would be considered best practice?

Do an assertEquals on the response in test method testBar on the qux instance variable in FooTest.

Do the above but also do a verify on the baz instance in FooTest that waldo and fred were also called? Or are these verify calls superfluous, since the baz is returned, I assume they were called?

Do 1 and 2?

Body:
Firstly, you need to define what happens when these statements are executed.

 baz.waldo();
 baz.fred();
 baz.newQux();

Since baz is a mock.

Secondly you have to do verify to make sure all the methods are called. You can also do assert. But first you need to define what has to be retuened when baz.newQux() is called. And check the response of foo.bar() if this is same as what you have defined.


问:
Which UML editor is this? Alternatively, how can I view and edit this diagram (XML file)?
A couple of years ago I worked on a project and thus I prepared some UML diagrams. Now I have the XML files but I can't remember the editor I used to create them. Can you help me in finding it?
I use Kubuntu.
here you can find an old
screenshot and an XML file

EDIT: I'm almost sure it was a free tool for linux. Nevertheless, any (free) editor that can open the XML files I have in my HD would be a satisfactory answer for me!

答:
Found it! Analysing the code I saw that "mx" was a recurring prefix. Googling the name of the XML entities I could see in the code, I found that they are described in mxGraph’s diagramming API. Finally, I found an online tool that uses mxGraph: "draw.io". Many thanks to Thomas Kilian!
Now, next question could be how to save the diagrams in a standard format for future use without going crazy again...</p>


问:
Prevent svg groups from overlapping (D3 js v4)
How can I prevent the svg's "g" element from overlapping on the other "g" elements when I drag the element to switch/change its position.
Below is the link to the code.

https://jsfiddle.net/3jxqgjcL/

```<code>var group = svg.selectAll('g')
  .data(rectangles)
  .enter().append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

group.append("rect")
     .attr("x", function(d) { return d.x; })
     .attr("y", function(d) { return d.y; })
     .attr("height", 60)
     .attr("width", 300)
     .style("fill", function(d, i) { return color(i); });

group.append("text")
     .attr("x", function(d) { return d.x; })
     .attr("y", function(d) { return d.y; })
       .attr("text-anchor", "start")
       .style("fill", "steelblue")
       .text("Close");

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).select("text")
    .attr("y", d.y = d3.event.y);
  d3.select(this).select("rect")
    .attr("y", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("active", false);
}
</code>```

答:
Your question is not exactly clear. I'm assuming that by prevent the svg's "g" element from overlapping you want to rearrange the groups when you release one of them.

That being the case, you can get all the <g> elements in the dragended function, sort them and translate them according to their indices:

```<code>function dragended(d) {
    d3.select(this).classed("active", false);
    var theseGroups = svg.selectAll(".groups").sort(function(a, b) {
        return d3.ascending(a.y, b.y);
    });
    theseGroups.attr("transform", function(d, i) {
        return "translate(" + margin.left / 2 + "," + (d.y = barHeight * i) + ")";
    })
}
</code>```

Here is a demo:

var margin = {
    top: 10,
    right: 10,
    bottom: 30,
    left: 10
  },
  width = 500 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom
distance = 0, barHeight = 75, i = 0;

function yAxis() {
  if (i == 0) {
    i++;
    return 2;
  } else {
    distance = parseInt(barHeight) * i;
    i++;
    return distance;
  }
}
var rectangles = d3.range(5).map(function() {
  return {
    x: 5,
    y: Math.round(yAxis())
  };
});

var color = d3.scaleOrdinal(d3.schemeCategory10);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var group = svg.selectAll('g')
  .data(rectangles)
  .enter().append("g")
  .attr("class", "groups")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")"
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

group.append("rect")
  .attr("height", 60)
  .attr("width", 300)
  .style("fill", function(d, i) {
    return color(i);
  });

group.append("text")
  .attr("text-anchor", "start")
  .style("fill", "steelblue")
  .text("Close");

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).attr("transform", "translate(" + margin.left / 2 + "," + (d.y = d3.event.y) + ")");
}

function dragended(d) {
  d3.select(this).classed("active", false);
  var theseGroups = svg.selectAll(".groups").sort(function(a, b) {
    return d3.ascending(a.y, b.y);
  });
  theseGroups.attr("transform", function(d, i) {
    return "translate(" + margin.left / 2 + "," + (d.y = barHeight * i) + ")";
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  border: 1px solid #000;
}</code>```

```

Body:
How can I prevent the svg's "g" element from overlapping on the other "g" elements when I drag the element to switch/change its position.
Below is the link to the code.

https://jsfiddle.net/3jxqgjcL/

var group = svg.selectAll('g')
  .data(rectangles)
  .enter().append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

group.append("rect")
     .attr("x", function(d) { return d.x; })
     .attr("y", function(d) { return d.y; })
     .attr("height", 60)
     .attr("width", 300)
     .style("fill", function(d, i) { return color(i); });

group.append("text")
     .attr("x", function(d) { return d.x; })
     .attr("y", function(d) { return d.y; })
       .attr("text-anchor", "start")
       .style("fill", "steelblue")
       .text("Close");

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).select("text")
    .attr("y", d.y = d3.event.y);
  d3.select(this).select("rect")
    .attr("y", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("active", false);
}

Body:
Your question is not exactly clear. I'm assuming that by prevent the svg's "g" element from overlapping you want to rearrange the groups when you release one of them.

That being the case, you can get all the <g> elements in the dragended function, sort them and translate them according to their indices:

function dragended(d) {
    d3.select(this).classed("active", false);
    var theseGroups = svg.selectAll(".groups").sort(function(a, b) {
        return d3.ascending(a.y, b.y);
    });
    theseGroups.attr("transform", function(d, i) {
        return "translate(" + margin.left / 2 + "," + (d.y = barHeight * i) + ")";
    })
}

Here is a demo:

var margin = {
    top: 10,
    right: 10,
    bottom: 30,
    left: 10
  },
  width = 500 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom
distance = 0, barHeight = 75, i = 0;

function yAxis() {
  if (i == 0) {
    i++;
    return 2;
  } else {
    distance = parseInt(barHeight) * i;
    i++;
    return distance;
  }
}
var rectangles = d3.range(5).map(function() {
  return {
    x: 5,
    y: Math.round(yAxis())
  };
});

var color = d3.scaleOrdinal(d3.schemeCategory10);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var group = svg.selectAll('g')
  .data(rectangles)
  .enter().append("g")
  .attr("class", "groups")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")"
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

group.append("rect")
  .attr("height", 60)
  .attr("width", 300)
  .style("fill", function(d, i) {
    return color(i);
  });

group.append("text")
  .attr("text-anchor", "start")
  .style("fill", "steelblue")
  .text("Close");

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).attr("transform", "translate(" + margin.left / 2 + "," + (d.y = d3.event.y) + ")");
}

function dragended(d) {
  d3.select(this).classed("active", false);
  var theseGroups = svg.selectAll(".groups").sort(function(a, b) {
    return d3.ascending(a.y, b.y);
  });
  theseGroups.attr("transform", function(d, i) {
    return "translate(" + margin.left / 2 + "," + (d.y = barHeight * i) + ")";
  })
}

svg {
  border: 1px solid #000;
}

<script src="https://d3js.org/d3.v4.min.js"></script>


问:
REST API: adapt a curl post to powershell
I try to adapt a working curl command to powershell

this is the working curl from postman:

```<code>curl -X POST \
  https://test.portal.com/api/v1/login \
  -H 'authorization: Basic ADSFws343==' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 06944eab-3634-dd34-4634-0966bd8872c5' \
  -F 'user[email]=xxx@xxx.com' \
  -F 'user[password]=xxx'
</code>```

This creates the following raw data

```<code>POST /api/v1/login HTTP/1.1
cache-control: no-cache
Postman-Token: 80b2b345-6f5d-4c63-bedf-c65038b1e5df
Authorization: Basic ADSFws343==
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Accept: */*
Host: test.portal.com
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------266295771457397823506834
content-length: 309
Connection: close

----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------266295771457397823506834--
</code>```

and I get the following response:

```<code>HTTP/1.1 201 Created
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 13:42:54 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 201 Created
Cache-Control: max-age=0, private, must-revalidate
X-XSS-Protection: 1; mode=block
X-Request-Id: d1dd86e7-325a-43d5-bfda-46a9df4cc660
ETag: W/"3b793a3a1971dac89b48633e0e031237"
X-Frame-Options: SAMEORIGIN
X-Runtime: 0.115464
X-Content-Type-Options: nosniff
X-Powered-By: Phusion Passenger 5.1.4
</code>```

with the expected data in the body.

Now I struggle to adapt the code to powershell

```<code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$boundary = "--------------------------210183530616764504332035"
$URL = "https://test.portal.com/api/v1/login"
$email = "xxx@xxx.com"
$password= "xxx"

$headers = @{
    "cache-control"="no-cache";
    "Postman-Token"="3cf33ce8-716e-4ac1-b2da-c46df65d5307"
    Authorization="Basic ADSFws343==";
    "content-type"="multipart/form-data; boundary=$boundary"
    "User-Agent"="PostmanRuntime/3.0.11-hotfix.2"
    "Accept"="*/*"
    "accept-encoding"="gzip, deflate"
}

$LF = "`n"
$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[email]`"$LF",
    $email,
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[password]`"$LF",
    $password,
    "--$boundary--$LF"
    ) -join $LF

$response = Invoke-RestMethod -Uri $URL -Headers $headers -Method Post -TimeoutSec 20 -Body $bodyLines -DisableKeepAlive
</code>```

This throws an exception:

```<code>Invoke-RestMethod : Incomplete response received from application
</code>```

and creates the following raw data

```<code>POST https://test.portal.com/api/v1/login HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------210183530616764504332065
Accept: */*
Postman-Token: 3cf33ce8-716e-4ac1-b2da-c46df65d5307
Authorization: Basic ADSFws343==
accept-encoding: gzip, deflate
cache-control: no-cache
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Host: test.portal.com
Content-Length: 300
Connection: Close

----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------210183530616764504332065--
</code>```

and this response

```<code>HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 14:02:23 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54
Connection: close
Status: 502 Bad Gateway
cache-control: no-cache, no-store, must-revalidate

<h2>Incomplete response received from application</h2>
</code>```

Where is my fault or what is missing? The only difference in the Raw Data is the somehow shorter content-length. even the boundarys have the same length as the postman curl

Thank you for taking your time

Edit: Changed the Headers to hash-table without effect and changed the powershell code to simulate the postman curl more accurate

Final Solution: Problem was the wrong format of the body. Changing

```<code>$LF = "`n"
</code>```

to

```<code>$LF = "`r`n"
</code>```

fixed the problem!

答:
try something like

```<code>$user = 'user'
$password= 'passwd'

$params = @{
    Uri = 'https://httpbin.org/basic-auth/user/passwd'
    Method = 'Get'
    Headers = @{
        Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($user):$($password)"))
    }
}

Invoke-RestMethod @params
</code>```

what bothers me is that you seem to be using both HTTP BasicAuth and also user/pass in the body, submitting a form. Perhaps something like

```<code>$user = 'user'
$password= 'passwd'

$boundary = '----------------------------266295771457397823506834'

$body = @"
$boundary
Content-Disposition: form-data; name="user[email]"

$user
$boundary
Content-Disposition: form-data; name="user[password]"

$password
$boundary--
"@

$params = @{
    Uri = 'https://httpbin.org/basic-auth/user/passwd'
    Method = 'Post'
    Headers = @{
        Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($user):$($password)"))
        'Content-Type' = "multipart/form-data; boundary=$boundary"
    }
    Body = $body
}

Invoke-RestMethod @params
</code>```

Body:
I try to adapt a working curl command to powershell

this is the working curl from postman:

curl -X POST \
  https://test.portal.com/api/v1/login \
  -H 'authorization: Basic ADSFws343==' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 06944eab-3634-dd34-4634-0966bd8872c5' \
  -F 'user[email]=xxx@xxx.com' \
  -F 'user[password]=xxx'

This creates the following raw data

POST /api/v1/login HTTP/1.1
cache-control: no-cache
Postman-Token: 80b2b345-6f5d-4c63-bedf-c65038b1e5df
Authorization: Basic ADSFws343==
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Accept: */*
Host: test.portal.com
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------266295771457397823506834
content-length: 309
Connection: close

----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------266295771457397823506834--

and I get the following response:

HTTP/1.1 201 Created
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 13:42:54 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 201 Created
Cache-Control: max-age=0, private, must-revalidate
X-XSS-Protection: 1; mode=block
X-Request-Id: d1dd86e7-325a-43d5-bfda-46a9df4cc660
ETag: W/"3b793a3a1971dac89b48633e0e031237"
X-Frame-Options: SAMEORIGIN
X-Runtime: 0.115464
X-Content-Type-Options: nosniff
X-Powered-By: Phusion Passenger 5.1.4

with the expected data in the body.

Now I struggle to adapt the code to powershell

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$boundary = "--------------------------210183530616764504332035"
$URL = "https://test.portal.com/api/v1/login"
$email = "xxx@xxx.com"
$password= "xxx"

$headers = @{
    "cache-control"="no-cache";
    "Postman-Token"="3cf33ce8-716e-4ac1-b2da-c46df65d5307"
    Authorization="Basic ADSFws343==";
    "content-type"="multipart/form-data; boundary=$boundary"
    "User-Agent"="PostmanRuntime/3.0.11-hotfix.2"
    "Accept"="*/*"
    "accept-encoding"="gzip, deflate"
}

$LF = "`n"
$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[email]`"$LF",
    $email,
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[password]`"$LF",
    $password,
    "--$boundary--$LF"
    ) -join $LF

$response = Invoke-RestMethod -Uri $URL -Headers $headers -Method Post -TimeoutSec 20 -Body $bodyLines -DisableKeepAlive

This throws an exception:

Invoke-RestMethod : Incomplete response received from application

and creates the following raw data

POST https://test.portal.com/api/v1/login HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------210183530616764504332065
Accept: */*
Postman-Token: 3cf33ce8-716e-4ac1-b2da-c46df65d5307
Authorization: Basic ADSFws343==
accept-encoding: gzip, deflate
cache-control: no-cache
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Host: test.portal.com
Content-Length: 300
Connection: Close

----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------210183530616764504332065--

and this response

HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 14:02:23 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54
Connection: close
Status: 502 Bad Gateway
cache-control: no-cache, no-store, must-revalidate

Incomplete response received from application

Where is my fault or what is missing? The only difference in the Raw Data is the somehow shorter content-length. even the boundarys have the same length as the postman curl

Thank you for taking your time

Edit: Changed the Headers to hash-table without effect and changed the powershell code to simulate the postman curl more accurate

Final Solution: Problem was the wrong format of the body. Changing

$LF = "`n"

to

$LF = "`r`n"

fixed the problem!

Body:
try something like

$user = 'user'
$password= 'passwd'

$params = @{
    Uri = 'https://httpbin.org/basic-auth/user/passwd'
    Method = 'Get'
    Headers = @{
        Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($user):$($password)"))
    }
}

Invoke-RestMethod @params

what bothers me is that you seem to be using both HTTP BasicAuth and also user/pass in the body, submitting a form. Perhaps something like

$user = 'user'
$password= 'passwd'

$boundary = '----------------------------266295771457397823506834'

$body = @"
$boundary
Content-Disposition: form-data; name="user[email]"

$user
$boundary
Content-Disposition: form-data; name="user[password]"

$password
$boundary--
"@

$params = @{
    Uri = 'https://httpbin.org/basic-auth/user/passwd'
    Method = 'Post'
    Headers = @{
        Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($user):$($password)"))
        'Content-Type' = "multipart/form-data; boundary=$boundary"
    }
    Body = $body
}

Invoke-RestMethod @params


问:
vertically align two different classes next to each other with css
How can I align two div's with different classes together above another?

If I have the following code:

```<code><div class="div1">
</div>
<div class="div2">
</div>
<div class="div3">
</div>
</code>```

how can I align div1 and div3 next to each other? and above the div1? Is it possible only with html and css?
thanks in advance

答:
Can't you just place all the div's in a container that is 100% width and do a text-align: center?

Simple jFiddle for you.

```<code>.container {
  width:100%;
  text-align:center;
}
</code>```

Body:
How can I align two div's with different classes together above another?

If I have the following code:

how can I align div1 and div3 next to each other? and above the div1? Is it possible only with html and css?
thanks in advance

Body:
Can't you just place all the div's in a container that is 100% width and do a text-align: center?

Simple jFiddle for you.

.container {
  width:100%;
  text-align:center;
}


问:
button link with font awesome not working
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.</p>

```<code> <a href="https://github.com/"> <button type="submit"><i class="fa fa-github"
    aria-hidden="true">GitHub</i></a>
</code>```

答:
Try this:

You should have the font awesome installed locally or by CDN

By CDN
You should put this code on the

```<code><link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' type='text/css' media='all' />
</code>```

HTML

```<code><button onclick="window.location.href='https://github.com/'"><i class="fa fa-github" aria-hidden="true"></i>GitHub</button>
</code>```

OR

```<code><a href="https://github.com/"><i class="fa fa-github" aria-hidden="true"></i>GitHub</a>
</code>```

Body:
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.

  <button type="submit">GitHub

Body:
Try this:

You should have the font awesome installed locally or by CDN

By CDN
You should put this code on the <header>

<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' type='text/css' media='all' />

HTML

<button onclick="window.location.href='https://github.com/'"><i class="fa fa-github" aria-hidden="true"></i>GitHub</button>

OR

<a href="https://github.com/"><i class="fa fa-github" aria-hidden="true"></i>GitHub</a>


问:
How elements in array are obtained by index?
I am learning about array as a data structure and I'm interested in how exactly in Java we obtain an element in an array by index.

What's happening under the hood when the following code is executed:

```<code>...
int i = array[2];
</code>```

How JVM stores refferences to primitive types in array? How we obtain the element in O(1)? Does JVM calculates position of the element relative other element?

答:
Arrays like int[], double[], etc. Is native arrays.
The Reference to native array is the reference to its first element.
Element with index "i" will be getted by dereferencing ("reference on the first element" + i * sizeOf("contained type")).

P.s. In the Java they are wrapped in other class for checking bounds, getting length and so on. In the low-level programming languages like C++ you can broke your programm, when u will try to change element by index grater than array length

Body:
I am learning about array as a data structure and I'm interested in how exactly in Java we obtain an element in an array by index.

What's happening under the hood when the following code is executed:

...
int i = array[2];

How JVM stores refferences to primitive types in array? How we obtain the element in O(1)? Does JVM calculates position of the element relative other element?


答:
If there is a possibility to do Assert, do it. In this case you will check the actual value that method returns after it was invoked.

Verify only checks that method was called. This is more useful when you call some method and you want to check that another method was called inside, but you couldn't do it based on the return object. In your case you return the whole object, thus, from my point of you, you should be able to use assert.

Title: JUnit test - asset or verify (or both) on a mock object?


问:
Notifications in Ionic 2
I have gone through many posts.

Its bit confusing to understand that does ionic 2 app send local-notification even if my-app-is-killed-by-user or not ?

I have below scenario.

Assuming that app-is-killed-by-user

Can we run the app in background (like after 24 hours check if some
  conditions are true by manipulating local/cloud storage) then send local notification ?

I am new to ionic 2. So can anyone let me know that above scenario is possible ?

If not possible then let me know that can we manipulate (get and analyse) local-storage via push notification server (assuming that app-is-killed-by-user) ?

答:
Both are possible. I'll tell you how i would do them and not share code (it can be long), i'll give you the steps and you can figure it out.

For the first scenario you'll need LocalNotification plugin, LocalStorage, Platform import from 'ionic-angular' and MomentJS(not required, but highly recommended).

You'll need to create a service, at least it's good so you don't need to put everything in your app.components.

You can use 3 of the Platform methods to verify and set the LocalNotification, they're .pause, .resume and .ready.

Pause will check if the user has left the app, but it's still running on background.

Resume will check if the user has come back to the app, but'll not trigger if the app was killed.

Ready will trigger when platform's ready, you'll use this to check if the app was killed and is starting for "the first time".

You'll need MomentJS to manipulate time, since it's easier to add days/hours to your current datetime.

LocalNotification accepts both ISO string and UNIX timestamp to schedule a notification.

Inside your created service you'll have methods to schedule and cancel a LocalNotification, check the plugin wiki for those.

On the pause method you'll call the schedule method and schedule a localNotification having Moment add 1 day to your current time: Moment().add(1, 'day').unix() and use the result in the 'at' of your schedule.

This'll return a promise with the data of your notification and it's id, save this id in your localStorage like this.storage.set('Daily', ReturnedID);

When the app is ready or resume you'll cancel the notification.

So basically that's it, when going off you save a notification, when going in you cancel it.

The second scenario is a little bit harder and you'll need a back-end for this since you'll need to keep checking the time that user has gone off the app. You'll need only MomentJS, the Platform import, you push service plugin and a way to connect to your database (via Http or plugin, if it's a service like Firebase).

The steps are the same for the first scenario, the new service, the platform calling this service methods, but now will add some methods for you push plugin, so when you receive a push you can show and manipulate data.

Most push services (and localNotification) have a Data attribute where you can share some data with the user, in your case it'll be the data you want to safe in the localStorage.

You'll need a token of that user so you can send a push to him, see your push docs to see how you can get that token and save it to the user database register/node.

When the user leave the app you'll store in your database the time you want the user to receive that push (i'm assuming you want to do the same as the first scenario, but in a different way).

When the user come back to the app, you'll detele that time register.

The tricky part: you'll need your back-end to go through every user register and get the time they need to receive the push, so if the time is < the current time you'll send the push and delete that register.

In the app when the user receive the push a function'll save the data to localStorage, manipulate, ready or everything you want.

Sorry i can't share some code, but if you need furter explanation or ideas just ask.
Hope this helps :D

Title: Notifications in Ionic 2


问:
How to shake virtual device created by Genymotion (Android Emulator)
I created a virtual device using Genymotion. I want to test an app that works with shaking the device. How can I make virtual device shake? I couldn't find how to shake that device. </p>

答: There isn't a native way to emulate a shake in genymotion, but you could try a tool like Frappe (Mac only) to send a shake action to the virtual device. Depending on the client you are trying to emulate, "adb shell input keyevent 82" may send a shake action, wake the device, or simulate a menu key press.</p>


问:
Scrolling DIV on static body scroll
I have a static body element and a DIV inside it, which height is 500px. It has overflow: visible and text longer than 500px. I want to scroll that DIV while I have mouse pointer over body (which doesn't have any scrollbars itself).

Any directions?

Pic related - the mouse pointer is outside of the DIV I want to scroll

答:
Ok I found it. For anyone who finds this thread:</p>

```<code>/** This is high-level function.
* It must react to delta being more/less than zero.
*/
function handle(delta) {
var target = $('#scrollable_content');
var top = target.scrollTop() - delta;
target.scrollTop(top);
}

/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
        event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
        delta = event.wheelDelta/120;
} else if (event.detail) { /** Mozilla case. */
        /** In Mozilla, sign of delta is different than in IE.
         * Also, delta is multiple of 3.
         */
        delta = -event.detail/3;
}

/** If delta is nonzero, handle it.
 * Basically, delta is now positive if wheel was scrolled up,
 * and negative, if wheel was scrolled down.
 */
if (delta) handle(delta);

/** Prevent default actions caused by mouse wheel.
 * That might be ugly, but we handle scrolls somehow
 * anyway, so don't bother here..
 */
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}

if (window.addEventListener) window.addEventListener('DOMMouseScroll',
wheel, false);
window.onmousewheel = document.onmousewheel = wheel;
</code>```

Title: Scrolling DIV on static body scroll

Body:
Ok I found it. For anyone who finds this thread:

/** This is high-level function.
* It must react to delta being more/less than zero.
*/
function handle(delta) {
var target = $('#scrollable_content');
var top = target.scrollTop() - delta;
target.scrollTop(top);
}

/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
        event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
        delta = event.wheelDelta/120;
} else if (event.detail) { /** Mozilla case. */
        /** In Mozilla, sign of delta is different than in IE.
         * Also, delta is multiple of 3.
         */
        delta = -event.detail/3;
}

/** If delta is nonzero, handle it.
 * Basically, delta is now positive if wheel was scrolled up,
 * and negative, if wheel was scrolled down.
 */
if (delta) handle(delta);

/** Prevent default actions caused by mouse wheel.
 * That might be ugly, but we handle scrolls somehow
 * anyway, so don't bother here..
 */
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}

if (window.addEventListener) window.addEventListener('DOMMouseScroll',
wheel, false);
window.onmousewheel = document.onmousewheel = wheel;


答:
This also works:</p>

```<code>from math import floor

lists = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

n = len(lists) # assume each list also has n-length

output_list = []

idx = 0
while idx <= floor(n/2):

    if len(output_list) == n*n:
        break

    # across ->
    print("Across ->")
    for item in lists[idx][idx:n-idx]:
        output_list.append(item)
    print(output_list)

    if len(output_list) == n*n:
        break

    # down
    print("Down")
    for _idx in range(idx+1, n-idx-1):
        output_list.append(lists[_idx][n-idx-1])
    print(output_list)

    if len(output_list) == n*n:
        break

    # across <-
    print("Across <-")
    for _idx in range(n-idx-1, idx-1, -1):
        output_list.append(lists[n-idx-1][_idx])
    print(output_list)

    if len(output_list) == n*n:
        break

    # up
    print("Up")
    for _idx in range(n-idx-2, idx, -1):
        output_list.append(lists[_idx][idx])
    print(output_list)

    idx += 1

print("\nOutput: ")
print(output_list)
</code>```

Title: Python: 2D to 1D list in clockwise direction?

Body:
I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.

For example:

When n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

or

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

would become

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

and when n = 5

list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]

or

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

would become

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

How can I efficiently do that for any value of nxn ??

Body:
This also works:

from math import floor

lists = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

n = len(lists) # assume each list also has n-length

output_list = []

idx = 0
while idx <= floor(n/2):

    if len(output_list) == n*n:
        break

    # across ->
    print("Across ->")
    for item in lists[idx][idx:n-idx]:
        output_list.append(item)
    print(output_list)

    if len(output_list) == n*n:
        break

    # down
    print("Down")
    for _idx in range(idx+1, n-idx-1):
        output_list.append(lists[_idx][n-idx-1])
    print(output_list)

    if len(output_list) == n*n:
        break

    # across <-
    print("Across <-")
    for _idx in range(n-idx-1, idx-1, -1):
        output_list.append(lists[n-idx-1][_idx])
    print(output_list)

    if len(output_list) == n*n:
        break

    # up
    print("Up")
    for _idx in range(n-idx-2, idx, -1):
        output_list.append(lists[_idx][idx])
    print(output_list)

    idx += 1

print("\nOutput: ")
print(output_list)


问:
BreadCrumb trail MVC3 and Razor
Anyone have an example of how to create a breadcrumb trail using the latest MVC3 release and razor syntax?</p>

答: You should be able to achieve this by using the MVC SiteMap Provider: http://mvcsitemap.codeplex.com/.  It contains features to create breadcrumb trails, and is documented fairly well (and you can always grab the code and modify it to do exactly what you want.)</p>

ContentLicense: CC BY-SA 2.5

Title: BreadCrumb trail MVC3 and Razor


问:
Loop through properties in JavaScript object with Lodash
Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:

```<code>myObject.options = {
  property1: 'value 1',
  property2: 'value 2'
};
</code>```

Properties will get dynamically added to this object. Is there a way for me to just loop through and do a check if a property exists? If so, how?

答:
In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.

The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

Here is an example:

```<code>const obj1 = {
  a: 5,
  b: "hello",
  [Symbol.iterator]: function() {
    const thisObj = this;
    let index = 0;
    return {
      next() {
        let keys = Object.keys(thisObj);
        return {
          value: thisObj[keys[index++]],
          done: (index > keys.length)
        };
      }
    };
  }
};
</code>```

Now we can use the for..of loop:

```<code>for (val of obj1) {
  console.log(val);
}    // 5 hello
</code>```

Body:
Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:

myObject.options = {
  property1: 'value 1',
  property2: 'value 2'
};

Properties will get dynamically added to this object. Is there a way for me to just loop through and do a check if a property exists? If so, how?

Body:
In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.

The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

Here is an example:

const obj1 = {
  a: 5,
  b: "hello",
  [Symbol.iterator]: function() {
    const thisObj = this;
    let index = 0;
    return {
      next() {
        let keys = Object.keys(thisObj);
        return {
          value: thisObj[keys[index++]],
          done: (index > keys.length)
        };
      }
    };
  }
};

Now we can use the for..of loop:

for (val of obj1) {
  console.log(val);
}    // 5 hello


问:
sending pdf in json from symfony to angular
i working on a project with symfony and angular and i want to send a pdf file in json or another way to send it from my backend to frontend app .

i won't try to save it on the server and send just the url to access . what i want is to send it on json data .

for more details i using FPDF to generate pdf file and i want to to it in json .
this is my controller :

```<code>/**
     * @Get("/testt")
     */
    public function test2Action()
    {
        $pdf = new \FPDF('P','mm','A4');
        $pdf->AddPage();
        $pdf->Image(__DIR__.'/../../../../web/assets/images/icons8-Calendar Filled-50.png');
        $pdf->SetFont('Arial','B',14);
        $pdf->SetXY(25,12);
        $pdf->Cell(40,10,utf8_decode('Evénements'));
        $pdf->SetXY(10,25);
        $pdf->Cell(40,10,utf8_decode("72eordre"));
        $pdf->SetXY(12,42);
        $pdf->Image(__DIR__.'/../../../../web/assets/images/icons8-Marker-50.png',null,null,-150);
        $pdf->SetFont('Arial','B',10);$pdf->SetTextColor(110,110,110);
        $pdf->SetXY(22,36);
        $pdf->Cell(40,10,utf8_decode(" Grand Palais"));
        $pdf->SetXY(22,41);
        $pdf->Cell(40,10,utf8_decode("saada 458"));
        $pdf->SetXY(22,46);
        $pdf->Cell(40,10,utf8_decode("59000, marrakech-"));
        $pdf->SetXY(12,61);
        $pdf->Image(__DIR__.'/../../../../web/assets/images/calendar-gris.png',null,null,-150);

        $pdf->SetXY(22,58);
        $pdf->Cell(40,10,utf8_decode("Du 27 septembre 2017 à 08:00"));
        $pdf->SetXY(22,63);
        $pdf->Cell(40,10,utf8_decode("Au 29 semptembre 2017 à 18:00"));

        $pdf->SetXY(10,80);
        $pdf->SetFont('Arial','B',10);$pdf->SetFont('');$pdf->SetTextColor(110,110,110);
        $pdf->Cell(40,10,utf8_decode("Cette carte"));
         $pdf->SetXY(10,85);
        $pdf->Cell(20,10,utf8_decode(" obtenir votre badge "));
        $pdf->SetXY(25,96);
        $pdf->Image(__DIR__.'/../../../../web/assets/qrcode.png',null,null,-220);
        $pdf->SetXY(25,160);
        $pdf->SetFillColor(1,49,180);
        $pdf->SetLineWidth(0.2835);
        $pdf->Rect(12,160,85,20, "F");
        $pdf->SetXY(14,161);
        $pdf->SetFont('Arial','B',14);$pdf->SetTextColor(255,255,255);
        $pdf->Cell(20,10,utf8_decode("yassine "));
        $pdf->SetXY(14,168);
        $pdf->SetFont('Arial','B',12);$pdf->SetTextColor(255,255,255);$pdf->SetFont('');
        $pdf->Cell(20,10,utf8_decode("CHEF DE PROJET "));
        $pdf->SetDrawColor(150,150,150);
        $pdf->Line(10, 25, 100, 25);
        $pdf->Line(10, 35, 100, 35);
        $pdf->Line(15, 55, 100, 55);
        $pdf->Line(10, 75, 100, 75);
        return new Response($pdf->Output(), 200, array(
            'Content-Type' => 'application/pdf'));
    }
</code>```

as you can see , the reponse type isby default in the FPDF api : application/pdf

so what is the solution to send this file and access from the frontend that is angular  2.3

答:
The safe way to embed a PDF into a JSON response is to encode it into base64 format. After that you can parse the response on a client side, decode the PDF data and do whatever you want with a PDF content.</p>

```<code>return new JsonResponse(['data' => base64_encode($pdf->Output())]);
</code>```

Body:
i working on a project with symfony and angular and i want to send a pdf file in json or another way to send it from my backend to frontend app .

i won't try to save it on the server and send just the url to access . what i want is to send it on json data .

for more details i using FPDF to generate pdf file and i want to to it in json .
this is my controller :

/**
     * @Get("/testt")
     */
    public function test2Action()
    {
        $pdf = new \FPDF('P','mm','A4');
        $pdf->AddPage();
        $pdf->Image(__DIR__.'/../../../../web/assets/images/icons8-Calendar Filled-50.png');
        $pdf->SetFont('Arial','B',14);
        $pdf->SetXY(25,12);
        $pdf->Cell(40,10,utf8_decode('Evénements'));
        $pdf->SetXY(10,25);
        $pdf->Cell(40,10,utf8_decode("72eordre"));
        $pdf->SetXY(12,42);
        $pdf->Image(__DIR__.'/../../../../web/assets/images/icons8-Marker-50.png',null,null,-150);
        $pdf->SetFont('Arial','B',10);$pdf->SetTextColor(110,110,110);
        $pdf->SetXY(22,36);
        $pdf->Cell(40,10,utf8_decode(" Grand Palais"));
        $pdf->SetXY(22,41);
        $pdf->Cell(40,10,utf8_decode("saada 458"));
        $pdf->SetXY(22,46);
        $pdf->Cell(40,10,utf8_decode("59000, marrakech-"));
        $pdf->SetXY(12,61);
        $pdf->Image(__DIR__.'/../../../../web/assets/images/calendar-gris.png',null,null,-150);

        $pdf->SetXY(22,58);
        $pdf->Cell(40,10,utf8_decode("Du 27 septembre 2017 à 08:00"));
        $pdf->SetXY(22,63);
        $pdf->Cell(40,10,utf8_decode("Au 29 semptembre 2017 à 18:00"));

        $pdf->SetXY(10,80);
        $pdf->SetFont('Arial','B',10);$pdf->SetFont('');$pdf->SetTextColor(110,110,110);
        $pdf->Cell(40,10,utf8_decode("Cette carte"));
         $pdf->SetXY(10,85);
        $pdf->Cell(20,10,utf8_decode(" obtenir votre badge "));
        $pdf->SetXY(25,96);
        $pdf->Image(__DIR__.'/../../../../web/assets/qrcode.png',null,null,-220);
        $pdf->SetXY(25,160);
        $pdf->SetFillColor(1,49,180);
        $pdf->SetLineWidth(0.2835);
        $pdf->Rect(12,160,85,20, "F");
        $pdf->SetXY(14,161);
        $pdf->SetFont('Arial','B',14);$pdf->SetTextColor(255,255,255);
        $pdf->Cell(20,10,utf8_decode("yassine "));
        $pdf->SetXY(14,168);
        $pdf->SetFont('Arial','B',12);$pdf->SetTextColor(255,255,255);$pdf->SetFont('');
        $pdf->Cell(20,10,utf8_decode("CHEF DE PROJET "));
        $pdf->SetDrawColor(150,150,150);
        $pdf->Line(10, 25, 100, 25);
        $pdf->Line(10, 35, 100, 35);
        $pdf->Line(15, 55, 100, 55);
        $pdf->Line(10, 75, 100, 75);
        return new Response($pdf->Output(), 200, array(
            'Content-Type' => 'application/pdf'));
    }

as you can see , the reponse type isby default in the FPDF api : application/pdf

so what is the solution to send this file and access from the frontend that is angular  2.3

Body:
The safe way to embed a PDF into a JSON response is to encode it into base64 format. After that you can parse the response on a client side, decode the PDF data and do whatever you want with a PDF content.

return new JsonResponse(['data' => base64_encode($pdf->Output())]);


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
Some bit shifting and & later...

```<code>int n = 5+32;
var lst = new List<int>();

int i = 1;
while (n > 0)
{
    if ((n & i) == i)
    {
        lst.Add(i);
        n &= ~i;
    }

    i <<= 1; // equivalent to i *= 2
}
</code>```

A little more esoteric, with the use of xor (^):

```<code>if (n != 0)
{
    while (true)
    {
        if ((n & i) != 0)
        {
            lst.Add(i);
            n ^= i;

            if (n == 0)
            {
                break;
            }
        }

        i <<= 1; // equivalent to i *= 2
    }
}
</code>```

Body:
Some bit shifting and & later...

int n = 5+32;
var lst = new List<int>();

int i = 1;
while (n > 0)
{
    if ((n & i) == i)
    {
        lst.Add(i);
        n &= ~i;
    }

    i <<= 1; // equivalent to i *= 2
}

A little more esoteric, with the use of xor (^):

if (n != 0)
{
    while (true)
    {
        if ((n & i) != 0)
        {
            lst.Add(i);
            n ^= i;

            if (n == 0)
            {
                break;
            }
        }

        i <<= 1; // equivalent to i *= 2
    }
}


问:
Python pandas: convert a column to a string?
I have some columns:

```<code>0                                            ['XS', '2X']
1                                      ['A2', '2X', '8W']
2                                                  ['2X']
3                    ['A2', 'FR', 'XS', '8W', '8E', '2X']
4                    ['A5', 'FR', 'XS', 'QF', '2X', '23']
5                                      ['XS', '2X', 'MF']
6                                                    None
</code>```

that I am trying to iterate over. It I loop over the column and get the type:

```<code>for item in data1['business_types']:
    print(type(item))
</code>```

It shows that the types are of type str

```<code><class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'NoneType'>
</code>```

I would like to convert the objects in this column to a list object that I can iterate over.

答:
I think you need ast.literal_eval with fillna for replace None to []:

```<code>data1['business_types'] = data1['business_types'].fillna('[]').apply(ast.literal_eval)
print (data1)
             business_types
0                  [XS, 2X]
1              [A2, 2X, 8W]
2                      [2X]
3  [A2, FR, XS, 8W, 8E, 2X]
4  [A5, FR, XS, QF, 2X, 23]
5              [XS, 2X, MF]
6                        []
</code>```

If need None (NaNs):

```<code>def f(x):
    try:
        return ast.literal_eval(x)
    except ValueError:
        return x

import ast

data1['business_types'] = data1['business_types'].apply(f)
print (data1)
             business_types
0                  [XS, 2X]
1              [A2, 2X, 8W]
2                      [2X]
3  [A2, FR, XS, 8W, 8E, 2X]
4  [A5, FR, XS, QF, 2X, 23]
5              [XS, 2X, MF]
6                       NaN

for item in data1['business_types']:
    print(type(item))

<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'float'>
</code>```

Body:
I have some columns:

0                                            ['XS', '2X']
1                                      ['A2', '2X', '8W']
2                                                  ['2X']
3                    ['A2', 'FR', 'XS', '8W', '8E', '2X']
4                    ['A5', 'FR', 'XS', 'QF', '2X', '23']
5                                      ['XS', '2X', 'MF']
6                                                    None

that I am trying to iterate over. It I loop over the column and get the type:

for item in data1['business_types']:
    print(type(item))

It shows that the types are of type str

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'NoneType'>

I would like to convert the objects in this column to a list object that I can iterate over.

Body:
I think you need ast.literal_eval with fillna for replace None to []:

data1['business_types'] = data1['business_types'].fillna('[]').apply(ast.literal_eval)
print (data1)
             business_types
0                  [XS, 2X]
1              [A2, 2X, 8W]
2                      [2X]
3  [A2, FR, XS, 8W, 8E, 2X]
4  [A5, FR, XS, QF, 2X, 23]
5              [XS, 2X, MF]
6                        []

If need None (NaNs):

def f(x):
    try:
        return ast.literal_eval(x)
    except ValueError:
        return x

import ast

data1['business_types'] = data1['business_types'].apply(f)
print (data1)
             business_types
0                  [XS, 2X]
1              [A2, 2X, 8W]
2                      [2X]
3  [A2, FR, XS, 8W, 8E, 2X]
4  [A5, FR, XS, QF, 2X, 23]
5              [XS, 2X, MF]
6                       NaN

for item in data1['business_types']:
    print(type(item))

<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'float'>


问:
“this” keyword doesn’t seem to work
I am trying to understand how the this keyword works in JavaScript and I made this script:

```<code>function click(){
    this.innerHTML="changed";
}
</code>```

Used in this HTML:

```<code><button id="clicker" onclick="click()" >Click me</button>
</code>```

But it doesn't work, can anyone explain why?

答:
Your question seems to be about the value of this. In an inline handler, this will represent the window. You can set the value of this using .call(), so it gives the value you desire.

Example: http://jsfiddle.net/patrick_dw/5uJ54/

```<code><button id="clicker" onclick="click.call(this)" >Click me</button>
</code>```

Now in your click method, this will be the <button> element.

The reason is that your inline attribute gets wrapped in a function, which itself has the context of the element. But it doesn't actually call your function from that context. By doing click(), it ends up looking like:

```<code>function onclick(event) {
    click();
}
</code>```

Your function is being called against no particular object, so the window is implied. By doing:

```<code><button id="clicker" onclick="click.call( this )" >Click me</button>
</code>```

...you end up with:

```<code>function onclick(event) {
    click.call( this );
}
</code>```

Giving the desired context. You can also pass the event object:

```<code><button id="clicker" onclick="click.call( this, event )" >Click me</button>
</code>```

...so you end up with:

```<code>function onclick(event) {
    click.call( this, event );
}
</code>```

So now in your click() function, you'll have the event as you'd expect.

Also, you may have issues with using click as a function name. I'd change it.

Title: “this” keyword doesn’t seem to work

Body:
I am trying to understand how the this keyword works in JavaScript and I made this script:

function click(){
    this.innerHTML="changed";
}

Used in this HTML:

<button id="clicker" onclick="click()" >Click me</button>

But it doesn't work, can anyone explain why?

Body:
Your question seems to be about the value of this. In an inline handler, this will represent the window. You can set the value of this using .call(), so it gives the value you desire.

Example: http://jsfiddle.net/patrick_dw/5uJ54/

<button id="clicker" onclick="click.call(this)" >Click me</button>

Now in your click method, this will be the <button> element.

The reason is that your inline attribute gets wrapped in a function, which itself has the context of the element. But it doesn't actually call your function from that context. By doing click(), it ends up looking like:

function onclick(event) {
    click();
}

Your function is being called against no particular object, so the window is implied. By doing:

<button id="clicker" onclick="click.call( this )" >Click me</button>

...you end up with:

function onclick(event) {
    click.call( this );
}

Giving the desired context. You can also pass the event object:

<button id="clicker" onclick="click.call( this, event )" >Click me</button>

...so you end up with:

function onclick(event) {
    click.call( this, event );
}

So now in your click() function, you'll have the event as you'd expect.

Also, you may have issues with using click as a function name. I'd change it.


问:
yii2. query with like condition
In my yii2 application i need something like this:

```<code>SELECT * FROM customers WHERE first_name||' '||last_name ILIKE '%Nick%' ORDER BY "id";
</code>```

This query gets customers with concatinated first_name and last_name like 'Nick'.

In my yii1 application I can use CDBCriteria next way:

```<code>$criteria = new CDbCriteria;
        $criteria->addSearchCondition(
            "first_name||' '||last_name",
            'Nick',
            true,
            'and',
            'ILIKE'
        );

$criteria->order = 't.id asc';
</code>```

And this works fine.

In yii2 I tried:

```<code>$a = \common\models\Customer::find()
        ->filterWhere(['ILIKE', "first_name||' '||last_name", 'Nick'])
        ->orderBy(['id' => SORT_ASC])
        ->all();
</code>```

And got exception column does not exist, and sql was:

```<code>SELECT * FROM "customers" WHERE "first_name||' '||last_name" ILIKE '%Nick%' ORDER BY "id"
</code>```

Using \yii\db\Expression doesnt change situation.

答:
Let it be for a while:</p>

```<code>\common\models\Customer::find()
                ->where("first_name||' '||last_name ilike '%'||:query||'%'", [':query' => $name])
                ->orderBy(['id' => SORT_ASC])
                ->all()
</code>```

Title: yii2. query with like condition

Body:
In my yii2 application i need something like this:

SELECT * FROM customers WHERE first_name||' '||last_name ILIKE '%Nick%' ORDER BY "id";

This query gets customers with concatinated first_name and last_name like 'Nick'.

In my yii1 application I can use CDBCriteria next way:

$criteria = new CDbCriteria;
        $criteria->addSearchCondition(
            "first_name||' '||last_name",
            'Nick',
            true,
            'and',
            'ILIKE'
        );

$criteria->order = 't.id asc';

And this works fine.

In yii2 I tried:

$a = \common\models\Customer::find()
        ->filterWhere(['ILIKE', "first_name||' '||last_name", 'Nick'])
        ->orderBy(['id' => SORT_ASC])
        ->all();

And got exception column does not exist, and sql was:

SELECT * FROM "customers" WHERE "first_name||' '||last_name" ILIKE '%Nick%' ORDER BY "id"

Using \yii\db\Expression doesnt change situation.

Body:
Let it be for a while:

\common\models\Customer::find()
                ->where("first_name||' '||last_name ilike '%'||:query||'%'", [':query' => $name])
                ->orderBy(['id' => SORT_ASC])
                ->all()


问:
Statement in Catch isn't executed
I need to fetch login details from my web service to authenticate login in my app. Below is the code which does the job.

```<code>      try {
                //Apache Libraries and namevaluepair has been deprecated since APK 21(?). Using HttpURLConnection instead.
                URL url = new URL(wsURL + authenticate);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

                OutputStream os = connection.getOutputStream();
                os.write(postParam.getBytes());
                os.flush();
                os.close();

                // Fetching the response code for debugging purposes.
                int responseCode = connection.getResponseCode();
                Log.d(TAG, "POST Response Code: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    //Adding every responseCode in the inputLine.
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    Log.d(TAG, "HTTP Response: " + response.toString());
                    //TODO: Check login logic again
                    //Sets Authentication flag
                    if (!response.toString().contains("Authentication Failed!")) {
                        authFlag = true;
                        Log.i(TAG, "Authentication Completed: Logged in Successfully!");
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            JSONArray jsonArray = jsonObject.getJSONArray("rows");
                            JSONObject beanObject = jsonArray.getJSONObject(0);

                            userBean = new UserBean(username, beanObject.getString("User_FullName"), beanObject.getInt("UserType_Code"));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Log.e(TAG, "Error!!! Abort!!!");
                }
                connection.disconnect();
            } catch (MalformedURLException e) {
                System.out.println("URLConnection Exception: " + e);
            } catch (IOException e) {
                System.out.println("IOStream Exception: " + e);
            }

            return postParam;
        }
</code>```

Issue I'm facing is I don't see anything related to it in my logcat but on debugging I find that the control goes to

} catch (MalformedURLException e) {

but
System.out.println("URLConnection Exception: " + e);
is never executed.
I'm novice at Android dev so there might be something which I can't see. Please help.

EDIT - I first tried with Log.e but it didn't work so I put System.out.println which didn't work either.

答:
just try

Log.e("tag","Exception: " + e);

and you can find it in android monitor

Title: Statement in Catch isn't executed

Body:
I need to fetch login details from my web service to authenticate login in my app. Below is the code which does the job.

      try {
                //Apache Libraries and namevaluepair has been deprecated since APK 21(?). Using HttpURLConnection instead.
                URL url = new URL(wsURL + authenticate);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

                OutputStream os = connection.getOutputStream();
                os.write(postParam.getBytes());
                os.flush();
                os.close();

                // Fetching the response code for debugging purposes.
                int responseCode = connection.getResponseCode();
                Log.d(TAG, "POST Response Code: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    //Adding every responseCode in the inputLine.
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    Log.d(TAG, "HTTP Response: " + response.toString());
                    //TODO: Check login logic again
                    //Sets Authentication flag
                    if (!response.toString().contains("Authentication Failed!")) {
                        authFlag = true;
                        Log.i(TAG, "Authentication Completed: Logged in Successfully!");
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            JSONArray jsonArray = jsonObject.getJSONArray("rows");
                            JSONObject beanObject = jsonArray.getJSONObject(0);

                            userBean = new UserBean(username, beanObject.getString("User_FullName"), beanObject.getInt("UserType_Code"));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Log.e(TAG, "Error!!! Abort!!!");
                }
                connection.disconnect();
            } catch (MalformedURLException e) {
                System.out.println("URLConnection Exception: " + e);
            } catch (IOException e) {
                System.out.println("IOStream Exception: " + e);
            }

            return postParam;
        }

Issue I'm facing is I don't see anything related to it in my logcat but on debugging I find that the control goes to

} catch (MalformedURLException e) {

but
System.out.println("URLConnection Exception: " + e);
is never executed.
I'm novice at Android dev so there might be something which I can't see. Please help.

EDIT - I first tried with Log.e but it didn't work so I put System.out.println which didn't work either.


问:
Babel with Gulp - How to set javascript file transpile order
In short I have an angular app and I want to use babel with gulp to transpile my .js files. However in the dist bundle.js it transpiles the controllers first and the module initiation afterwards. So I want babel to transpile .module.js files first and then .controller.js files. This way my code will be ordered correctly and controllers could be attached properly to modules. Here is my gulpfile.js:</p>

```<code>const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const concat = require('gulp-concat');

gulp.task('default', () => {
    return gulp.src('public/src/**/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(concat('bundle.js'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('public/dist'));
});
</code>```

答:
why not move the modules and controllers each in their own subfolders, and gulp.src each folder in order?

Use .src(['foo/', 'bar/']) to specify the order

Body:
In short I have an angular app and I want to use babel with gulp to transpile my .js files. However in the dist bundle.js it transpiles the controllers first and the module initiation afterwards. So I want babel to transpile .module.js files first and then .controller.js files. This way my code will be ordered correctly and controllers could be attached properly to modules. Here is my gulpfile.js:

const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const concat = require('gulp-concat');

gulp.task('default', () => {
    return gulp.src('public/src/**/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(concat('bundle.js'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('public/dist'));
});


答:
You should not use System.out,
instead use logging functions like logcat for debugging.

In this example, considering that the catch catches an error, you should use:

```<code>private static final String TAG = "MyActivity";
...
catch (MalformedURLException e) {
Log.e(TAG, "URLConnection Exception: " + e.getMessage());
                } catch (IOException e) {
Log.e(TAG, "IO error: " + e.getMessage());
                }
</code>```

Here is an explanation of how to use them properly.

If you can't see logcat, go there.

Title: Statement in Catch isn't executed

Body:
You should not use System.out,
instead use logging functions like logcat for debugging.

In this example, considering that the catch catches an error, you should use:

private static final String TAG = "MyActivity";
...
catch (MalformedURLException e) {
Log.e(TAG, "URLConnection Exception: " + e.getMessage());
                } catch (IOException e) {
Log.e(TAG, "IO error: " + e.getMessage());
                }

Here is an explanation of how to use them properly.

If you can't see logcat, go there.


问:
CodingBat Logic-1 > caughtSpeeding
Hi I'm new to Java and I need a little help.The problem is from coding bat:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

```<code> public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday = true){
       if (speed >=61 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday = false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }
</code>```

I'm getting caughtSpeeding(65, true) should be 0 when my code runs to = 1 and caughtSpeeding(85, false) should be 2 when my code runs to = 1 again.

Thanks

答:
For starters, this line:

```<code>if (isBirthday = true){
</code>```

should be changed to:

```<code>if (isBirthday == true){
</code>```

The equality operator that checks if two expressions are equal is == and not =. After fixing this, there's still something else you have to check in your code. Read the problem carefully again and make sure your logic is returning the correct output in all possible cases.

Title: CodingBat Logic-1 > caughtSpeeding

Body:
Hi I'm new to Java and I need a little help.The problem is from coding bat:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

 public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday = true){
       if (speed >=61 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday = false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }

I'm getting caughtSpeeding(65, true) should be 0 when my code runs to = 1 and caughtSpeeding(85, false) should be 2 when my code runs to = 1 again.

Thanks

Body:
For starters, this line:

if (isBirthday = true){

should be changed to:

if (isBirthday == true){

The equality operator that checks if two expressions are equal is == and not =. After fixing this, there's still something else you have to check in your code. Read the problem carefully again and make sure your logic is returning the correct output in all possible cases.


问:
Count the number of missing values in a dataframe Spark
I have a dataset with missing values , I would like to get the number of missing values for each columns. Following is what I did , I got the number of non missing values. How can I use it to get the number of missing values?

df.describe().filter($"summary" === "count").show
```
<pre class="lang-none prettyprint-override"><code>+-------+---+---+---+
|summary|  x|  y|  z|
+-------+---+---+---+
|  count|  1|  2|  3|
+-------+---+---+---+
</code>```

Any help please to get a dataframe in which we'll find columns and number of missing values for each one.

答:
You could count the missing values by summing the boolean output of the isNull() method, after converting it to type integer:

In Scala:

import org.apache.spark.sql.functions.{sum, col}
df.select(df.columns.map(c => sum(col(c).isNull.cast("int")).alias(c)): _*).show
```

<p>In <code>Python</code>:</p>

```from pyspark.sql.functions import col,sum
df.select(*(sum(col(c).isNull().cast("int")).alias(c) for c in df.columns)).show()
```

<p>Alternatively, you could also use the output of <code>df.describe().filter($"summary" === "count")</code>, and subtract the number in each cell by the number of rows in the data:</p>

<p>In <code>Scala</code>:</p>

<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions.lit,

val rows = df.count()
val summary = df.describe().filter($"summary" === "count")
summary.select(df.columns.map(c =>(lit(rows) - col(c)).alias(c)): _*).show
</code>```

In Python:

from pyspark.sql.functions import lit

rows = df.count()
summary = df.describe().filter(col("summary") == "count")
summary.select(*((lit(rows)-col(c)).alias(c) for c in df.columns)).show()
```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataset with missing values , I would like to get the number of missing values for each columns. Following is what I did , I got the number of non missing values. How can I use it to get the number of missing values?

df.describe().filter($"summary" === "count").show

+-------+---+---+---+
|summary|  x|  y|  z|
+-------+---+---+---+
|  count|  1|  2|  3|
+-------+---+---+---+

Any help please to get a dataframe in which we'll find columns and number of missing values for each one.

Body:
You could count the missing values by summing the boolean output of the isNull() method, after converting it to type integer:

In Scala:

import org.apache.spark.sql.functions.{sum, col}
df.select(df.columns.map(c => sum(col(c).isNull.cast("int")).alias(c)): _*).show

In Python:

from pyspark.sql.functions import col,sum
df.select(*(sum(col(c).isNull().cast("int")).alias(c) for c in df.columns)).show()

Alternatively, you could also use the output of df.describe().filter($"summary" === "count"), and subtract the number in each cell by the number of rows in the data:

In Scala:

import org.apache.spark.sql.functions.lit,

val rows = df.count()
val summary = df.describe().filter($"summary" === "count")
summary.select(df.columns.map(c =>(lit(rows) - col(c)).alias(c)): _*).show

In Python:

from pyspark.sql.functions import lit

rows = df.count()
summary = df.describe().filter(col("summary") == "count")
summary.select(*((lit(rows)-col(c)).alias(c) for c in df.columns)).show()


问:
get next immediate same date using php

i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

```<code>$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
</code>```

or

```<code>$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
</code>```

thanks in your advance

答:
Try this -

```<code><?php

$day = '05';
$today = date('Y-m-d');
$supplied = date('Y-m-'.$day);

if($today>$supplied){
    $final = date('Y-m-d', strtotime("+1 months", strtotime($supplied)));
}
else{
    $final = $supplied;
}

echo $today;
echo '<br />';
echo $supplied;
echo '<br />';
echo $final;
</code>```

What I'm doing here -

Comparing the current and supplied date

Based on comparison, if supplied date is smaller, I'm adding 1 month else dislpaying the supplied date.

Title: get next immediate same date using php

Body:
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));

or

$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

thanks in your advance

Body:
Try this -

<?php

$day = '05';
$today = date('Y-m-d');
$supplied = date('Y-m-'.$day);

if($today>$supplied){
    $final = date('Y-m-d', strtotime("+1 months", strtotime($supplied)));
}
else{
    $final = $supplied;
}

echo $today;
echo '<br />';
echo $supplied;
echo '<br />';
echo $final;

What I'm doing here -

Comparing the current and supplied date

Based on comparison, if supplied date is smaller, I'm adding 1 month else dislpaying the supplied date.


问:
DOM HTMLElement className property when the element has no class name set
When you have an HTML element with no class name set, what is the value of HTMLElement className property? My first thought was that it is undefined, but I found out that in FF it is just an empty string. My question is - can I rely on this behavior in all current and future browsers? Is that part of some specification or is it just another browser trick to avoid errors in badly written code?</p>

答:
```<code>interface HTMLElement : Element {
           attribute  DOMString            id;
           attribute  DOMString            title;
           attribute  DOMString            lang;
           attribute  DOMString            dir;
           attribute  DOMString            className;
};
</code>```

— http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html

And also see the definition of DOMString.

So it should be safe.

Body:
interface HTMLElement : Element {
           attribute  DOMString            id;
           attribute  DOMString            title;
           attribute  DOMString            lang;
           attribute  DOMString            dir;
           attribute  DOMString            className;
};

— http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html

And also see the definition of DOMString.

So it should be safe.


答:
Change your isBirthday if statements slightly.

```<code>= // 'make this left-side value equal something'.
== // 'comparison of two values'
</code>```

so for isBirthday you could have

```<code>if(isBirthday) // is 'isBirthday' true?
if(isBirthday == true) // same as above

if(!isBirthday) // is 'isBirthday' not true (false)?
if(isBirthday == false) // same as above
</code>```

Title: CodingBat Logic-1 > caughtSpeeding

Body:
Change your isBirthday if statements slightly.

= // 'make this left-side value equal something'.
== // 'comparison of two values'

so for isBirthday you could have

if(isBirthday) // is 'isBirthday' true?
if(isBirthday == true) // same as above

if(!isBirthday) // is 'isBirthday' not true (false)?
if(isBirthday == false) // same as above


问:
Can I use getElementById to select and hide content that does not have the id specified?
For example, I have this function.

```<code>function showprintdiv() {
    var x = document.getElementById('post-Print ');
    if (!x.style.display || x.style.display == 'block') {
        x.style.display = 'none';
    } else {
        x.style.display = 'block';
}
</code>```

I have this function 7 times with 8 sections that have an ID which is generated via

```<code><div id="post-<?php
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo $tag->name . ' ';
        }
    }
?>" class="col-md-4 no-pad containerhover">
</code>```

Currently when I click a button, it hides or shows the content of post-Print

I want it to hide/show the content of the 7 other sections I have, so post-Print is there all the time.

I think there should be some way to hide every DIV with a class except for if they have the specified ID.

答:
First of all, HTML id attributes should not contain any spaces, so you'll need to adapt your PHP code for that. It is necessary before the following will work:

Focussing on your question: if you want to get to all the post- elements, except one particular one, post-Print, then use querySelectorAll with a smart CSS selector [id^=post-]:not(#post-Print).

Here is a demo:

function showprintdiv() {
    // Iterate over all elements that have an id that starts with "post-",
    // except the one you want to keep visible:
    var elems = document.querySelectorAll('[id^=post-]:not(#post-Print)');
    Array.from(elems, function (x) {
        if (x.id == 'post-Print') return; // don't touch this one.
        x.style.display = (!x.style.display || x.style.display == 'block')
            ? 'none' : 'block';
    });
}

// Demo: toggle visibility every half second:
setInterval(showprintdiv,  500);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="post-Print" class="col-md-4 no-pad containerhover">post-Print</div>
<div id="post-1"     class="col-md-4 no-pad containerhover">post-1</div>
<div id="post-2"     class="col-md-4 no-pad containerhover">post-2</div>
<div id="post-3"     class="col-md-4 no-pad containerhover">post-3</div></code>```

Body:
For example, I have this function.

function showprintdiv() {
    var x = document.getElementById('post-Print ');
    if (!x.style.display || x.style.display == 'block') {
        x.style.display = 'none';
    } else {
        x.style.display = 'block';
}

I have this function 7 times with 8 sections that have an ID which is generated via

<div id="post-<?php
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo $tag->name . ' ';
        }
    }
?>" class="col-md-4 no-pad containerhover">

Currently when I click a button, it hides or shows the content of post-Print

I want it to hide/show the content of the 7 other sections I have, so post-Print is there all the time.

I think there should be some way to hide every DIV with a class except for if they have the specified ID.

Body:
First of all, HTML id attributes should not contain any spaces, so you'll need to adapt your PHP code for that. It is necessary before the following will work:

Focussing on your question: if you want to get to all the post- elements, except one particular one, post-Print, then use querySelectorAll with a smart CSS selector [id^=post-]:not(#post-Print).

Here is a demo:

function showprintdiv() {
    // Iterate over all elements that have an id that starts with "post-",
    // except the one you want to keep visible:
    var elems = document.querySelectorAll('[id^=post-]:not(#post-Print)');
    Array.from(elems, function (x) {
        if (x.id == 'post-Print') return; // don't touch this one.
        x.style.display = (!x.style.display || x.style.display == 'block')
            ? 'none' : 'block';
    });
}

// Demo: toggle visibility every half second:
setInterval(showprintdiv,  500);

<div id="post-Print" class="col-md-4 no-pad containerhover">post-Print</div>
<div id="post-1"     class="col-md-4 no-pad containerhover">post-1</div>
<div id="post-2"     class="col-md-4 no-pad containerhover">post-2</div>
<div id="post-3"     class="col-md-4 no-pad containerhover">post-3</div>


问:
selec2 search - Return no results found message if a specific criteria didnt match
I am using select2 4.0.3 for search drop down. As per my understanding its default functionality is not to match with the start of entries the drop down have. So I have implemented the below given code

```<code>function matchStart(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return false;
}

$("select").select2({
    placeholder : "Input country name or select region",
    matcher : function (params, data) {
        return matchStart(params, data);
    },
});
</code>```

My problem is, the dropdown is not showing "No results found" message even if there is no matching results found. Can anyone help me on this.

Thanks in advance.

答:
Try changing the return value of matchStart from false to null.

Also you can remove the extra function around the matcher argument. The result:

```<code>function matchStart(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return null;
}

$("select").select2({
    placeholder: "Input country name or select region",
    matcher: matchStart
});
</code>```

Body:
I am using select2 4.0.3 for search drop down. As per my understanding its default functionality is not to match with the start of entries the drop down have. So I have implemented the below given code

function matchStart(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return false;
}

$("select").select2({
    placeholder : "Input country name or select region",
    matcher : function (params, data) {
        return matchStart(params, data);
    },
});

My problem is, the dropdown is not showing "No results found" message even if there is no matching results found. Can anyone help me on this.

Thanks in advance.

Body:
Try changing the return value of matchStart from false to null.

Also you can remove the extra function around the matcher argument. The result:

function matchStart(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return null;
}

$("select").select2({
    placeholder: "Input country name or select region",
    matcher: matchStart
});


问:
How to launch RDP Session using asp.net
I want to launch Remote Desktop using my ASP.net website. I have tried using .RDP file and use Process class to launch it using MSTSC.exe but I am unable to open the session. So please let me know how can I do that ?

Thanks
Laxmilal

答:
You can try the approach described by JJ Clements.

Basically it involves updating the registry on the browser machine, to support an rdp:// url scheme.  Then, when you click on a link like rdp://foo, or when you key in rdp://foo into the browser address bar, it opens MSTSC.exe on the browser machine.

Title: How to launch RDP Session using asp.net