问:
Null memory address when passing variables between functions without pointers in C++?
When I compile a program in XCode, I get a "Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)" error that points to the variables I am passing between functions.

In questions I have seen on Stack Overflow relating to this subject, I've seen errors where pointers and references were improperly used in functions, returning a memory location of "0", but I'm not using pointers or references, just a variable which was declared with global scope.

Would it be better to use pointers here?

My program is trying to split an array of input in half and then print them out side-by-side. I use one int function and two string functions that accept int arguments and exit with return 0;

Is there a particular problem with passing variables declared outside of a function between functions? I have tried using pointers and references, but these return the same memory address error.

EDIT: The problem was using return 0; for functions defined as strings. I changed the function type to void and simply used return; to exit the function. The memory access problem was fixed afterwards.

答: The return value matching the defined type of function was the correct answer, provided by @RemyLebeau and @BoPerrsson.</p>


来源: stackexchange

问:
Strange chevrons in tabled data in IE and Edge
I am seeing chevrons in my tables to the right of the data before the border.

The css has no images or nothing out of the ordinary either, could it be a javascript issue, jquery or something?
I am not sure what to post here, Here is a sample of the html:

```<code><table cellpadding="0" cellspacing="0" border="0" class="datatable table table-striped table-bordered">
        <thead>
            <tr>
                <th>xxxxxxxxxx</th>
                <th>xxxxxxxxxxx</th>
                <th>xxxxxxxxxx</th>
                <th>xxxxxxxxx</th>
                <th>xxxxxxxx</th>
                <th>xxxxxx</th>
            </tr>
        </thead>

        <tbody>
                        <tr class="gradeX">
                <td>xxxxxxxx</td>
                <td>xxxxxx</td>
                <td>xxxxxxxxx</td>
                <td>xxxxxxxx</td>
                <td>xxxxxxxx</td>

                <td>xxxxxxxxxxx</td>
            </tr>
</code>```

Thanks in advance, not sure what else to post, please advise

答:
Its hard for me to know specifically what the issue looks like with these fixes because I dont have IE but from the experience I have had with IE these few things might fix the issue...

1) It could be that you haven't specified a DOCTYPE.

Without a doctype, IE will start all kinds of rendering glitches. To fix this problem, simply add a valid doctype to the top of the page, before the  tag.

If you're not sure which doctype to use, use the HTML5 doctype - it's as simple as this:

```<code><!DOCTYPE html>
</code>```

2) It could also possibly be overflow issue. If there is too much data in a cell IE might try to add the scrollbar so try:

```<code>table {
    overflow: hidden;
}
</code>```

3) If it is an overflow issue and the above didnt work, it can be common that tables exceed the width they are given so this can fix that:

```<code>table{
  table-layout:fixed;
}
</code>```

Documentation on this is here

ContentLicense: CC BY-SA 3.0

Body:
I am seeing chevrons in my tables to the right of the data before the border.

The css has no images or nothing out of the ordinary either, could it be a javascript issue, jquery or something?
I am not sure what to post here, Here is a sample of the html:

                xxxxxxxxxx
                xxxxxxxxxxx
                xxxxxxxxxx
                xxxxxxxxx
                xxxxxxxx
                xxxxxx

                xxxxxxxx
                xxxxxx
                xxxxxxxxx
                xxxxxxxx
                xxxxxxxx

                xxxxxxxxxxx

Thanks in advance, not sure what else to post, please advise

Body:
Its hard for me to know specifically what the issue looks like with these fixes because I dont have IE but from the experience I have had with IE these few things might fix the issue...

1) It could be that you haven't specified a DOCTYPE.

Without a doctype, IE will start all kinds of rendering glitches. To fix this problem, simply add a valid doctype to the top of the page, before the <html> tag.

If you're not sure which doctype to use, use the HTML5 doctype - it's as simple as this:

<!DOCTYPE html>

2) It could also possibly be overflow issue. If there is too much data in a cell IE might try to add the scrollbar so try:

table {
    overflow: hidden;
}

3) If it is an overflow issue and the above didnt work, it can be common that tables exceed the width they are given so this can fix that:

table{
  table-layout:fixed;
}

Documentation on this is here


问:
ImageMagick Montage With Exiftool output as -label
I am working on creating contact sheets with Image Magick's montage command. I would like to include particular meta data as the -label for the contact sheet images. I am pulling the data using exiftool:

```<code>$creator = C:\exiftool.exe "-Creator" $image
</code>```

and creating the montage like so:

```<code>montage -verbose -label %t_$creator -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImages.FullName E:\Contact_Sheet.jpg
</code>```

However, I run into an issue of the -label containing the creator for ALL the files in the directory $dailyImages instead of the creator for each respective file.

Is anyone able to use the exiftool command to pull a single file's 'creator' and pipe it into the montage command so the respective image on the contact sheet as $filename_$creator. (In case you are unfamiliar, the %t in -label %t_$creator is built in to Image Magick to provide the filename as the -label)

答:
Given what I said above, if you want some EXIF data that ImageMagick supports, then you can do for example:

```<code>montage -label "%t %[EXIF:make]" input.jpg output.jpg
</code>```

I have tested that and it works on an image I have.

This also works for me on ImageMagick 6.9.9.23 Q16 Mac OSX.

```<code>make=`convert input.jpg -format "%[EXIF:make]" info:`
montage -label "%t $make" input.jpg output.jpg
</code>```

This also works for me:

```<code>make=`exiftool -make input.jpg | sed 's/ *//g' | cut -d: -f2`
montage -label "%t $make" input.jpg output.jpg
</code>```

So everything seems to point to the lack of a Creator field in EXIF data.

ContentLicense: CC BY-SA 4.0

Body:
I am working on creating contact sheets with Image Magick's montage command. I would like to include particular meta data as the -label for the contact sheet images. I am pulling the data using exiftool:

$creator = C:\exiftool.exe "-Creator" $image

and creating the montage like so:

montage -verbose -label %t_$creator -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImages.FullName E:\Contact_Sheet.jpg

However, I run into an issue of the -label containing the creator for ALL the files in the directory $dailyImages instead of the creator for each respective file.

Is anyone able to use the exiftool command to pull a single file's 'creator' and pipe it into the montage command so the respective image on the contact sheet as $filename_$creator. (In case you are unfamiliar, the %t in -label %t_$creator is built in to Image Magick to provide the filename as the -label)

Body:
Given what I said above, if you want some EXIF data that ImageMagick supports, then you can do for example:

montage -label "%t %[EXIF:make]" input.jpg output.jpg

I have tested that and it works on an image I have.

This also works for me on ImageMagick 6.9.9.23 Q16 Mac OSX.

make=`convert input.jpg -format "%[EXIF:make]" info:`
montage -label "%t $make" input.jpg output.jpg

This also works for me:

make=`exiftool -make input.jpg | sed 's/ *//g' | cut -d: -f2`
montage -label "%t $make" input.jpg output.jpg

So everything seems to point to the lack of a Creator field in EXIF data.


问:
Query with multiple EXIST
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

```<code>select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
</code>```

Is there any way to optimize or making this shorter?

答:
To shorten you could

```<code>select *
from rooms r
where @N = (select count(distinct eq_id)
            from equipments
            where eq_id IN ('eq1','eq2',...,'eqN') and room_id=r.id)
</code>```

EDIT
but not sure if it will actually make it faster... quite the opposite, the version with EXISTS AND EXISTS has a chance to prune execution branch on the first false, the above must actually count the distinct values (go through all records) and see what that value is.

So you should think what is faster:

going once through all records related to a room (one correlated subquery) or

running N (worst case) correlated (but highly selective subqueries) for each room

It depends on the statistics of your data (I would think that if most rooms don't have all the sought equipment in them then your initial version should be faster, if most rooms have all equipment in them then the proposed version might perform better; also if the EXISTS version is faster make an effort to first the queries that are most likely to fail i.e. first check for rarest equipment)

You can also try a version with GROUP BY

```<code>select r.*
from rooms r join
     equipments e on r.id = e.room_id
group by r.id
where eg_id in ('eq1','eq2',...,'eqN')
having count(distinct e.eq_id) = @N
</code>```

(above SQL not tested)

ContentLicense: CC BY-SA 2.5

Title: Query with multiple EXIST

Body:
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)

Is there any way to optimize or making this shorter?

Body:
To shorten you could

select *
from rooms r
where @N = (select count(distinct eq_id)
            from equipments
            where eq_id IN ('eq1','eq2',...,'eqN') and room_id=r.id)

EDIT
but not sure if it will actually make it faster... quite the opposite, the version with EXISTS AND EXISTS has a chance to prune execution branch on the first false, the above must actually count the distinct values (go through all records) and see what that value is.

So you should think what is faster:

going once through all records related to a room (one correlated subquery) or

running N (worst case) correlated (but highly selective subqueries) for each room

It depends on the statistics of your data (I would think that if most rooms don't have all the sought equipment in them then your initial version should be faster, if most rooms have all equipment in them then the proposed version might perform better; also if the EXISTS version is faster make an effort to first the queries that are most likely to fail i.e. first check for rarest equipment)

You can also try a version with GROUP BY

select r.*
from rooms r join
     equipments e on r.id = e.room_id
group by r.id
where eg_id in ('eq1','eq2',...,'eqN')
having count(distinct e.eq_id) = @N

(above SQL not tested)


问:
Get Guid lookup table from custome Field in Microsoft Project Online
in this case i have custome field namely "Project Phase" then in value based on Lookup Table.

how can i get guid or internal name like 'Entry_d4399450ea69e61180cb00155d18530e' based on Delay value that appear in above image. this internal name i will use for updating data using C# Console.

here my simple code, but it doesn't VALID:

```<code>var PrjList = projContext.LoadQuery(projContext.CustomFields.Where(proj => proj.Name == cFieldName));
projContext.ExecuteQuery();
Guid pGuid = PrjList.First().Id;

Console.WriteLine(pGuid);
</code>```

答:
i finally i got simple linq query in ms project to get internal name of lookup based on custome field. here is my codeand it worked:

```<code>var InternalNameLookup = pubProj.CustomFields.LookupEntries.Where(x => x.FullValue == "Delay").First().InternalName;
</code>```

this code will display internal name "Entry_d4399450ea69e61180cb00155d18530e". this is that i need to update my custome field based on lookup field.

Body:
in this case i have custome field namely "Project Phase" then in value based on Lookup Table.

how can i get guid or internal name like 'Entry_d4399450ea69e61180cb00155d18530e' based on Delay value that appear in above image. this internal name i will use for updating data using C# Console.

here my simple code, but it doesn't VALID:

var PrjList = projContext.LoadQuery(projContext.CustomFields.Where(proj => proj.Name == cFieldName));
projContext.ExecuteQuery();
Guid pGuid = PrjList.First().Id;

Console.WriteLine(pGuid);

Body:
i finally i got simple linq query in ms project to get internal name of lookup based on custome field. here is my codeand it worked:

var InternalNameLookup = pubProj.CustomFields.LookupEntries.Where(x => x.FullValue == "Delay").First().InternalName;

this code will display internal name "Entry_d4399450ea69e61180cb00155d18530e". this is that i need to update my custome field based on lookup field.


问:
send_file vs html5 download attribute
It looks like the HTML5 download attribute is supported on every browser now, and I was wondering if there are any advantages/disadvantages to using this instead of creating a link and using send_file in a controller with Rails.

答:
send_file is both more versatile and more efficient.

Its main advantage is that it uses the X-Sendfile response header. What that does is offload the streaming process of the file from Ruby to the server (e.g. Nginx or Apache) which is optimized for high-throughput content delivery.

Plain 'download' links save the target regardless of what's displayed on it. This could be a problem if, for example, the target is session-protected, and the session expires before you click the link. You'd end up saving the login page without knowing it. With send_file you can dynamically initiate the download if the session is ok, or redirect to the login page otherwise.

send_file also lets you specify a meaningful file name dynamically, so if your link points to, say, /users/42, you could set the download name to be "John Smith.csv" instead of the cryptic "42".

Title: send_file vs html5 download attribute


问:
Is it possible to have comments in Log4J2 JSON configuration
I have log4j2 configured using JSON format, e.g.:

```<code>{
  "configuration": {
    "monitorInterval": 60,
    "properties": {
      ...
    },
    "appenders": {
      ...
    },

    "loggers": {
      "asyncRoot": {
        ...
</code>```

etc.
The configuration is quite complex, so it requires some clarifications for whoever attempts to understand or change it in the future.

If this configuration was in XML, I could specify comments clarifying each section right in the configuration (changing my configuration to XML is not an option). But JSON doesn't have comments as a concept, and  recommendation is to specify comments as data. E.g.:

```<code>{
  "configuration": {
    "monitorInterval": 60,
    "_comment_": "here we go",
    "properties": {
</code>```

But I'm not sure if something like that is a good idea in log4j2 case: instead of making configuration more clear, it actually adds a bulk to it, such comments are not clearly separated from actual data, and I am not sure if it will cause any stability / performance issues parsing configuration (as you can see, this configuration is parsed every 60 sec, so...)

Is there any common / recommended approach to describe the configuration with log4j2?
Or did you successfully test/use the above approach (comments as data)?

Thanks in advance.

答:
Additional information: Log4J2 enables comments explicitly in JsonConfiguration implementation:

```<code>protected ObjectMapper getObjectMapper() {
    return new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true);
}
</code>```

It refers to a property from com.fasterxml.jackson.core, which describes details on which comments are supported and why:

```<code>/**
* Feature that determines whether parser will allow use
* of Java/C++ style comments (both '/'+'*' and
* '//' varieties) within parsed content or not.
*<p>
* Since JSON specification does not mention comments as legal
* construct,
* this is a non-standard feature; however, in the wild
* this is extensively used. As such, feature is
* <b>disabled by default</b> for parsers and must be
* explicitly enabled.
*/
ALLOW_COMMENTS(false)
</code>```

Feature is not documented anywhere in Log4J, also notice that by default Jackson has it disabled.

Body:
I have log4j2 configured using JSON format, e.g.:

{
  "configuration": {
    "monitorInterval": 60,
    "properties": {
      ...
    },
    "appenders": {
      ...
    },

    "loggers": {
      "asyncRoot": {
        ...

etc.
The configuration is quite complex, so it requires some clarifications for whoever attempts to understand or change it in the future.

If this configuration was in XML, I could specify comments clarifying each section right in the configuration (changing my configuration to XML is not an option). But JSON doesn't have comments as a concept, and  recommendation is to specify comments as data. E.g.:

{
  "configuration": {
    "monitorInterval": 60,
    "_comment_": "here we go",
    "properties": {

But I'm not sure if something like that is a good idea in log4j2 case: instead of making configuration more clear, it actually adds a bulk to it, such comments are not clearly separated from actual data, and I am not sure if it will cause any stability / performance issues parsing configuration (as you can see, this configuration is parsed every 60 sec, so...)

Is there any common / recommended approach to describe the configuration with log4j2?
Or did you successfully test/use the above approach (comments as data)?

Thanks in advance.

Body:
Additional information: Log4J2 enables comments explicitly in JsonConfiguration implementation:

protected ObjectMapper getObjectMapper() {
    return new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true);
}

It refers to a property from com.fasterxml.jackson.core, which describes details on which comments are supported and why:

/**
* Feature that determines whether parser will allow use
* of Java/C++ style comments (both '/'+'*' and
* '//' varieties) within parsed content or not.
*<p>
* Since JSON specification does not mention comments as legal
* construct,
* this is a non-standard feature; however, in the wild
* this is extensively used. As such, feature is
* <b>disabled by default</b> for parsers and must be
* explicitly enabled.
*/
ALLOW_COMMENTS(false)

Feature is not documented anywhere in Log4J, also notice that by default Jackson has it disabled.


问:
mocking injected class method
I have a Gateway class that has contains an instance of a Resource class.  I've already done my unit testing on Resource, and to simplify testing, Resource is injected into Gateway as a dependency at initialization:

```<code>class Gateway:

  def __init__(self, resource):
    self._resource = resource(Master)

  def list_things(self):
    return self._resource.list_resource()
</code>```

Now I'd like write unit test for Gateway to verify that resource.list_resource() gets called as a result of calling gateway.list_things().  My best attempt doesn't work:

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

    def test_list_things(self):
        mock_resource = Mock()
        g = modbus.gateway.Gateway(mock_resource)
        g.list_things()
        mock_resource.list_resource.assert_called_once()
</code>```

The result:

```<code>AssertionError: Expected 'list_resource' to have been called once. Called 0 times.
</code>```

What am I missing?

答:
In the actual use case of the mock_resource that you passed into Gateway for your test case, the constructor in Gateway actually makes a further call to the resource argument as a constructor, so that what the test expects is actually emulating the checking of the call against the class method, not the instance method of the mock_resource.  Demonstrating this using just the minimum number of statements can be done using the following:

```<code>>>> mock_resource = Mock()
>>> self_resource = mock_resource('Master')  # emulate Gateway.__init__
>>> self_resource.list_resource()            # emulate Gateway.list_things
<Mock name='mock().list_resource()' id='140441464498496'>
>>> mock_resource.list_resource.assert_called_once()  # test_list_things
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/unittest/mock.py", line 795, in assert_called_once
    raise AssertionError(msg)
AssertionError: Expected 'list_resource' to have been called once. Called 0 times.
>>> self_resource.list_resource.assert_called_once()  # test the _actual_ call
>>>
</code>```

Note that I had assigned self_resource to emulate the self._resource = resource(Master) statement in the constructor for Resource, and the mismatching of the test vs. what is actually executed should now be apparent.

To fix this, the test should check the call like so:

```<code>    def test_list_things(self):
        mock_resource = Mock()
        g = modbus.gateway.Gateway(mock_resource)
        g.list_things()
        # mock_resource.list_resource.assert_called_once()
        g._resource.list_resource.assert_called_once()
</code>```

Title: mocking injected class method

Body:
I have a Gateway class that has contains an instance of a Resource class.  I've already done my unit testing on Resource, and to simplify testing, Resource is injected into Gateway as a dependency at initialization:

class Gateway:

  def __init__(self, resource):
    self._resource = resource(Master)

  def list_things(self):
    return self._resource.list_resource()

Now I'd like write unit test for Gateway to verify that resource.list_resource() gets called as a result of calling gateway.list_things().  My best attempt doesn't work:

class TestGateway(unittest.TestCase):

    def test_list_things(self):
        mock_resource = Mock()
        g = modbus.gateway.Gateway(mock_resource)
        g.list_things()
        mock_resource.list_resource.assert_called_once()

The result:

AssertionError: Expected 'list_resource' to have been called once. Called 0 times.

What am I missing?

Body:
In the actual use case of the mock_resource that you passed into Gateway for your test case, the constructor in Gateway actually makes a further call to the resource argument as a constructor, so that what the test expects is actually emulating the checking of the call against the class method, not the instance method of the mock_resource.  Demonstrating this using just the minimum number of statements can be done using the following:

>>> mock_resource = Mock()
>>> self_resource = mock_resource('Master')  # emulate Gateway.__init__
>>> self_resource.list_resource()            # emulate Gateway.list_things
<Mock name='mock().list_resource()' id='140441464498496'>
>>> mock_resource.list_resource.assert_called_once()  # test_list_things
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/unittest/mock.py", line 795, in assert_called_once
    raise AssertionError(msg)
AssertionError: Expected 'list_resource' to have been called once. Called 0 times.
>>> self_resource.list_resource.assert_called_once()  # test the _actual_ call
>>>

Note that I had assigned self_resource to emulate the self._resource = resource(Master) statement in the constructor for Resource, and the mismatching of the test vs. what is actually executed should now be apparent.

To fix this, the test should check the call like so:

    def test_list_things(self):
        mock_resource = Mock()
        g = modbus.gateway.Gateway(mock_resource)
        g.list_things()
        # mock_resource.list_resource.assert_called_once()
        g._resource.list_resource.assert_called_once()


问:
Get any key from keyboard in C++ including keys like control
I'm programming in C++ and have run into a wall.

I need to get input from the keyboard.  The problem is that I also need to get input from keys like control, scroll lock, windows key, etc.  I also need to be able to differentiate between the numpad and regular numbers 0-9.

I tried using _getch().  While it can get keys like arrow keys and the numpad, I can't get keys like control, shift and scroll lock.

Does anyone have any suggestions?

答:
I see the word "windows key" so I'm assuming you're programming for Windows

Use WinAPI ReadConsoleInput

```<code>HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD ir;
DWORD read;
if (!ReadConsoleInput(hInput, &ir, 1, &read) || read == 0) {
    // Something went wrong
}
if (ir.EventType == KEY_EVENT) {
    // Do stuff here
}
</code>```

Refer to KEY_EVENT_RECORD for more information. You can get control keys states from

```<code>ir.Event.KeyEvent.dwControlKeyState
</code>```

This is an example provided by Microsoft.

Body:
I see the word "windows key" so I'm assuming you're programming for Windows

Use WinAPI ReadConsoleInput

HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD ir;
DWORD read;
if (!ReadConsoleInput(hInput, &ir, 1, &read) || read == 0) {
    // Something went wrong
}
if (ir.EventType == KEY_EVENT) {
    // Do stuff here
}

Refer to KEY_EVENT_RECORD for more information. You can get control keys states from

ir.Event.KeyEvent.dwControlKeyState

This is an example provided by Microsoft.


问:
How to run a VSTS build definition sequence locally without pushing to the repo
Is there a way to run the sequence of a build definition locally, without having to push changes to the repository and have the build trigger?

Currently, I have a simple build definition with only a couple of steps that I can run manually, but I plan on adding more steps to the sequence and ideally would like to run them all at once.

Similar question: Drone.io build locally without pushing to the repo

答:
If you need to build your project locally without pushing to a remote repository, the tasks in the VSTS build definition can not be used. You need to build each steps manually by the related CLI or related software.

Assume in your VSTS build definition, there is the tasks as below:

NuGet restore

Visual Studio Build

In order to build locally, you need to use execute the below steps manually:

Use the NuGet CLI, nuget.exe /path/to/project restore to work as the NuGet restore step in VSTS build.

Use the MSBuild CLI, msbuild /path/to/project [arguments] or build in Visual Studio to work as Visual Studio Build step in VSTS build.


问:
Trying to setup elasticsearch cluster with docker-compose
My environment is two physical machine, both running in docker-compose.

I want to create elasticsearch cluster cross two docker container.

My architecture like this

two container can't connected each other, any ideas?

docker image is using elasticsearch:5.4.2

docker-compose.yml

```<code>version: '2'

services:
  elasticsearch:
    image: es:542
    hostname: es2
    container_name: es2
    user: elasticsearch
    ports:
    - 9200:9200
    - 9300:9300
    environment:
    - ES_JAVA_OPTS=-Xms1g -Xmx1g
    command: /usr/share/elasticsearch/bin/elasticsearch
</code>```

elasticsearch.yml

```<code>http.host: 0.0.0.0
transport.host: 0.0.0.0
discovery.zen.minimum_master_nodes: 2

cluster.name: prod_es_cluster
node.name: prod_es_node1
node.master: true
node.data: true
discovery.zen.ping_timeout: 10s

network.host: 0.0.0.0
network.bind_host: 0.0.0.0
network.publish_host: 0.0.0.0
transport.tcp.port: 9300
discovery.zen.ping.unicast.hosts: ["127.0.0.1", "[::1]"]
</code>```

and logs

```<code>ES1
</code>```

[2017-11-09T05:56:10,552][INFO ][o.e.t.TransportService ] [prod_es_node1] publish_address {172.24.0.2:9300}, bound_addresses {[::]:9300}
[2017-11-09T05:56:10,558][INFO ][o.e.b.BootstrapChecks ] [prod_es_node1] bound or publishing to a non-loopback or non-link-local address,enforcing bootstrap checks
[2017-11-09T05:56:40,576][WARN ][o.e.n.Node ][prod_es_node1]timed out while waiting for initial discovery state - timeout: 30s
[2017-11-09T05:56:40,584][INFO ][o.e.h.n.Netty4HttpServerTransport] [prod_es_node1] publish_address {172.24.0.2:9200}, bound_addresses {[::]:9200}
[2017-11-09T05:56:40,587][INFO ][o.e.n.Node ] [prod_es_node1] started

```<code>ES2
</code>```

[2017-11-09T09:37:20,084][WARN ][o.e.d.z.ZenDiscovery ] [prod_es_node2]failed to connect to master [{prod_es_node1}{BxKzhOnJTUC50cYTz_Hm fA}{zqtU07jfQJOrmB9AYL01Ig}{172.24.0.2}{172.24.0.2:9300}], retrying...
org.elasticsearch.transport.ConnectTransportException:[prod_es_node1][172.24.0.2:9300] connect_timeout[30s]
at org.elasticsearch.transport.netty4.Netty4Transport.connectToChannels(Netty4Transport.java:361) ~[?:?]
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:549) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TcpTransport.connectToNode(TcpTransport.java:473) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:315) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:302) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:468) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:420) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4100(ZenDiscovery.java:83) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1197) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.4.2.
jar:5.4.2]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_131]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_131]
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException:Connection refused: 172.24.0.2/172.24.0.2:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[?:?]

答:
Now I use openvswitch and pipework to build cluster network

ovs setting:

```<code>#ES1
sudo brctl addbr br0
sudo ip link set dev br0 up
sudo ovs-vsctl add-br ovs0
sudo ovs-vsctl set bridge ovs0 stp_enable=true
sudo ovs-vsctl add-port ovs0 br0
sudo ovs-vsctl add-port ovs0 gre0 -- set interface gre0 type=gre options:remote_ip=10.251.34.50
</code>```

pipwork setting:

```<code>sudo pipework-master/pipework br0 -i eth1 es1 172.28.0.2/8
</code>```

docker container network information:

elasticsearch@es1:/usr/share/elasticsearch$ ip a

521: eth1@if522:  mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 4e:06:91:91:1f:3e brd ff:ff:ff:ff:ff:ff
    inet 172.28.0.2/8 brd 172.255.255.255 scope global eth1
       valid_lft forever preferred_lft forever

after setting both two docker container, cluster should be work !!

ES1

```<code>elasticsearch@es1:/usr/share/elasticsearch$ ping 172.18.0.2
PING 172.18.0.2 (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=1.222 ms
64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.339 ms
64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.547 ms
64 bytes from 172.18.0.2: icmp_seq=3 ttl=64 time=0.303 ms
64 bytes from 172.18.0.2: icmp_seq=4 ttl=64 time=0.333 ms
64 bytes from 172.18.0.2: icmp_seq=5 ttl=64 time=0.362 ms`
</code>```

ES logs:

```<code>[2017-11-17T02:06:21,205][INFO ][o.e.n.Node               ] [prod_es_node1] started
[2017-11-17T02:06:21,223][INFO ][o.e.c.s.ClusterService   ] [prod_es_node1] new_master {prod_es_node1}{IoG7C5BYQ26AYsggMuJo2A}{AL3oD0itR1CgibIr-x-8Sg}{172.28.0.2}{172.28.0.2:9300}, reason: zen-disco-elected-as-master ([0] nodes joined)
[2017-11-17T02:06:21,254][INFO ][o.e.g.GatewayService     ] [prod_es_node1] recovered [0] indices into cluster_state
[2017-11-17T02:06:29,205][INFO ][o.e.c.s.ClusterService   ] [prod_es_node1] added {{prod_es_node2}{ZA7CwKyBQS2gm-OamVSz2g}{U6WQyzwoQCiDkwBvmUxoQw}{172.18.0.2}{172.18.0.2:9300},}, reason: zen-disco-node-join[{prod_es_node2}{ZA7CwKyBQS2gm-OamVSz2g}{U6WQyzwoQCiDkwBvmUxoQw}{172.18.0.2}{172.18.0.2:9300}]`
</code>```

TEST

```<code>curl localhost:9200/_cluster/health?pretty
{
  "cluster_name" : "prod_es_cluster",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 2,
  "number_of_data_nodes" : 2,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0
}
</code>```

Body:
My environment is two physical machine, both running in docker-compose.

I want to create elasticsearch cluster cross two docker container.

My architecture like this

two container can't connected each other, any ideas?

docker image is using elasticsearch:5.4.2

docker-compose.yml

version: '2'

services:
  elasticsearch:
    image: es:542
    hostname: es2
    container_name: es2
    user: elasticsearch
    ports:
    - 9200:9200
    - 9300:9300
    environment:
    - ES_JAVA_OPTS=-Xms1g -Xmx1g
    command: /usr/share/elasticsearch/bin/elasticsearch

elasticsearch.yml

http.host: 0.0.0.0
transport.host: 0.0.0.0
discovery.zen.minimum_master_nodes: 2

cluster.name: prod_es_cluster
node.name: prod_es_node1
node.master: true
node.data: true
discovery.zen.ping_timeout: 10s

network.host: 0.0.0.0
network.bind_host: 0.0.0.0
network.publish_host: 0.0.0.0
transport.tcp.port: 9300
discovery.zen.ping.unicast.hosts: ["127.0.0.1", "[::1]"]

and logs

ES1

[2017-11-09T05:56:10,552][INFO ][o.e.t.TransportService ] [prod_es_node1] publish_address {172.24.0.2:9300}, bound_addresses {[::]:9300}
[2017-11-09T05:56:10,558][INFO ][o.e.b.BootstrapChecks ] [prod_es_node1] bound or publishing to a non-loopback or non-link-local address,enforcing bootstrap checks
[2017-11-09T05:56:40,576][WARN ][o.e.n.Node ][prod_es_node1]timed out while waiting for initial discovery state - timeout: 30s
[2017-11-09T05:56:40,584][INFO ][o.e.h.n.Netty4HttpServerTransport] [prod_es_node1] publish_address {172.24.0.2:9200}, bound_addresses {[::]:9200}
[2017-11-09T05:56:40,587][INFO ][o.e.n.Node ] [prod_es_node1] started

ES2

[2017-11-09T09:37:20,084][WARN ][o.e.d.z.ZenDiscovery ] [prod_es_node2]failed to connect to master [{prod_es_node1}{BxKzhOnJTUC50cYTz_Hm fA}{zqtU07jfQJOrmB9AYL01Ig}{172.24.0.2}{172.24.0.2:9300}], retrying...
org.elasticsearch.transport.ConnectTransportException:[prod_es_node1][172.24.0.2:9300] connect_timeout[30s]
at org.elasticsearch.transport.netty4.Netty4Transport.connectToChannels(Netty4Transport.java:361) ~[?:?]
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:549) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TcpTransport.connectToNode(TcpTransport.java:473) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:315) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:302) ~[elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:468) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:420) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4100(ZenDiscovery.java:83) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1197) [elasticsearch-5.4.2.jar:5.4.2]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.4.2.
jar:5.4.2]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_131]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_131]
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException:Connection refused: 172.24.0.2/172.24.0.2:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[?:?]

Body:
Now I use openvswitch and pipework to build cluster network

ovs setting:

#ES1
sudo brctl addbr br0
sudo ip link set dev br0 up
sudo ovs-vsctl add-br ovs0
sudo ovs-vsctl set bridge ovs0 stp_enable=true
sudo ovs-vsctl add-port ovs0 br0
sudo ovs-vsctl add-port ovs0 gre0 -- set interface gre0 type=gre options:remote_ip=10.251.34.50

pipwork setting:

sudo pipework-master/pipework br0 -i eth1 es1 172.28.0.2/8

docker container network information:

elasticsearch@es1:/usr/share/elasticsearch$ ip a

521: eth1@if522:  mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 4e:06:91:91:1f:3e brd ff:ff:ff:ff:ff:ff
    inet 172.28.0.2/8 brd 172.255.255.255 scope global eth1
       valid_lft forever preferred_lft forever

after setting both two docker container, cluster should be work !!

ES1

elasticsearch@es1:/usr/share/elasticsearch$ ping 172.18.0.2
PING 172.18.0.2 (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=1.222 ms
64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.339 ms
64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.547 ms
64 bytes from 172.18.0.2: icmp_seq=3 ttl=64 time=0.303 ms
64 bytes from 172.18.0.2: icmp_seq=4 ttl=64 time=0.333 ms
64 bytes from 172.18.0.2: icmp_seq=5 ttl=64 time=0.362 ms`

ES logs:

[2017-11-17T02:06:21,205][INFO ][o.e.n.Node               ] [prod_es_node1] started
[2017-11-17T02:06:21,223][INFO ][o.e.c.s.ClusterService   ] [prod_es_node1] new_master {prod_es_node1}{IoG7C5BYQ26AYsggMuJo2A}{AL3oD0itR1CgibIr-x-8Sg}{172.28.0.2}{172.28.0.2:9300}, reason: zen-disco-elected-as-master ([0] nodes joined)
[2017-11-17T02:06:21,254][INFO ][o.e.g.GatewayService     ] [prod_es_node1] recovered [0] indices into cluster_state
[2017-11-17T02:06:29,205][INFO ][o.e.c.s.ClusterService   ] [prod_es_node1] added {{prod_es_node2}{ZA7CwKyBQS2gm-OamVSz2g}{U6WQyzwoQCiDkwBvmUxoQw}{172.18.0.2}{172.18.0.2:9300},}, reason: zen-disco-node-join[{prod_es_node2}{ZA7CwKyBQS2gm-OamVSz2g}{U6WQyzwoQCiDkwBvmUxoQw}{172.18.0.2}{172.18.0.2:9300}]`

TEST

curl localhost:9200/_cluster/health?pretty
{
  "cluster_name" : "prod_es_cluster",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 2,
  "number_of_data_nodes" : 2,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0
}


问:
Fatal error: Class 'ZipArchive' not found in
I have a problem that I install 'Archive_Zip 0.1.1' on Linux server, but when I try to run the script to create the zip file it gives the fatal error

Fatal error: Class ZipArchive not found in ...

where I put the code

```<code>$zip = new ZipArchive;
var_dump($zip);
$res = $zip->open($filename, ZipArchive::OVERWRITE);
if ($res !== TRUE) {
    echo 'Error: Unable to create zip file';
    exit;
}
if (is_file($src)) {
    $zip->addFile($src);
} else {
    // echo "<br>" . dirname(__FILE__) . $src;//'/install1';
    if (!is_dir($src)) {
         $zip->close();
         @unlink($filename);
         echo 'Error: File not found';
         exit;
    }
    recurse_zip($src, $zip, $path_length);
}
$zip->close();
echo "<br>file name ".$filename;
</code>```

but it doesn't find the class file.

Please tell me the solution. What should I do to resolve the problem?
I also put php.ini file to the folder where script is, but it does not work.

答:
First of all, The solution for remote server:

If you are using cpanel you may have zip extension installed but not activate. You need to active it. For this case you need to go to cpanel > inside software section > click on PHP version. Then find zip and check it. Now save.

You should see like the image.

Refresh page. The error should disappear.

Note: If you dont found, contact server provider. They will install for you.

Body:
I have a problem that I install 'Archive_Zip 0.1.1' on Linux server, but when I try to run the script to create the zip file it gives the fatal error

Fatal error: Class ZipArchive not found in ...

where I put the code

$zip = new ZipArchive;
var_dump($zip);
$res = $zip->open($filename, ZipArchive::OVERWRITE);
if ($res !== TRUE) {
    echo 'Error: Unable to create zip file';
    exit;
}
if (is_file($src)) {
    $zip->addFile($src);
} else {
    // echo "
" . dirname(__FILE__) . $src;//'/install1';
    if (!is_dir($src)) {
         $zip->close();
         @unlink($filename);
         echo 'Error: File not found';
         exit;
    }
    recurse_zip($src, $zip, $path_length);
}
$zip->close();
echo "
file name ".$filename;

but it doesn't find the class file.

Please tell me the solution. What should I do to resolve the problem?
I also put php.ini file to the folder where script is, but it does not work.


问:
how to see iOS device logs in Console app using os_log
I want to test my app when it is not launched via Xcode, but rather by launching directly from the springboard. And I want to see log messages as I do that.

I'm not having any trouble seeing console logs for the simulator using os_log. It's great, because my category and subsystem let me filter to see exactly the messages I want to see in the Console app:

Now I want to do this on my device. I can see my connected device listed in the Console app:

But I don't see any of my app's os_log or print messages in the Console app. Is this just not a supported thing? Is there a way to log to the Console app from my device? Is there any way to log from my app running independently on the device?

EDIT Curiouser and curiouser. Now I'm able to see some of my app's os_log messages in the Console while the app runs independently on the device:

The catch, however, is that word "some". It seems to start working for a while and then it just mysteriously stops again. It's as if the pipeline from the device to the Console is unreliable.

So now the question becomes: is there any way to log reliably from my app running independently on the device?

答:
This is not a complete answer, but a large part of the trick seems to be this:

In Xcode's Devices and Simulators window, locate the device and show the console display by tapping the tiny button at the lower left.

It appears that this somehow opens the floodgates and allows the stream of log events to pass through to the Console app. It still isn't 100% reliable; eventually the stream can be mysteriously shut off, and I have the impression that events are randomly omitted now and then. But it seems to be a sine qua non for getting the stream to flow at all.


问:
Python coverage badges, how to get them?
I am using Python coverage to test my apps. Looking at other developers on GitHub I see they have a small badge which shows the percentage of coverage. Using coverage, how can I generate these badges?

The coverage badge is the one I'm looking at below.

Update: There are packages that generate badges i.e. nose-htmloutput! Cool

答:
I have written a python badge generation package that produces badges very visually similar to the main badge services.  It is highly flexible, you can import and use in your python code, or run from the command line.  It is simple, and self-contained.

You can set the badge label and value, and you can set the color based on thresholds.  There are pre-built settings for pylint, coverage, and pipeline success, but you can create any badge you like.

Here is a link to the github project with more detailed documentation: https://github.com/jongracecox/anybadge

Install with pip install anybadge

Example python code:

```<code>import anybadge

# Define thresholds: <2=red, <4=orange <8=yellow <10=green
thresholds = {2: 'red',
              4: 'orange',
              6: 'yellow',
              10: 'green'}

badge = anybadge.Badge('pylint', 2.22, thresholds=thresholds)

badge.write_badge('pylint.svg')
</code>```

Example command line use:

```<code>anybadge --label pylint --value 2.22 --file pylint.svg 2=red 4=orange 8=yellow 10=green
</code>```

Body:
I have written a python badge generation package that produces badges very visually similar to the main badge services.  It is highly flexible, you can import and use in your python code, or run from the command line.  It is simple, and self-contained.

You can set the badge label and value, and you can set the color based on thresholds.  There are pre-built settings for pylint, coverage, and pipeline success, but you can create any badge you like.

Here is a link to the github project with more detailed documentation: https://github.com/jongracecox/anybadge

Install with pip install anybadge

Example python code:

import anybadge

# Define thresholds: <2=red, <4=orange <8=yellow <10=green
thresholds = {2: 'red',
              4: 'orange',
              6: 'yellow',
              10: 'green'}

badge = anybadge.Badge('pylint', 2.22, thresholds=thresholds)

badge.write_badge('pylint.svg')

Example command line use:

anybadge --label pylint --value 2.22 --file pylint.svg 2=red 4=orange 8=yellow 10=green


问:
How to remove this loop to call div elements separately?
Here's the code I'm using for the audio players:

https://codepen.io/katzkode/pen/ZbxYYG

What it does:

Creates multiple audio players at once (by using a single div element) for each song using a loop.

Loop:

```<code>/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

var files:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3" // 3
            ];
</code>```

Is invoked in HTML when I use:

```<code><div id="audio-players"></div>
</code>```

What I'm trying to accomplish:

Remove the loop so I could insert any player separately and tweak them separately however I want like this: https://puu.sh/ynD4q/6ab2ba7816.png

I want to use this code to invoke the desired audio player:

```<code><audio id="audio-0" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>
<div id="audioplayer-0" class="audioplayer">
    <button id="playbutton-0" class="play playbutton"></button>
    <div id="timeline-0" class="timeline">
        <div id="playhead-0" class="playhead"></div>
    </div>
</div>
</code>```

When I try to use it, the play / stop / change position buttons stop working.

It's driving me crazy, I just started learning jQuery. Thank you a lot!

答:
You just need to change the id for your new audio element,
see the working demo

// Event listener for DOM
document.addEventListener("DOMContentLoaded", theDOMHasLoaded, false);

// array of audio files (stored in a folder called music)
var files = ["interlude.mp3", // 0
  "chooseyourweapon.mp3", // 1
  "interlude.mp3", // 2
  "scriptures.mp3" // 3
];

///////////////////////////////////////////////
// Find and store audio info
///////////////////////////////////////////////

// array for AudioObjects
var audioList = [];
// components and the index for their AudioObject
var componentDict = {};
// store AudioObject that is currently playing
var playingAudio = null;
// store playhead id if one is being dragged
var onplayhead = null;

/* AudioObject Constructor */
function AudioObject(audio, duration) {
  this.audio = audio;
  this.id = audio.id;
  this.duration = duration;
}
/* bindAudioPlayer
 * Store audioplayer components in correct AudioObject
 * num identifes correct audioplayer
 */
AudioObject.prototype.bindAudioPlayer = function(num) {
  this.audioplayer = document.getElementById("audioplayer-" + num);
  this.playbutton = document.getElementById("playbutton-" + num);
  this.timeline = document.getElementById("timeline-" + num);
  this.playhead = document.getElementById("playhead-" + num);
  this.timelineWidth = this.timeline.offsetWidth - this.playhead.offsetWidth
}

/* addEventListeners() */
AudioObject.prototype.addEventListeners = function() {
  this.audio.addEventListener("timeupdate", AudioObject.prototype.timeUpdate, false);
  this.audio.addEventListener("durationchange", AudioObject.prototype.durationChange, false);
  this.timeline.addEventListener("click", AudioObject.prototype.timelineClick, false);
  this.playbutton.addEventListener("click", AudioObject.prototype.pressPlay, false);
  // Makes playhead draggable
  this.playhead.addEventListener('mousedown', AudioObject.prototype.mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}

/* populateAudioList */
function populateAudioList() {
  var audioElements = document.getElementsByClassName("audio");
  for (i = 0; i < audioElements.length; i++) {
    audioList.push(
      new AudioObject(audioElements[i], 0)
    );
    audioList[i].bindAudioPlayer(i);
    audioList[i].addEventListeners();
  }
}

/* populateComponentDictionary()
 * {key=element id : value=index of audioList} */
function populateComponentDictionary() {
  for (i = 0; i < audioList.length; i++) {
    componentDict[audioList[i].audio.id] = i;
    componentDict[audioList[i].playbutton.id] = i;
    componentDict[audioList[i].timeline.id] = i;
    componentDict[audioList[i].playhead.id] = i;
  }
}

///////////////////////////////////////////////
// Update Audio Player
///////////////////////////////////////////////

/* durationChange
 * set duration for AudioObject */
AudioObject.prototype.durationChange = function() {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.duration = this.duration;
}

/* pressPlay()
 * call play() for correct AudioObject
 */
AudioObject.prototype.pressPlay = function() {
  var index = getAudioListIndex(this.id);
  audioList[index].play();
}

/* play()
 * play or pause selected audio, if there is a song playing pause it
 */
AudioObject.prototype.play = function() {
  if (this == playingAudio) {
    playingAudio = null;
    this.audio.pause();
    changeClass(this.playbutton, "playbutton play");
  }
  // else check if playing audio exists and pause it, then start this
  else {
    if (playingAudio != null) {
      playingAudio.audio.pause();
      changeClass(playingAudio.playbutton, "playbutton play");
    }
    this.audio.play();
    playingAudio = this;
    changeClass(this.playbutton, "playbutton pause");
  }
}

/* timelineClick()
 * get timeline's AudioObject
 */
AudioObject.prototype.timelineClick = function(event) {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.audio.currentTime = ao.audio.duration * clickPercent(event, ao.timeline, ao.timelineWidth);
}

/* mouseDown */
AudioObject.prototype.mouseDown = function(event) {
  onplayhead = this.id;
  var ao = audioList[getAudioListIndex(this.id)];
  window.addEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
  ao.audio.removeEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}

/* mouseUp EventListener
 * getting input from all mouse clicks */
function mouseUp(e) {
  if (onplayhead != null) {
    var ao = audioList[getAudioListIndex(onplayhead)];
    window.removeEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
    // change current time
    ao.audio.currentTime = ao.audio.duration * clickPercent(e, ao.timeline, ao.timelineWidth);
    ao.audio.addEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
  }
  onplayhead = null;
}

/* mousemove EventListener
 * Moves playhead as user drags */
AudioObject.prototype.moveplayhead = function(e) {
  var ao = audioList[getAudioListIndex(onplayhead)];
  var newMargLeft = e.clientX - getPosition(ao.timeline);

  if (newMargLeft >= 0 && newMargLeft <= ao.timelineWidth) {
    document.getElementById(onplayhead).style.marginLeft = newMargLeft + "px";
  }
  if (newMargLeft < 0) {
    playhead.style.marginLeft = "0px";
  }
  if (newMargLeft > ao.timelineWidth) {
    playhead.style.marginLeft = ao.timelineWidth + "px";
  }
}

/* timeUpdate
 * Synchronizes playhead position with current point in audio
 * this is the html audio element
 */
AudioObject.prototype.timeUpdate = function() {
  // audio element's AudioObject
  var ao = audioList[getAudioListIndex(this.id)];
  var playPercent = ao.timelineWidth * (ao.audio.currentTime / ao.duration);
  ao.playhead.style.marginLeft = playPercent + "px";
  // If song is over
  if (ao.audio.currentTime == ao.duration) {
    changeClass(ao.playbutton, "playbutton play");
    ao.audio.currentTime = 0;
    ao.audio.pause();
    playingAudio = null;
  }
}

///////////////////////////////////////////////
// Utility Methods
///////////////////////////////////////////////

/* changeClass
 * overwrites element's class names */
function changeClass(element, newClasses) {
  element.className = newClasses;
}

/* getAudioListIndex
 * Given an element's id, find the index in audioList for the correct AudioObject */
function getAudioListIndex(id) {
  return componentDict[id];
}

/* clickPercent()
 * returns click as decimal (.77) of the total timelineWidth */
function clickPercent(e, timeline, timelineWidth) {
  return (event.clientX - getPosition(timeline)) / timelineWidth;
}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
  return el.getBoundingClientRect().left;
}
///////////////////////////////////////////////
// GENERATE HTML FOR AUDIO ELEMENTS AND PLAYERS
///////////////////////////////////////////////

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
  for (f in files) {
    var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
    $("#audio-players").append(audioString);
  }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
  for (f in files) {
    var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
    $("#audio-players").append(playerString);
  }
}

/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
  // Generate HTML for audio elements and audio players
  createAudioElements();
  createAudioPlayers();

  // Populate Audio List
  populateAudioList();
  populateComponentDictionary();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.audioplayer {
  width: 480px;
  height: 60px;
  margin: 50px auto auto auto;
  border: solid;
}

.playbutton {
  height: 60px;
  width: 60px;
  border: none;
  float: left;
  outline: none;
}

.play {
  background: url('http://www.alexkatz.me/codepen/img/play.png');
}

.pause {
  background: url('http://www.alexkatz.me/codepen/img/pause.png');
}

.play,
.pause {
  background-size: 50% 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.timeline {
  width: 400px;
  height: 20px;
  margin-top: 20px;
  float: left;
  border-radius: 15px;
  background: rgba(0, 0, 0, .3);
}

.playhead {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  margin-top: 1px;
  background: rgba(0, 0, 0, 1);
  cursor: pointer;
}</code>```

<audio id="audio-4" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>

  <button id="playbutton-4" class="play playbutton"></button>

```

Body:
Here's the code I'm using for the audio players:

https://codepen.io/katzkode/pen/ZbxYYG

What it does:

Creates multiple audio players at once (by using a single div element) for each song using a loop.

Loop:

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

var files:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3" // 3
            ];

Is invoked in HTML when I use:

What I'm trying to accomplish:

Remove the loop so I could insert any player separately and tweak them separately however I want like this: https://puu.sh/ynD4q/6ab2ba7816.png

I want to use this code to invoke the desired audio player:

<audio id="audio-0" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>

    <button id="playbutton-0" class="play playbutton"></button>

When I try to use it, the play / stop / change position buttons stop working.

It's driving me crazy, I just started learning jQuery. Thank you a lot!

Body:
You just need to change the id for your new audio element,
see the working demo

// Event listener for DOM
document.addEventListener("DOMContentLoaded", theDOMHasLoaded, false);

// array of audio files (stored in a folder called music)
var files = ["interlude.mp3", // 0
  "chooseyourweapon.mp3", // 1
  "interlude.mp3", // 2
  "scriptures.mp3" // 3
];

///////////////////////////////////////////////
// Find and store audio info
///////////////////////////////////////////////

// array for AudioObjects
var audioList = [];
// components and the index for their AudioObject
var componentDict = {};
// store AudioObject that is currently playing
var playingAudio = null;
// store playhead id if one is being dragged
var onplayhead = null;

/* AudioObject Constructor */
function AudioObject(audio, duration) {
  this.audio = audio;
  this.id = audio.id;
  this.duration = duration;
}
/* bindAudioPlayer
 * Store audioplayer components in correct AudioObject
 * num identifes correct audioplayer
 */
AudioObject.prototype.bindAudioPlayer = function(num) {
  this.audioplayer = document.getElementById("audioplayer-" + num);
  this.playbutton = document.getElementById("playbutton-" + num);
  this.timeline = document.getElementById("timeline-" + num);
  this.playhead = document.getElementById("playhead-" + num);
  this.timelineWidth = this.timeline.offsetWidth - this.playhead.offsetWidth
}

/* addEventListeners() */
AudioObject.prototype.addEventListeners = function() {
  this.audio.addEventListener("timeupdate", AudioObject.prototype.timeUpdate, false);
  this.audio.addEventListener("durationchange", AudioObject.prototype.durationChange, false);
  this.timeline.addEventListener("click", AudioObject.prototype.timelineClick, false);
  this.playbutton.addEventListener("click", AudioObject.prototype.pressPlay, false);
  // Makes playhead draggable
  this.playhead.addEventListener('mousedown', AudioObject.prototype.mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}

/* populateAudioList */
function populateAudioList() {
  var audioElements = document.getElementsByClassName("audio");
  for (i = 0; i < audioElements.length; i++) {
    audioList.push(
      new AudioObject(audioElements[i], 0)
    );
    audioList[i].bindAudioPlayer(i);
    audioList[i].addEventListeners();
  }
}

/* populateComponentDictionary()
 * {key=element id : value=index of audioList} */
function populateComponentDictionary() {
  for (i = 0; i < audioList.length; i++) {
    componentDict[audioList[i].audio.id] = i;
    componentDict[audioList[i].playbutton.id] = i;
    componentDict[audioList[i].timeline.id] = i;
    componentDict[audioList[i].playhead.id] = i;
  }
}

///////////////////////////////////////////////
// Update Audio Player
///////////////////////////////////////////////

/* durationChange
 * set duration for AudioObject */
AudioObject.prototype.durationChange = function() {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.duration = this.duration;
}

/* pressPlay()
 * call play() for correct AudioObject
 */
AudioObject.prototype.pressPlay = function() {
  var index = getAudioListIndex(this.id);
  audioList[index].play();
}

/* play()
 * play or pause selected audio, if there is a song playing pause it
 */
AudioObject.prototype.play = function() {
  if (this == playingAudio) {
    playingAudio = null;
    this.audio.pause();
    changeClass(this.playbutton, "playbutton play");
  }
  // else check if playing audio exists and pause it, then start this
  else {
    if (playingAudio != null) {
      playingAudio.audio.pause();
      changeClass(playingAudio.playbutton, "playbutton play");
    }
    this.audio.play();
    playingAudio = this;
    changeClass(this.playbutton, "playbutton pause");
  }
}

/* timelineClick()
 * get timeline's AudioObject
 */
AudioObject.prototype.timelineClick = function(event) {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.audio.currentTime = ao.audio.duration * clickPercent(event, ao.timeline, ao.timelineWidth);
}

/* mouseDown */
AudioObject.prototype.mouseDown = function(event) {
  onplayhead = this.id;
  var ao = audioList[getAudioListIndex(this.id)];
  window.addEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
  ao.audio.removeEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}

/* mouseUp EventListener
 * getting input from all mouse clicks */
function mouseUp(e) {
  if (onplayhead != null) {
    var ao = audioList[getAudioListIndex(onplayhead)];
    window.removeEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
    // change current time
    ao.audio.currentTime = ao.audio.duration * clickPercent(e, ao.timeline, ao.timelineWidth);
    ao.audio.addEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
  }
  onplayhead = null;
}

/* mousemove EventListener
 * Moves playhead as user drags */
AudioObject.prototype.moveplayhead = function(e) {
  var ao = audioList[getAudioListIndex(onplayhead)];
  var newMargLeft = e.clientX - getPosition(ao.timeline);

  if (newMargLeft >= 0 && newMargLeft <= ao.timelineWidth) {
    document.getElementById(onplayhead).style.marginLeft = newMargLeft + "px";
  }
  if (newMargLeft < 0) {
    playhead.style.marginLeft = "0px";
  }
  if (newMargLeft > ao.timelineWidth) {
    playhead.style.marginLeft = ao.timelineWidth + "px";
  }
}

/* timeUpdate
 * Synchronizes playhead position with current point in audio
 * this is the html audio element
 */
AudioObject.prototype.timeUpdate = function() {
  // audio element's AudioObject
  var ao = audioList[getAudioListIndex(this.id)];
  var playPercent = ao.timelineWidth * (ao.audio.currentTime / ao.duration);
  ao.playhead.style.marginLeft = playPercent + "px";
  // If song is over
  if (ao.audio.currentTime == ao.duration) {
    changeClass(ao.playbutton, "playbutton play");
    ao.audio.currentTime = 0;
    ao.audio.pause();
    playingAudio = null;
  }
}

///////////////////////////////////////////////
// Utility Methods
///////////////////////////////////////////////

/* changeClass
 * overwrites element's class names */
function changeClass(element, newClasses) {
  element.className = newClasses;
}

/* getAudioListIndex
 * Given an element's id, find the index in audioList for the correct AudioObject */
function getAudioListIndex(id) {
  return componentDict[id];
}

/* clickPercent()
 * returns click as decimal (.77) of the total timelineWidth */
function clickPercent(e, timeline, timelineWidth) {
  return (event.clientX - getPosition(timeline)) / timelineWidth;
}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
  return el.getBoundingClientRect().left;
}
///////////////////////////////////////////////
// GENERATE HTML FOR AUDIO ELEMENTS AND PLAYERS
///////////////////////////////////////////////

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
  for (f in files) {
    var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
    $("#audio-players").append(audioString);
  }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
  for (f in files) {
    var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("#audio-players").append(playerString);
  }
}

/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
  // Generate HTML for audio elements and audio players
  createAudioElements();
  createAudioPlayers();

  // Populate Audio List
  populateAudioList();
  populateComponentDictionary();
}

.audioplayer {
  width: 480px;
  height: 60px;
  margin: 50px auto auto auto;
  border: solid;
}

.playbutton {
  height: 60px;
  width: 60px;
  border: none;
  float: left;
  outline: none;
}

.play {
  background: url('http://www.alexkatz.me/codepen/img/play.png');
}

.pause {
  background: url('http://www.alexkatz.me/codepen/img/pause.png');
}

.play,
.pause {
  background-size: 50% 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.timeline {
  width: 400px;
  height: 20px;
  margin-top: 20px;
  float: left;
  border-radius: 15px;
  background: rgba(0, 0, 0, .3);
}

.playhead {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  margin-top: 1px;
  background: rgba(0, 0, 0, 1);
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="audio-players"></div>
<audio id="audio-4" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>
<div id="audioplayer-4" class="audioplayer">
  <button id="playbutton-4" class="play playbutton"></button>
  <div id="timeline-4" class="timeline">
    <div id="playhead-4" class="playhead"></div>
  </div>
</div>


问:
Change detection in Angular template expression calls function too many times
I have dates all throughout my angular application that look something like this:

```<code>{{ stringAsDate(entry.followUpDate) | date:"yMdjm" }}
</code>```

the stringAsDate function looks like:

```<code>stringAsDate(dateStr: any) {
    if(dateStr != null){
        return new Date(moment(dateStr).seconds(0).milliseconds(0).toISOString());
    }
}
</code>```

The stringAsDate() function is necessary to have the same dates across all browsers. (I was getting inconsistencies because different browsers evaluate new Date() differently.) Anyways, this works. However, stringAsDate() is getting called every change detection (every click, etc.) so the performance of the application is really bad because I have these dates all over the place.

Is there a way to avoid stringAsDate() being called so many times?

答: In Angular4 put the get keyword in the function declaration before its name, so that you'll be able to refer that function in the template as a property (within curly braces).

Body:
I have dates all throughout my angular application that look something like this:

{{ stringAsDate(entry.followUpDate) | date:"yMdjm" }}

the stringAsDate function looks like:

stringAsDate(dateStr: any) {
    if(dateStr != null){
        return new Date(moment(dateStr).seconds(0).milliseconds(0).toISOString());
    }
}

The stringAsDate() function is necessary to have the same dates across all browsers. (I was getting inconsistencies because different browsers evaluate new Date() differently.) Anyways, this works. However, stringAsDate() is getting called every change detection (every click, etc.) so the performance of the application is really bad because I have these dates all over the place.

Is there a way to avoid stringAsDate() being called so many times?


问:
In node.js how to get/construct URL string from WHATWG URL including user and password but nothing after host
What would be the recommended way of deriving the following:

```<code>https://user:pass@hostname:port
</code>```

From:

```<code>https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash
</code>```

when dealing with node.js url module using current WHATWG URL ?

答:
As of Node 8.x with the WHATWG URL API:</p>

```<code>const { URL } = require('url');
const url = new URL('https://user:pass@hostname:1234/p/a/t/h?q=whatevere#hash');
url.search = url.pathname = url.hash = '';
console.log(url.toString()); // https://user:pass@hostname:1234/
</code>```

Body:
What would be the recommended way of deriving the following:

https://user:pass@hostname:port

From:

https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash

when dealing with node.js url module using current WHATWG URL ?

Body:
As of Node 8.x with the WHATWG URL API:

const { URL } = require('url');
const url = new URL('https://user:pass@hostname:1234/p/a/t/h?q=whatevere#hash');
url.search = url.pathname = url.hash = '';
console.log(url.toString()); // https://user:pass@hostname:1234/


问:
3D pointer seg error
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

```<code>int ***grid;
    grid=new int **[number];
</code>```

then I want to assign the 2D arrays to the 3D construct

```<code>for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);
</code>```

with

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}
</code>```

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

```<code>printf("%d",grid[1][1][1]);
</code>```

What is my mistake?

Best,
  Hannes

答:
Printing out the address

```<code>printf("%p",&grid[1][1][1]);
</code>```

You are printing the address here. That's why you may not get what you desire to see.

```<code>printf("%d",grid[1][1][1]);
</code>```

This will print the array element.

And to read an input from stdin you will use scanf() which requires you to pass address of an variable.

```<code>scanf("%d",&grid[1][1][1]);
</code>```

Zeroing out the allocated memory

Also you can't get the size of the array using sizeof. SO to initialize with 0 you use memset on the chunks that are allocated at once with a new.

In your case example would be Like 1201ProgramAlarm pointed out

```<code>for(int i = 0; i < 600; i++){
      ...
      memset(grid[i],0,sizeof(int)*600);
}
</code>```

There is another way you can initialise an allocated memory in c++.

grid[i]=new int[600]();

For example:

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600]();

...
  return(grid);
}
</code>```

Title: 3D pointer seg error

Body:
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

int ***grid;
    grid=new int **[number];

then I want to assign the 2D arrays to the 3D construct

for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);

with

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

printf("%d",grid[1][1][1]);

What is my mistake?

Best,
  Hannes

Body:
Printing out the address

printf("%p",&grid[1][1][1]);

You are printing the address here. That's why you may not get what you desire to see.

printf("%d",grid[1][1][1]);

This will print the array element.

And to read an input from stdin you will use scanf() which requires you to pass address of an variable.

scanf("%d",&grid[1][1][1]);

Zeroing out the allocated memory

Also you can't get the size of the array using sizeof. SO to initialize with 0 you use memset on the chunks that are allocated at once with a new.

In your case example would be Like 1201ProgramAlarm pointed out

for(int i = 0; i < 600; i++){
      ...
      memset(grid[i],0,sizeof(int)*600);
}

There is another way you can initialise an allocated memory in c++.

grid[i]=new int[600]();

For example:

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600]();

...
  return(grid);
}


问:
Nested for loop to multiply two lists by two variables python 3
I'm importing a CSV file into Python, then performing least squares regression with the x and y values. So far my program:

opens CSV file and delimits at commas

creates two lists consisting of X and Y (x_list and y_list, respectively)

calculates the average of all the values of X, and does the same for all the
values of Y (x_avg and y_avg, respectively)

I'm having trouble finding the numerator of the slope:

sum((Xi - X avg) * (Yi - Y avg))

I'm using a nested for loop but am getting an incorrect result back for my m_num (slope numerator).

```<code>def compute_numerator(x_list, y_list, x_avg, y_avg):
    m_num = 0
    xi = []
    yi = []
    multiples = []
    xi = [(x - x_avg) for x in x_list]
    yi = [(y - y_avg) for y in y_list]
    for x in xi:
        for y in yi:
            multiples = [x * y]
    m_num = sum(multiples)
    print(m_num)
    return m_num
</code>```

I need m_num to return the sum of all the values of (X - the average of X) * (Y - the average of Y)

Any suggestions or critiques welcome! Trying to learn and also pick up good programming habits. Thanks for your time!

答:
If you want each (x, y) value in x_list,y_list paired up with each other, this would work:

```<code>sum((x-x_avg)*(y-y_avg) for x, y in zip(x_list, y_list))
</code>```

Your problem is that you're not pairing them, and instead having each x value sum with all y values, like so:

```<code>sum((x-x_avg)*(y-y_avg) for x, y in x_list for y in y_list)
</code>```

Body:
I'm importing a CSV file into Python, then performing least squares regression with the x and y values. So far my program:

opens CSV file and delimits at commas

creates two lists consisting of X and Y (x_list and y_list, respectively)

calculates the average of all the values of X, and does the same for all the
values of Y (x_avg and y_avg, respectively)

I'm having trouble finding the numerator of the slope:

sum((Xi - X avg) * (Yi - Y avg))

I'm using a nested for loop but am getting an incorrect result back for my m_num (slope numerator).

def compute_numerator(x_list, y_list, x_avg, y_avg):
    m_num = 0
    xi = []
    yi = []
    multiples = []
    xi = [(x - x_avg) for x in x_list]
    yi = [(y - y_avg) for y in y_list]
    for x in xi:
        for y in yi:
            multiples = [x * y]
    m_num = sum(multiples)
    print(m_num)
    return m_num

I need m_num to return the sum of all the values of (X - the average of X) * (Y - the average of Y)

Any suggestions or critiques welcome! Trying to learn and also pick up good programming habits. Thanks for your time!

Body:
If you want each (x, y) value in x_list,y_list paired up with each other, this would work:

sum((x-x_avg)*(y-y_avg) for x, y in zip(x_list, y_list))

Your problem is that you're not pairing them, and instead having each x value sum with all y values, like so:

sum((x-x_avg)*(y-y_avg) for x, y in x_list for y in y_list)


问:
Software for taking notes on programming
What type of software is good for taking notes on programming?  For example, if I want to jot down different methods/functions that are useful for different things.  Ideally, the software would have  syntax highlighting.

The software would need to support Mac OS X.  I will most probably be using this for Objective-C/iPhone development and Ruby on Rails development.

I want something that can shift between ordinary text and coding syntax.  For example if I was to type:

In order to create a rectangle in Objective-C with a name square use: (CGRect *) square...........

I would like the objective-C code to have syntax highlighting but not the rest of the text.

Thanks!

P.S. I use textmate generally for coding.

答: I found that either a mind-mapping tool or a text editor with an outlining support are very suitable for this sort of notes. On OS X I'm using FreeMind, everywhere else - Emacs org mode.</p>


问:
Laravel Validator return error messages
```<code>public function search()
{
    if ($this->articleValidator->validateSearch(request())) {
        $response['response'] = TRUE;
        $response['data']['articles'] = $this->articleService->searchArticles(request()->keyword, request()->category, request()->from, request()->to);
        $response['html'] = view('partials/content-administrator-subsystem/articles', $response['data'])->render();
    } else {
        $response['response'] = $this->articleValidator->searchValidationErrors();
    }

    return json_encode($response);
    exit;
}
</code>```

I have this function inside my ArticlesPageController. I send a POST request with axios to this method.

```<code>class ArticleValidator implements ArticleValidatorInterface
{
    protected $searchValidator;

    /**
     * Validates articles search request
     *
     * @param request - Request object
     * @returns true/false if validation succeeded
     */
    public function validateSearch($request)
    {
        $this->searchValidator = Validator::make($request->all(), [
            'category' => 'array|min:1|exists:categories,id',
            'from' => 'date',
            'to' => 'date|after_or_equal:from'
        ]);

        return !$this->searchValidator->fails();
    }

    /**
     * Returns search validation errors
     *
     * @return validation errors or null if everything went well
     */
    public function searchValidationErrors()
    {
        if ($this->searchValidator) {
            print_r($this->searchValidator->errors()->getMessages());
            return $this->searchValidator->errors();
        }

        return null;
    }
}
</code>```

This is validator class.

The problem is, if validator fails, I get such return:

```<code>{
    "response": {
        "to": ["validation.after_or_equal"]
    }
}
</code>```

As you can see, it is validation rule that has failed, the problem is, that I need to get actual messages not the rule that has failed.

I know that in normal flow, I can do return redirect()->withErrors($errors) and in a view I would get an $errors array, but now, when it is an AJAX call, I cant do any redirects. so how can I get actual messages and return them back?

答:
As you can see here https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic, when you use the validate() method and your request was an AJAX one, you get the errors in JSON format in the response. You can see another way to use the Validator here https://laravel.com/docs/5.5/validation#automatic-redirection.

You may have to check for the corresponding version of the documentation because there were slight variations over time, but this should give you a kickstart.

Title: Laravel Validator return error messages

Body:
public function search()
{
    if ($this->articleValidator->validateSearch(request())) {
        $response['response'] = TRUE;
        $response['data']['articles'] = $this->articleService->searchArticles(request()->keyword, request()->category, request()->from, request()->to);
        $response['html'] = view('partials/content-administrator-subsystem/articles', $response['data'])->render();
    } else {
        $response['response'] = $this->articleValidator->searchValidationErrors();
    }

    return json_encode($response);
    exit;
}

I have this function inside my ArticlesPageController. I send a POST request with axios to this method.

class ArticleValidator implements ArticleValidatorInterface
{
    protected $searchValidator;

    /**
     * Validates articles search request
     *
     * @param request - Request object
     * @returns true/false if validation succeeded
     */
    public function validateSearch($request)
    {
        $this->searchValidator = Validator::make($request->all(), [
            'category' => 'array|min:1|exists:categories,id',
            'from' => 'date',
            'to' => 'date|after_or_equal:from'
        ]);

        return !$this->searchValidator->fails();
    }

    /**
     * Returns search validation errors
     *
     * @return validation errors or null if everything went well
     */
    public function searchValidationErrors()
    {
        if ($this->searchValidator) {
            print_r($this->searchValidator->errors()->getMessages());
            return $this->searchValidator->errors();
        }

        return null;
    }
}

This is validator class.

The problem is, if validator fails, I get such return:

{
    "response": {
        "to": ["validation.after_or_equal"]
    }
}

As you can see, it is validation rule that has failed, the problem is, that I need to get actual messages not the rule that has failed.

I know that in normal flow, I can do return redirect()->withErrors($errors) and in a view I would get an $errors array, but now, when it is an AJAX call, I cant do any redirects. so how can I get actual messages and return them back?


问:
Will adding attributes file increase Git performance?
Without .gitattributes, Git has to detect if a file is text or binary. If I add .gitattributes and specify the file is text, no detection is needed. I assume performance will increase a bit. Am I correct?

答:
In theory, it could make lead to a slight performance boost. However, git only checks the first 8000 bytes of the file for null bytes (source), which would be quite fast.

So, sure, go for it! It's certainly not going to hurt, but you probably won't notice the difference unless you have a ridiculous number of files.


问:
how to create wx.ITEM_DROPDOWN in wxpython
I am a novice wxpython，and i want to create a option button in toolbar, and The code is down here,But he didn't go into effect,I don't know what's wrong,Could you give me some advice,Thanks</p>

```<code>import wx

class Mywin(wx.Frame):
    def __init__(self, parent, title):
        super(Mywin, self).__init__(parent, title=title)
        self.InitUI()
    def InitUI(self):
        menubar = wx.MenuBar()
        menu = wx.Menu()
        menubar.Append(menu, "File")
        self.SetMenuBar(menubar)
        tb = wx.ToolBar(self, -1,style=wx.TB_TEXT|wx.TB_FLAT|wx.TB_HORZ_TEXT|wx.TB_HORZ_LAYOUT|wx.TB_TOP)#wx.TB_BOTTOM wx.TB_DOCKABLE
        tb.SetToolSeparation(22)
        tb.AddTool(101, 'what', wx.Bitmap("中国电信.png"), "开始",wx.ITEM_DROPDOWN)
        menu = wx.Menu()
        item = wx.MenuItem(menu, 222, "查看", "跳转到url")
        menu.AppendItem(item)
        bool = tb.SetDropdownMenu(101,menu)
        print(bool)
        tb.Bind(wx.EVT_TOOL_DROPDOWN,self.OnDropDown)
        tb.Bind(wx.EVT_TOOL, self.Onright)
        tb.Realize()
        self.SetSize((700, 250))

        #self.text = wx.TextCtrl(self, -1, style=wx.EXPAND | wx.TE_MULTILINE)
        self.Centre()
        self.Show(True)
    def OnDropDown(self,event):
        print(event)

    def Onright(self, event):
        print(event)
        self.text.AppendText(str(event.GetId()) + "\n")
        event.Skip()

ex = wx.App()
Mywin(None, 'ToolBar demo')
ex.MainLoop()
</code>```

答:
this is demo , Can you tell me your version , 2.7 or 3.0 ? </p>

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
ZetCode wxPython tutorial

This example shows a simple menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: September 2011
'''
import wx

class Example(wx.Frame):

    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)

        self.InitUI()

    def InitUI(self):

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        fitem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.OnQuit, fitem)

        self.SetSize((300, 200))
        self.SetTitle('Simple menu')
        self.Centre()
        self.Show(True)

    def OnQuit(self, e):
        self.Close()

def main():
    ex = wx.App()
    Example(None)
    ex.MainLoop()

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

Body:
I am a novice wxpython，and i want to create a option button in toolbar, and The code is down here,But he didn't go into effect,I don't know what's wrong,Could you give me some advice,Thanks

import wx

class Mywin(wx.Frame):
    def __init__(self, parent, title):
        super(Mywin, self).__init__(parent, title=title)
        self.InitUI()
    def InitUI(self):
        menubar = wx.MenuBar()
        menu = wx.Menu()
        menubar.Append(menu, "File")
        self.SetMenuBar(menubar)
        tb = wx.ToolBar(self, -1,style=wx.TB_TEXT|wx.TB_FLAT|wx.TB_HORZ_TEXT|wx.TB_HORZ_LAYOUT|wx.TB_TOP)#wx.TB_BOTTOM wx.TB_DOCKABLE
        tb.SetToolSeparation(22)
        tb.AddTool(101, 'what', wx.Bitmap("中国电信.png"), "开始",wx.ITEM_DROPDOWN)
        menu = wx.Menu()
        item = wx.MenuItem(menu, 222, "查看", "跳转到url")
        menu.AppendItem(item)
        bool = tb.SetDropdownMenu(101,menu)
        print(bool)
        tb.Bind(wx.EVT_TOOL_DROPDOWN,self.OnDropDown)
        tb.Bind(wx.EVT_TOOL, self.Onright)
        tb.Realize()
        self.SetSize((700, 250))

        #self.text = wx.TextCtrl(self, -1, style=wx.EXPAND | wx.TE_MULTILINE)
        self.Centre()
        self.Show(True)
    def OnDropDown(self,event):
        print(event)

    def Onright(self, event):
        print(event)
        self.text.AppendText(str(event.GetId()) + "\n")
        event.Skip()

ex = wx.App()
Mywin(None, 'ToolBar demo')
ex.MainLoop()

Body:
this is demo , Can you tell me your version , 2.7 or 3.0 ?

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
ZetCode wxPython tutorial

This example shows a simple menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: September 2011
'''
import wx

class Example(wx.Frame):

    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)

        self.InitUI()

    def InitUI(self):

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        fitem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.OnQuit, fitem)

        self.SetSize((300, 200))
        self.SetTitle('Simple menu')
        self.Centre()
        self.Show(True)

    def OnQuit(self, e):
        self.Close()

def main():
    ex = wx.App()
    Example(None)
    ex.MainLoop()

if __name__ == '__main__':
    main()