问:
How to work with variables in DOCKERFILE
I am creating NGINX container. I want to write all logs into a mounted volume rather than the default volume. This I can achieve by updating nginx.conf file by pointing access_log and error_log to a folder in mounted volume. The twist is that I want each container to write to container specific folder within the mounted volume.

For eg:
Container image name: mycontainerapp
Mounted volume: /logdirectory
Then I want:
/var/log to point to /logdirectory/mycontainerapp/{containerID}/log

This way, I can have multiple containers log to the common mounted volume.

AFAIK, I can get container ID from /proc/1/cpuset
I am not sure of any other way to get the container ID

Question is, how can I read that containerID and use it to create the mounted volume (with folder name) using DOCKERFILE?

Also, if there is a better approach to what I am trying to achieve, please do let me know as I am a newbie to docker.

答:
Docker has a logging mechanism included which removes standard log files from the equation. All data sent to stdout and stderr will be captured by Dockers logging interface.

There are a number of logging drivers that can then ship logs from your Docker host to a central logging service (Graylog, Syslog, AWS CloudWatch, ETW, Fluentd, Google Cloud, Splunk). The json driver is the default which is locally stored on the Docker host. journald will also be stored and accessible locally.

In nginx config, or any container for that matter, send the access log stdout or /dev/fd/1 and send the error log to stderr or /dev/fd/2

```<code>daemon off;
error_log /dev/fd/2 info;

http {
  access_log /dev/fd/1;
  ...
}
</code>```

Once you start applying this concept to all containers, any log management requirements are removed from the container/application level and pushed up to the host. Container meta data can be attached to logs. It becomes easier to move or change the logging mechanism. Moving to clustered setups like Swarm becomes less of a hassle. This all ties into the 1 process per container idea of the world that Docker pushes.

Body:
Docker has a logging mechanism included which removes standard log files from the equation. All data sent to stdout and stderr will be captured by Dockers logging interface.

There are a number of logging drivers that can then ship logs from your Docker host to a central logging service (Graylog, Syslog, AWS CloudWatch, ETW, Fluentd, Google Cloud, Splunk). The json driver is the default which is locally stored on the Docker host. journald will also be stored and accessible locally.

In nginx config, or any container for that matter, send the access log stdout or /dev/fd/1 and send the error log to stderr or /dev/fd/2

daemon off;
error_log /dev/fd/2 info;

http {
  access_log /dev/fd/1;
  ...
}

Once you start applying this concept to all containers, any log management requirements are removed from the container/application level and pushed up to the host. Container meta data can be attached to logs. It becomes easier to move or change the logging mechanism. Moving to clustered setups like Swarm becomes less of a hassle. This all ties into the 1 process per container idea of the world that Docker pushes.


来源: stackexchange

问:
TreeMap and click event
How to generate onclick event in TreeMap</p>

答:
I think your are asking for Jquery treemap plugin. If so, I have done this once. check the below code

```<code> $('.treemapCell').each(function () {

    $(this).find('span').click(function () {

         //Code
                });
    });
</code>```

Cheers!!

ContentLicense: CC BY-SA 4.0

Title: TreeMap and click event

Body:
I think your are asking for Jquery treemap plugin. If so, I have done this once. check the below code

 $('.treemapCell').each(function () {

    $(this).find('span').click(function () {

         //Code
                });
    });

Cheers!!

ContentLicense: CC BY-SA 2.5


问:
Python Sorting Multiple Lists Simultaneously
This is slightly different than most of the sorting questions on here and I haven't been able to figure out how to get this to work. I have 3 lists, and 2 of them I need to match the order of the 3rd list. There are integers in list 2 that correspond to the same indexed word in list 1. If there is an item in the 3rd list not in the other two i need to generate random numbers for it. The third list is also a tuple, but it's sorted so not sure that will matter. if a word is in lists are in 1 and 2 but not in 3 we can drop those.

For example:

```<code>import random

List1 = ['test', 'list', '1']
list2 = [[1,2,3], [4,5,6], [1,3,5]
list3 = [('this', 1),('is',2),('a',3),('test',4),('list',5)]
</code>```

what I'd like the results to be is

```<code>list1 = ['this', 'is', 'a' , 'test', 'list'] (just equal to first item in list 3)
list2 = [random((1,4),3), random((1,4),3), random((1,4),3), [1,2,3],[4,5,6]]
</code>```

答:
Create a dictionary by zipping the corresponding elements of list1 and list2. Then, you can create the final list by getting elements from that dict, or a list of random numbers if the element is not present.

```<code>>>> list1 = ['test', 'list', '1']
>>> list2 = [[1,2,3], [4,5,6], [1,3,5]]
>>> d = dict(zip(list1, list2))
>>> d
{'1': [1, 3, 5], 'list': [4, 5, 6], 'test': [1, 2, 3]}
>>> list4 = [x for x, y in list3]
>>> list5 = [d.get(x, [random.randint(1,4) for _ in range(3)]) for x in list4]
>>> list5
[[1, 2, 4], [3, 3, 1], [3, 3, 1], [1, 2, 3], [4, 5, 6]]
</code>```

Some notes:

I renamed list1 and list2 in the output to list4 and list5.

Here, same words refer to the same numbers list instance from list2, i.e. if you modify one, you modify all of them. If that's not what you want, use list(d.get(...)) in the list comprehension for list5 to create new lists for each element.

Using get with default might be a bit wasteful here, as it creates all those lists and calls randint even if the default value is not used. Instead, you might want to use a ternary: [d[x] if x in d else [random list] for ...]

Both ways, if the same word appears twice in list3 that's not also in list1, those two words will get different random numbers in list5; if you want the same random lists for same words, use [d.setdefault(x, [random list]) for ...]

ContentLicense: CC BY-SA 3.0

Body:
This is slightly different than most of the sorting questions on here and I haven't been able to figure out how to get this to work. I have 3 lists, and 2 of them I need to match the order of the 3rd list. There are integers in list 2 that correspond to the same indexed word in list 1. If there is an item in the 3rd list not in the other two i need to generate random numbers for it. The third list is also a tuple, but it's sorted so not sure that will matter. if a word is in lists are in 1 and 2 but not in 3 we can drop those.

For example:

import random

List1 = ['test', 'list', '1']
list2 = [[1,2,3], [4,5,6], [1,3,5]
list3 = [('this', 1),('is',2),('a',3),('test',4),('list',5)]

what I'd like the results to be is

list1 = ['this', 'is', 'a' , 'test', 'list'] (just equal to first item in list 3)
list2 = [random((1,4),3), random((1,4),3), random((1,4),3), [1,2,3],[4,5,6]]

Body:
Create a dictionary by zipping the corresponding elements of list1 and list2. Then, you can create the final list by getting elements from that dict, or a list of random numbers if the element is not present.

>>> list1 = ['test', 'list', '1']
>>> list2 = [[1,2,3], [4,5,6], [1,3,5]]
>>> d = dict(zip(list1, list2))
>>> d
{'1': [1, 3, 5], 'list': [4, 5, 6], 'test': [1, 2, 3]}
>>> list4 = [x for x, y in list3]
>>> list5 = [d.get(x, [random.randint(1,4) for _ in range(3)]) for x in list4]
>>> list5
[[1, 2, 4], [3, 3, 1], [3, 3, 1], [1, 2, 3], [4, 5, 6]]

Some notes:

I renamed list1 and list2 in the output to list4 and list5.

Here, same words refer to the same numbers list instance from list2, i.e. if you modify one, you modify all of them. If that's not what you want, use list(d.get(...)) in the list comprehension for list5 to create new lists for each element.

Using get with default might be a bit wasteful here, as it creates all those lists and calls randint even if the default value is not used. Instead, you might want to use a ternary: [d[x] if x in d else [random list] for ...]

Both ways, if the same word appears twice in list3 that's not also in list1, those two words will get different random numbers in list5; if you want the same random lists for same words, use [d.setdefault(x, [random list]) for ...]


问:
Relationship decay in Neo4j
I'm evaluating neo4j for a project. Overall it seem to fit my needs fairly well but I have one requirement that I'm not sure about.

I need to be able to create a relationship between two nodes that decays over time.

Does neo4j support such a thing? Or does anyone know of a crafty way of doing this?

答:
To get the "freshest" relationships first, you could just sort the relationships in descending order by their stored timestamps.

For example:

```<code>MATCH (f:Foo {id: 123})-[b:BAR]->()
RETURN b
ORDER BY b.stored_timestamp DESC;
</code>```

Title: Relationship decay in Neo4j

Body:
To get the "freshest" relationships first, you could just sort the relationships in descending order by their stored timestamps.

For example:

MATCH (f:Foo {id: 123})-[b:BAR]->()
RETURN b
ORDER BY b.stored_timestamp DESC;


问:
Django: Python path syntax to my custom validators.py?
I want to implement the solution detailed in this thread but I can't for the life of me figure out the Python path syntax in settings.py needed to link back to my custom validators.py I'm not even sure where to put it. I feel like a simple explanation of how the Python path syntax works in Django ought to be in the docs but after almost 20 minutes of looking through them I don't see anything. Any help would be greatly appreciated.

答:
I'm assuming your custom validators.py is within your project, so like any of your other Python project's module it is accessed using dot notation.

The only thing "different" here is that you append the actual class name to this module string. For example:

```<code>AUTH_PASSWORD_VALIDATORS = [
    'yourproject.validators.YourValidatorClass',
]
</code>```

(although the format is not specified in this specific setting in the docs, it is a constant pattern used throughout Django settings)

Body:
I'm assuming your custom validators.py is within your project, so like any of your other Python project's module it is accessed using dot notation.

The only thing "different" here is that you append the actual class name to this module string. For example:

AUTH_PASSWORD_VALIDATORS = [
    'yourproject.validators.YourValidatorClass',
]

(although the format is not specified in this specific setting in the docs, it is a constant pattern used throughout Django settings)


问:
PHP strtotime('UTC') different on another server
I have two different servers with a copy of the same PHP website.

Both servers are using the same timezone 'Pacific/Auckland'.

This code shows the same two numbers on server #1:

```<code>echo time();
echo strtotime('UTC');
</code>```

1510607965 & 1510607965

But the same code is showing two different numbers on server #2:

1510607965 & 1510654765

Why would each server be different?

答:
Both servers were using the same version of PHP but one of them had a problem with the timezone database.

I installed a new timezonedb and server #1 is showing the correct UTC time now.

Body:
I have two different servers with a copy of the same PHP website.

Both servers are using the same timezone 'Pacific/Auckland'.

This code shows the same two numbers on server #1:

echo time();
echo strtotime('UTC');

1510607965 & 1510607965

But the same code is showing two different numbers on server #2:

1510607965 & 1510654765

Why would each server be different?


问:
Git Commit on Mac using Sublime 2: subl command works by itself but not during a git commit
I am learning the basics of Git and have run into an issue while trying to use Sublime 2 as my default text editor for commit messages.

I am using a Mac and the Sublime text editor(Version 2.0.2, Build 2221)

As per instructions on  help.github I used the following line:

```<code>git config --global core.editor "subl -n -w"
</code>```

However, when I attempt a git commit command I get the following message:

```<code>subl -n -w: subl: command not found
error: There was a problem with the editor 'subl -n -w'.
Please supply the message using either -m or -F option.
</code>```

I know that subl and subl -n -w work as I have tried them in isolation and they launch the editor. So the issue must be when the editor is opened from the git commit command.

I have looked at the questions and answers from 1, 2 & 3 and attempted the solutions but haven't been able to resolve my issue.

答:
I encountered the same error trying to configure Sublime Text 3 for git commit messages on Mac. Like you, the subl terminal command launched Sublime Text 3 but produced an error when used with git commit.

I initially tried git config --global core.editor "subl -n -w" and got:

```<code>subl -n -w: subl: command not found
error: There was a problem with the editor 'subl -n -w'.
Please supply the message using either -m or -F option.
</code>```

Then I tried the following, substituting subl with the absolute path:

```<code>$ git config --global core.editor "'/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w"
</code>```

and received the following error:

```<code>'/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w: /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl: No such file or directory
error: There was a problem with the editor ''/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w'.
Please supply the message using either -m or -F option.
</code>```

This was because the absolute file path contained an escaping backslash that is unnecessary. Once I removed the backslash it worked!
The correct git config command is:

```<code>$ git config --global core.editor "'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl' -n -w"
</code>```

Ta daa!

Body:
I am learning the basics of Git and have run into an issue while trying to use Sublime 2 as my default text editor for commit messages.

I am using a Mac and the Sublime text editor(Version 2.0.2, Build 2221)

As per instructions on  help.github I used the following line:

git config --global core.editor "subl -n -w"

However, when I attempt a git commit command I get the following message:

subl -n -w: subl: command not found
error: There was a problem with the editor 'subl -n -w'.
Please supply the message using either -m or -F option.

I know that subl and subl -n -w work as I have tried them in isolation and they launch the editor. So the issue must be when the editor is opened from the git commit command.

I have looked at the questions and answers from 1, 2 & 3 and attempted the solutions but haven't been able to resolve my issue.

Body:
I encountered the same error trying to configure Sublime Text 3 for git commit messages on Mac. Like you, the subl terminal command launched Sublime Text 3 but produced an error when used with git commit.

I initially tried git config --global core.editor "subl -n -w" and got:

subl -n -w: subl: command not found
error: There was a problem with the editor 'subl -n -w'.
Please supply the message using either -m or -F option.

Then I tried the following, substituting subl with the absolute path:

$ git config --global core.editor "'/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w"

and received the following error:

'/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w: /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl: No such file or directory
error: There was a problem with the editor ''/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl' -n -w'.
Please supply the message using either -m or -F option.

This was because the absolute file path contained an escaping backslash that is unnecessary. Once I removed the backslash it worked!
The correct git config command is:

$ git config --global core.editor "'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl' -n -w"

Ta daa!


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答:
I favor the first.    Some I/O operators require they are inside a try/catch for
some condition or other.  Also,  operations can always return null unexpectedly,
even though that is not in the manual.</p>

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.


问:
SQL Server 2008 trigger update when specific column changes
Other solutions got me this far, but ultimately things are not working for me.

I have a column in tbl_activity named abstract. When tbl_activity.abstract changes, I want to set tbl_activity.flag = 0.

My 2 versions of the trigger will set flag = 0, but then I cannot set flag back to 1, because changing that flag causes it to trigger, and it keeps setting the flag = 0. I've tried comparing old to new values, deleted to inserted values, and tried INSTEAD OF INSERT.

Can someone please examine this code and tell me what I'm missing?

```<code>ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract NOT LIKE i.abstract
</code>```

This results in "Command[s] completed successfully" - but when a column other than abstract changes, the trigger always sets flag = 0. Ideas?

答:
since the code i posted to ask my question, contained the erroneous use of INSTEAD OF - my "answer" at this point is that i changed my tbl_activity.abstract field from type Text to type Varchar(MAX) not null. One of the original problems was that the SQL trigger would not allow use of a text field. I will post that question properly on another post. Meanwhile, this code works, in the context where the "abstract" field is type varchar:</p>

```<code>ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON  [dbo].[tbl_activity] --table using the trigger
AFTER INSERT, UPDATE
AS UPDATE a
set a.flag = 0 --target action when above table is changed
FROM tbl_activity a
 INNER JOIN INSERTED i ON a.activityid = i.activityid
 INNER JOIN DELETED d ON d.activityid = i.activityid
WHERE d.abstract <> i.abstract
</code>```

Body:
Other solutions got me this far, but ultimately things are not working for me.

I have a column in tbl_activity named abstract. When tbl_activity.abstract changes, I want to set tbl_activity.flag = 0.

My 2 versions of the trigger will set flag = 0, but then I cannot set flag back to 1, because changing that flag causes it to trigger, and it keeps setting the flag = 0. I've tried comparing old to new values, deleted to inserted values, and tried INSTEAD OF INSERT.

Can someone please examine this code and tell me what I'm missing?

ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract NOT LIKE i.abstract

This results in "Command[s] completed successfully" - but when a column other than abstract changes, the trigger always sets flag = 0. Ideas?

Body:
since the code i posted to ask my question, contained the erroneous use of INSTEAD OF - my "answer" at this point is that i changed my tbl_activity.abstract field from type Text to type Varchar(MAX) not null. One of the original problems was that the SQL trigger would not allow use of a text field. I will post that question properly on another post. Meanwhile, this code works, in the context where the "abstract" field is type varchar:

ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON  [dbo].[tbl_activity] --table using the trigger
AFTER INSERT, UPDATE
AS UPDATE a
set a.flag = 0 --target action when above table is changed
FROM tbl_activity a
 INNER JOIN INSERTED i ON a.activityid = i.activityid
 INNER JOIN DELETED d ON d.activityid = i.activityid
WHERE d.abstract <> i.abstract


问:
jQuery checkbox filter, working but want to reset when unchecked
I'm building a filter for a selection of condos. I've figured out how to filter using a slider and now also need to filter by number of bedrooms using two checkboxes.

```<code><form name="filter" method="post" action="">
  <p>Bedrooms
    <input id="1bdrm" type="checkbox" value="1bdrm" />1 Bedroom
    <input id="2bdrm" type="checkbox" value="2bdrm" />2 Bedroom
  </p>
</form>
</code>```

So far I have the filter limiting the selection to show only 1 bedroom units, but can't figure out how to reset and show all units when unchecking the checkbox.

```<code>// Set values for units
$('#cohen').data({
  id: 4,
  sqft: 976,
  bdrms: 2
});
$('#curnoe').data({
  id: 5,
  sqft: 572,
  bdrms: 2
});
$('#richler').data({
  id: 6,
  sqft: 624,
  bdrms: 2
});
$('#carr').data({
  id: 7,
  sqft: 544,
  bdrms: 1
});
$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

//filter by number of bedrooms
$(document).ready(function() {
  var theValue;

  $("#1bdrm").click(function() {
    filterItems();
  });
});

function filterItems() {
  $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if (itemData.bdrms == 1) {
      $this.show();
      itemData.matching = true;
    } else {
      $this.hide();
      itemData.matching = false;
    }
  });
}
</code>```

Here's a fiddle link.. https://jsfiddle.net/3y9vz1q1/ I'm using the .data method to store unique attributes on each unit so that i can filter for each attribute (example: I have another script written for a slider that limits condos by sqft.

Hoping the community can point me in the right direction! Thanks in advance.

Marc.

答:
Always, when you click to checkbox, filter funtion started and because last item

```<code>$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});
</code>```

has 1, list don't reset

Try it:

```<code>  $(document).ready(function() {
        var theValue;

        $("#1bdrm").click(function() {
          if(this.checked){
            filterItems(false);
              }else{
            filterItems(true);
            }
        });
      });

      function filterItems(reset)
      {
        $.each($('.condo-box'), function() {
          $this = $(this);
          itemData = $this.data();
          if(itemData.bdrms == 1 || reset === true){
            $this.show();
            itemData.matching = true;
          } else {
            $this.hide();
            itemData.matching = false;
          }
        });
      }
</code>```

Body:
I'm building a filter for a selection of condos. I've figured out how to filter using a slider and now also need to filter by number of bedrooms using two checkboxes.

<form name="filter" method="post" action="">

Bedrooms
    <input id="1bdrm" type="checkbox" value="1bdrm" />1 Bedroom
    <input id="2bdrm" type="checkbox" value="2bdrm" />2 Bedroom

</form>

So far I have the filter limiting the selection to show only 1 bedroom units, but can't figure out how to reset and show all units when unchecking the checkbox.

// Set values for units
$('#cohen').data({
  id: 4,
  sqft: 976,
  bdrms: 2
});
$('#curnoe').data({
  id: 5,
  sqft: 572,
  bdrms: 2
});
$('#richler').data({
  id: 6,
  sqft: 624,
  bdrms: 2
});
$('#carr').data({
  id: 7,
  sqft: 544,
  bdrms: 1
});
$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

//filter by number of bedrooms
$(document).ready(function() {
  var theValue;

  $("#1bdrm").click(function() {
    filterItems();
  });
});

function filterItems() {
  $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if (itemData.bdrms == 1) {
      $this.show();
      itemData.matching = true;
    } else {
      $this.hide();
      itemData.matching = false;
    }
  });
}

Here's a fiddle link.. https://jsfiddle.net/3y9vz1q1/ I'm using the .data method to store unique attributes on each unit so that i can filter for each attribute (example: I have another script written for a slider that limits condos by sqft.

Hoping the community can point me in the right direction! Thanks in advance.

Marc.

Body:
Always, when you click to checkbox, filter funtion started and because last item

$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

has 1, list don't reset

Try it:

  $(document).ready(function() {
        var theValue;

        $("#1bdrm").click(function() {
          if(this.checked){
            filterItems(false);
              }else{
            filterItems(true);
            }
        });
      });

      function filterItems(reset)
      {
        $.each($('.condo-box'), function() {
          $this = $(this);
          itemData = $this.data();
          if(itemData.bdrms == 1 || reset === true){
            $this.show();
            itemData.matching = true;
          } else {
            $this.hide();
            itemData.matching = false;
          }
        });
      }


问:
Eclipse - java.lang.ClassNotFoundException
When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.

My project structure is the following:

parent project (pom-packaging)

Web project (war-packaging - my JUnit-test is in here)

Flex project

Configuration project

edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.

Here's my JUnit's run-configuration:
alt text http://www.walkner.biz/_temp/runconfig.png

Testclass (but as I said; it doesn't work with a simple HelloWorld either...):

```<code>import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;

public class UserDaoTest {
/**
 * the applicationcontext.
 */
private ApplicationContext ctx = null;

/**
 * the user itself.
 */
private User record = null;

/**
 * Interface for the user.
 */
private UserRepository dao = null;

@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}

@After
public void tearDown() throws Exception {
dao = null;
}

@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}

@Test
    public final void testIsNoUser() throws Exception {
    Assert.assertFalse(dao.isUser("not", "existing"));
        Assert.assertFalse(dao.isUser(null, null));
        Assert.assertFalse(dao.isUser("", ""));
    }
}
</code>```

答: Go To Build Path -> Source and toggle to Yes option "Ignore Optional Compile Problems" for all source folders.</p>

Body:
When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.

My project structure is the following:

parent project (pom-packaging)

Web project (war-packaging - my JUnit-test is in here)

Flex project

Configuration project

edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.

Here's my JUnit's run-configuration:
alt text http://www.walkner.biz/_temp/runconfig.png

Testclass (but as I said; it doesn't work with a simple HelloWorld either...):

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;

public class UserDaoTest {
/**
 * the applicationcontext.
 */
private ApplicationContext ctx = null;

/**
 * the user itself.
 */
private User record = null;

/**
 * Interface for the user.
 */
private UserRepository dao = null;

@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}

@After
public void tearDown() throws Exception {
dao = null;
}

@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}

@Test
    public final void testIsNoUser() throws Exception {
    Assert.assertFalse(dao.isUser("not", "existing"));
        Assert.assertFalse(dao.isUser(null, null));
        Assert.assertFalse(dao.isUser("", ""));
    }
}


问:
In for (int val :arr), what does the colon mean?
```<code>#include <iostream>
using namespace std;
int arr[] = { 1, 2, 3 };

void Show()
{
    for (int val : arr) {
        cout << val;
    }
}

int main()
{
    Show();
    return 0;
}
</code>```

result will be 123 .
 i will be very grateful to get explanation of this  -int val :arr-
 specifically what - : -  does here ?  what is it .

答:
It is called range loop.

```<code>int arr[] = { 1, 2, 3 };
for (int val : arr)
   cout << val;
</code>```

works the same as:

```<code>int arr[] = { 1, 2, 3 };
for (int i=0;i<sizeof(arr)/sizeof(int);i++)
{
   int val=arr[i];
   cout << val;
}
</code>```

But range loop can do far more.

It simply means loop through all members. Keep in mind some classes can have a complicated iterator and a range for runs through an array in a clean way. Also, notice it is a c++11 feature.

Body:
#include <iostream>
using namespace std;
int arr[] = { 1, 2, 3 };

void Show()
{
    for (int val : arr) {
        cout << val;
    }
}

int main()
{
    Show();
    return 0;
}

result will be 123 .
 i will be very grateful to get explanation of this  -int val :arr-
 specifically what - : -  does here ?  what is it .

Body:
It is called range loop.

int arr[] = { 1, 2, 3 };
for (int val : arr)
   cout << val;

works the same as:

int arr[] = { 1, 2, 3 };
for (int i=0;i<sizeof(arr)/sizeof(int);i++)
{
   int val=arr[i];
   cout << val;
}

But range loop can do far more.

It simply means loop through all members. Keep in mind some classes can have a complicated iterator and a range for runs through an array in a clean way. Also, notice it is a c++11 feature.


问:
How to launch a Common Lisp GTK app from a command line script (or cron)?
I have written a program generating a simple tray icon using cl-cffi-gtk and Common Lisp called tray-icon.lisp which is defined in a ASDF system called hourly-player. My problem is now that while this app starts fine from the command line, starting it from a script turns out to be a bit more difficult.
If I try

```<code>sbcl --eval '(asdf:load-system "hourly-player")' --eval '(hourly-player:run)'
</code>```

my application is correctly loaded into the SBCL REPL and the tray icon displays correctly. However if I add a & to launch my script in the background it seems to immediately terminate.

Adding a (loop) at the end of my run function keeps the script from terminating but obviously also occupies my CPU a lot more than would be necessary for such a app (roughly 12% load according to conky compared to basically nothing when running in sbcl).

Is there some canonical way to keep my script alive as a background process?

I'm also aware that there are other ways of executing a lisp programm but they either share the same problem (e.g. core dumps) or seem to break my system definitions dependencies (at least buildapp and cl-launch seem to do so).

If it helps, my project can be found here.

答: A quick shot might be to do (loop (sleep 60)) to keep your main program alive.  You also might want to look at using within-main-loop-and-wait instead of within-main-loop (from gtk+).

Body:
I have written a program generating a simple tray icon using cl-cffi-gtk and Common Lisp called tray-icon.lisp which is defined in a ASDF system called hourly-player. My problem is now that while this app starts fine from the command line, starting it from a script turns out to be a bit more difficult.
If I try

sbcl --eval '(asdf:load-system "hourly-player")' --eval '(hourly-player:run)'

my application is correctly loaded into the SBCL REPL and the tray icon displays correctly. However if I add a & to launch my script in the background it seems to immediately terminate.

Adding a (loop) at the end of my run function keeps the script from terminating but obviously also occupies my CPU a lot more than would be necessary for such a app (roughly 12% load according to conky compared to basically nothing when running in sbcl).

Is there some canonical way to keep my script alive as a background process?

I'm also aware that there are other ways of executing a lisp programm but they either share the same problem (e.g. core dumps) or seem to break my system definitions dependencies (at least buildapp and cl-launch seem to do so).

If it helps, my project can be found here.


问:
Wordpress Home page URL changing to /?i=1 - issue
When I try to access my Wordpress website directly or from google, the Home page URL automatically adding /?i=1 and sometimes /?i=2 to the URL in the address bar.

I think it's a very simple to solve it, but I tried many things and didn't work.

So I wonder how can I solve this to be only the URL without /?i=1 or /?i=2 ?

答:
```<code>RewriteCond %{QUERY_STRING} ^(.*)i=[^&]+(.*)$ [NC]
RewriteRule ^(.*)$ /$1?%1%2 [R=301,L]
</code>```

Add this in htaccess

Body:
RewriteCond %{QUERY_STRING} ^(.*)i=[^&]+(.*)$ [NC]
RewriteRule ^(.*)$ /$1?%1%2 [R=301,L]

Add this in htaccess


问:
What are SparkSession Config Options
I am trying to use SparkSession to convert JSON data of a file to RDD with Spark Notebook. I already have the JSON file.

```<code> val spark = SparkSession
   .builder()
   .appName("jsonReaderApp")
   .config("config.key.here", configValueHere)
   .enableHiveSupport()
   .getOrCreate()
val jread = spark.read.json("search-results1.json")
</code>```

I am very new to spark and do not know what to use for config.key.here and configValueHere.

答:
SparkSession

To get all the "various Spark parameters as key-value pairs" for a SparkSession, “The entry point to programming Spark with the Dataset and DataFrame API," run the following (this is using Spark Python API, Scala would be very similar).

import pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
SparkConf().getAll()
```
<p>or without importing <code>SparkConf</code>:</p>
<pre class="lang-py prettyprint-override"><code>spark.sparkContext.getConf().getAll()
</code>```

Depending on which API you are using, see one of the following:

https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/SparkSession.html

https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/spark_session.html

https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/SparkSession.html

https://spark.apache.org/docs/latest/api/R/reference/sparkR.session.html

You can get a deeper level list of SparkSession configuration options by running the code below.  Most are the same, but there are a few extra ones. I am not sure if you can change these.

spark.sparkContext._conf.getAll()
```
<h2>SparkContext</h2>
<p>To get all the "various Spark parameters as key-value pairs" for a SparkContext, the "Main entry point for Spark functionality," ... "connection to a Spark cluster," ... and "to create RDDs, accumulators and broadcast variables on that cluster,” run the following.</p>
<pre class="lang-py prettyprint-override"><code>import pyspark
from pyspark import SparkConf, SparkContext
spark_conf = SparkConf().setAppName("test")
spark = SparkContext(conf = spark_conf)
SparkConf().getAll()
</code>```

Depending on which API you are using, see one of the following:

https://spark.apache.org/docs/latest/api/scala/org/apache/spark/SparkContext.html

https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.SparkContext.html

https://spark.apache.org/docs/latest/api/java/org/apache/spark/SparkContext.html

https://spark.apache.org/docs/latest/api/R/reference/sparkR.init-deprecated.html

Spark parameters

You should get a list of tuples that contain the "various Spark parameters as key-value pairs" similar to the following:

[(u'spark.eventLog.enabled', u'true'),
 (u'spark.yarn.appMasterEnv.PYSPARK_PYTHON', u'/<yourpath>/parcels/Anaconda-4.2.0/bin/python'),
 ...
 ...
 (u'spark.yarn.jars', u'local:/<yourpath>/lib/spark2/jars/*')]
```
<p>Depending on which API you are using, see one of the following:</p>
<ol>
<li>https://spark.apache.org/docs/latest/api/scala/org/apache/spark/SparkConf.html</li>
<li>https://spark.apache.org/docs/latest//api/python/reference/api/pyspark.SparkConf.html</li>
<li>https://spark.apache.org/docs/latest/api/java/org/apache/spark/SparkConf.html</li>
<li>https://spark.apache.org/docs/3.3.2/api/R/reference/sparkR.conf.html (for SparkR, sparkConfig can only be set from <code>sparkR.session(sparkConfig=list())</code>)</li>
</ol>
<p>For a complete list of Spark properties, see:<br />
http://spark.apache.org/docs/latest/configuration.html#viewing-spark-properties</p>
<h2>Setting Spark parameters</h2>
<p>Each tuple is <code>("spark.some.config.option", "some-value")</code> which you can set in your application with:</p>
<h3>SparkSession</h3>
<pre class="lang-py prettyprint-override"><code>spark = (
    SparkSession
    .builder
    .appName("Your App Name")
    .config("spark.some.config.option1", "some-value")
    .config("spark.some.config.option2", "some-value")
    .getOrCreate())

sc = spark.sparkContext
</code>```

SparkContext

spark_conf = (
    SparkConf()
    .setAppName("Your App Name")
    .set("spark.some.config.option1", "some-value")
    .set("spark.some.config.option2", "some-value"))

sc = SparkContext(conf = spark_conf)
```
<h3>spark-defaults</h3>
<p>You can also set the Spark parameters in a <code>spark-defaults.conf</code> file:</p>
<pre class="lang-bash prettyprint-override"><code>spark.some.config.option1 some-value
spark.some.config.option2 "some-value"
</code>```

then run your Spark application with spark-submit (pyspark):

spark-submit \
--properties-file path/to/your/spark-defaults.conf \
--name "Your App Name" \
--py-files path/to/your/supporting/pyspark_files.zip \
--class Main path/to/your/pyspark_main.py
```

Title: What are SparkSession Config Options

Body:
I am trying to use SparkSession to convert JSON data of a file to RDD with Spark Notebook. I already have the JSON file.

 val spark = SparkSession
   .builder()
   .appName("jsonReaderApp")
   .config("config.key.here", configValueHere)
   .enableHiveSupport()
   .getOrCreate()
val jread = spark.read.json("search-results1.json")

I am very new to spark and do not know what to use for config.key.here and configValueHere.

Body:
SparkSession

To get all the "various Spark parameters as key-value pairs" for a SparkSession, “The entry point to programming Spark with the Dataset and DataFrame API," run the following (this is using Spark Python API, Scala would be very similar).

import pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
SparkConf().getAll()

or without importing SparkConf:

spark.sparkContext.getConf().getAll()

Depending on which API you are using, see one of the following:

https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/SparkSession.html

https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/spark_session.html

https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/SparkSession.html

https://spark.apache.org/docs/latest/api/R/reference/sparkR.session.html

You can get a deeper level list of SparkSession configuration options by running the code below.  Most are the same, but there are a few extra ones. I am not sure if you can change these.

spark.sparkContext._conf.getAll()

SparkContext

To get all the "various Spark parameters as key-value pairs" for a SparkContext, the "Main entry point for Spark functionality," ... "connection to a Spark cluster," ... and "to create RDDs, accumulators and broadcast variables on that cluster,” run the following.

import pyspark
from pyspark import SparkConf, SparkContext
spark_conf = SparkConf().setAppName("test")
spark = SparkContext(conf = spark_conf)
SparkConf().getAll()

Depending on which API you are using, see one of the following:

https://spark.apache.org/docs/latest/api/scala/org/apache/spark/SparkContext.html

https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.SparkContext.html

https://spark.apache.org/docs/latest/api/java/org/apache/spark/SparkContext.html

https://spark.apache.org/docs/latest/api/R/reference/sparkR.init-deprecated.html

Spark parameters

You should get a list of tuples that contain the "various Spark parameters as key-value pairs" similar to the following:

[(u'spark.eventLog.enabled', u'true'),
 (u'spark.yarn.appMasterEnv.PYSPARK_PYTHON', u'/<yourpath>/parcels/Anaconda-4.2.0/bin/python'),
 ...
 ...
 (u'spark.yarn.jars', u'local:/<yourpath>/lib/spark2/jars/*')]

Depending on which API you are using, see one of the following:

https://spark.apache.org/docs/latest/api/scala/org/apache/spark/SparkConf.html

https://spark.apache.org/docs/latest//api/python/reference/api/pyspark.SparkConf.html

https://spark.apache.org/docs/latest/api/java/org/apache/spark/SparkConf.html

https://spark.apache.org/docs/3.3.2/api/R/reference/sparkR.conf.html (for SparkR, sparkConfig can only be set from sparkR.session(sparkConfig=list()))

For a complete list of Spark properties, see:

http://spark.apache.org/docs/latest/configuration.html#viewing-spark-properties

Setting Spark parameters

Each tuple is ("spark.some.config.option", "some-value") which you can set in your application with:

SparkSession

spark = (
    SparkSession
    .builder
    .appName("Your App Name")
    .config("spark.some.config.option1", "some-value")
    .config("spark.some.config.option2", "some-value")
    .getOrCreate())

sc = spark.sparkContext

SparkContext

spark_conf = (
    SparkConf()
    .setAppName("Your App Name")
    .set("spark.some.config.option1", "some-value")
    .set("spark.some.config.option2", "some-value"))

sc = SparkContext(conf = spark_conf)

spark-defaults

You can also set the Spark parameters in a spark-defaults.conf file:

spark.some.config.option1 some-value
spark.some.config.option2 "some-value"

then run your Spark application with spark-submit (pyspark):

spark-submit \
--properties-file path/to/your/spark-defaults.conf \
--name "Your App Name" \
--py-files path/to/your/supporting/pyspark_files.zip \
--class Main path/to/your/pyspark_main.py


问:
Tinymce is not returning HTML but just text
I'm struggeling with this problem. I'm very new to javascript i had tinymce v3 for my website working, but i wanted to update it also looked way to complicated. So i installed v4 it took me a while but i finaly got i working. In the sence of its showing the textarea. When i post my page it does not return text with html tags around it but just a string. And when i use blockquotes it just returns a string with
[quote][/quote].
This is the code i use.

```<code><script src="@Url.Content("~/Scripts/tinymce/jquery.tinymce.min.js")" type="text/javascript"></script>

<script type="text/javascript">

    (function(){

      $(function() {

          $('#@ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)').tinymce({

            // Location of TinyMCE script
            script_url: '@Url.Content("~/Scripts/tinymce/tinymce.js")',
            theme: "modern",

            height: "300",
            width: "1150",
            verify_html: true,
            statusbar: true,
            plugins : "pagebreak,bbcode,link,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",

            // Theme options
            theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,thisisnotvaled,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,codehighlighting,netadvimage",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : false,

            // Example content CSS (should be your site CSS)
            content_css : "@Url.Content("~/Scripts/tinymce/css/content.css")",
            convert_urls: false,

            // TODO: Make line breaks work and qoutes are now also not working

            force_br_newlines: true,
            force_p_newlines: true,
            forced_root_block: '',
            remove_linebreaks: false,
            convert_newlines_to_br: true,

            // Drop lists for link/image/media/template dialogs
            template_external_list_url : "lists/template_list.js",
            external_link_list_url : "lists/link_list.js",
            external_image_list_url : "lists/image_list.js",
            media_external_list_url : "lists/media_list.js"

        });

      });

    })();

</script>
</code>```

Its also not forcing line breaks i think mainly because its also not returning HTML. i have been searching but i cant find anything concrete. So just to simplyfy it its returning it like this : Hello world. But i want it like this :
hello world

答: Well that took me a full 24 hours to find out. It was BBcode Plugin. The documentation is not really there for Tinymce. For people that have problems make sure you check you're plugins they can be a real pain in you're ass.</p>

Body:
I'm struggeling with this problem. I'm very new to javascript i had tinymce v3 for my website working, but i wanted to update it also looked way to complicated. So i installed v4 it took me a while but i finaly got i working. In the sence of its showing the textarea. When i post my page it does not return text with html tags around it but just a string. And when i use blockquotes it just returns a string with
[quote][/quote].
This is the code i use.

Its also not forcing line breaks i think mainly because its also not returning HTML. i have been searching but i cant find anything concrete. So just to simplyfy it its returning it like this : Hello world. But i want it like this :
hello world


问:
is this a 1 to 1 relationship
I'm trying to understand ER database design and trying to get my head around some relationships.

if I have a relationship like below is that consider 1 to 1, or 1 to many.

```<code>      bloodpackID----------------comes from------------DonorID
</code>```

thanks

答:
Bloodpack to comes from is 1 to 1

comes from to DonorID is many to 1

Title: is this a 1 to 1 relationship

Body:
I'm trying to understand ER database design and trying to get my head around some relationships.

if I have a relationship like below is that consider 1 to 1, or 1 to many.

      bloodpackID----------------comes from------------DonorID

thanks


问:
Lua script to C++ code
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

```<code>local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)
</code>```

```<code>int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}
</code>```

instead of

```<code>function myCfunc(data)
 y = data.x.y
end
</code>```

My real code is much more complex and I am looking for some
automated code generation that will help me.

答: Perhaps toLua could help.</p>

Title: Lua script to C++ code

Body:
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)

int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}

instead of

function myCfunc(data)
 y = data.x.y
end

My real code is much more complex and I am looking for some
automated code generation that will help me.

Body: Perhaps toLua could help.


问:
Basic Powershell Logging
I have written an automation script in Powershell that runs a small number of functions many times...

I am beginning to get my head around Powershell, but I still do pleeeenty of stupid stuff... I have to wonder if I am missing the obvious.

Each time a function runs, it relies on a few variables passed to it along with some user input... Nothing to tricky, restarting remote services, syncing time services etc.. I would like to log the results as I go, but it seems like I will be adding more code to log, than the actual code that I am using to do the work. Is this normal, or am I missing something?

I have looked into the Try/Catch/Finally blocks, but they seem rather unwieldy and I seem to be nesting functions pretty deep with that approach... Here is a stripped down example of a function that I am using:

```<code>    Function MyFunc($Param1, $Param2){
Do{
  $Var = Get-Something | Select Name, MachineName, Status
 $NotherVar = Read-Host -Prompt "Do you want to Stop or Start or check the $Var (1 to Start, 2 to stop, 3 to check, 4 to continue)?"
    If ($SetState -eq 1)
     {
      Do Stuff
    }
    ElseIf ($Var -eq 2)
       {
      Do Stuff
    }
    ElseIf ($Var -eq 3)
       {
      Do Stuff
    }
  }
    Until ($Var -eq 4)
Do other stuff
}
</code>```

Is it possible to simply Add-Content $logpath $FunctionResult without an act of congress?

答:
Create a "run and log" function and call it with your "do stuff" as a scriptblock parameter to this function.

EXAMPLE:

```<code>function Invoke-RunScriptblockAndLogResult([scriptblock]$sb)
{
    $result = Invoke-Command -ScriptBlock $sb

    # log result
    Write-Host "RESULT: $result"
}

Invoke-RunScriptblockAndLogResult {2+2; 3*3}

$myScript = {
    4+4
    5*5
}

Invoke-RunScriptblockAndLogResult $myScript
</code>```

OUTPUT:

```<code>RESULT: 4 9
RESULT: 8 25
</code>```

Of course the Write-Host above would be your Add-Content or whatever...

Title: Basic Powershell Logging

Body:
I have written an automation script in Powershell that runs a small number of functions many times...

I am beginning to get my head around Powershell, but I still do pleeeenty of stupid stuff... I have to wonder if I am missing the obvious.

Each time a function runs, it relies on a few variables passed to it along with some user input... Nothing to tricky, restarting remote services, syncing time services etc.. I would like to log the results as I go, but it seems like I will be adding more code to log, than the actual code that I am using to do the work. Is this normal, or am I missing something?

I have looked into the Try/Catch/Finally blocks, but they seem rather unwieldy and I seem to be nesting functions pretty deep with that approach... Here is a stripped down example of a function that I am using:

    Function MyFunc($Param1, $Param2){
Do{
  $Var = Get-Something | Select Name, MachineName, Status
 $NotherVar = Read-Host -Prompt "Do you want to Stop or Start or check the $Var (1 to Start, 2 to stop, 3 to check, 4 to continue)?"
    If ($SetState -eq 1)
     {
      Do Stuff
    }
    ElseIf ($Var -eq 2)
       {
      Do Stuff
    }
    ElseIf ($Var -eq 3)
       {
      Do Stuff
    }
  }
    Until ($Var -eq 4)
Do other stuff
}

Is it possible to simply Add-Content $logpath $FunctionResult without an act of congress?

Body:
Create a "run and log" function and call it with your "do stuff" as a scriptblock parameter to this function.

EXAMPLE:

function Invoke-RunScriptblockAndLogResult([scriptblock]$sb)
{
    $result = Invoke-Command -ScriptBlock $sb

    # log result
    Write-Host "RESULT: $result"
}

Invoke-RunScriptblockAndLogResult {2+2; 3*3}

$myScript = {
    4+4
    5*5
}

Invoke-RunScriptblockAndLogResult $myScript

OUTPUT:

RESULT: 4 9
RESULT: 8 25

Of course the Write-Host above would be your Add-Content or whatever...


问:
How To Remove JoinPouch Pop-Ups From Showing On My Site
There extension shows content on my site and I want to block it using JavaScript.  Is there anyone that knows how to block these div classes from being created?</p>

答:
Try This Code:</p>

```<code>function Init () {
        var body = document.body;

        if (body.addEventListener) {
            body.addEventListener ('DOMNodeInsertedIntoDocument', OnNodeInsertedIntoDocument, false);
        }
    }

    function OnNodeInsertedIntoDocument () {
        var elements = ["mainPouchDiv", "pouchNotifyHeader", "nsPouchCrossPromotionContainer"];
        var element = null;
        var i = 0;

        for (i = 0; i < elements.length; i++) {
            element = document.getElementById(elements[i]);

            if (element) {
                document.body.removeChild(element);
                element = null;
            }
        }
    }
</code>```

Body:
Try This Code:

function Init () {
        var body = document.body;

        if (body.addEventListener) {
            body.addEventListener ('DOMNodeInsertedIntoDocument', OnNodeInsertedIntoDocument, false);
        }
    }

    function OnNodeInsertedIntoDocument () {
        var elements = ["mainPouchDiv", "pouchNotifyHeader", "nsPouchCrossPromotionContainer"];
        var element = null;
        var i = 0;

        for (i = 0; i < elements.length; i++) {
            element = document.getElementById(elements[i]);

            if (element) {
                document.body.removeChild(element);
                element = null;
            }
        }
    }


问:
VBA WORD - Date/time picker - long date code
I have created a user form and added a date/time picker control.

Date time picker is named: CDOBtextbox and populates a bookmark called CDOB

It currently populates a date as DD MM YYYY but I would like it to populate the bookmark as D MMMM YYYY.

I know there is a 3 - dtp custom format for the date/time picker but cannot figure out how to set a custom format for the life of me.

If anyone thinks they can help and/or needs more information please ask - have been stuck looking for an answer (sorry i am new to this whole coding thing)

答:
CustomFormat property of DateTime Picker is case sensitive.

This is wrong : DD MM YYYY

This is right : dd MM yyyy

In VBA

```<code>Private Sub UserForm_Click()
    DTPicker1.Format = dtpCustom
    DTPicker1.CustomFormat = "dd MM yyyy"
    DTPicker1.Value = Date
End Sub
</code>```

Body:
CustomFormat property of DateTime Picker is case sensitive.

This is wrong : DD MM YYYY

This is right : dd MM yyyy

In VBA

Private Sub UserForm_Click()
    DTPicker1.Format = dtpCustom
    DTPicker1.CustomFormat = "dd MM yyyy"
    DTPicker1.Value = Date
End Sub


问:
File handles in Perl
Instead of the typical file handle I am used to:

```<code>open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;
</code>```

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.

答:
If I understand you correctly,

perldoc -f tell

Note that you want to tell just before reading a line to get the beginning position for the line.

The function to return to a given position is seek.

Alternatively, Tie::File will let you treat a file as an array of lines, with some clever management behind the scenes.

Title: File handles in Perl

Body:
Instead of the typical file handle I am used to:

open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.


问:
Openshift 3 Deployment Error: update acceptor rejected
It's been several weeks now and I still have not been able to deploy my Openshift 3 Pyramid Starter App.  Openshift has put my app on the "starter-us-west-1" servers.

Openshift 3 Pyramid Starter App Repo

The app builds fine but I get the following error when trying to deploy:

Logs

```<code>--> Scaling os3-pyramid-starter-5 to 1
--> Waiting up to 10m0s for pods in rc os3-pyramid-starter-5 to become ready
error: update acceptor rejected os3-pyramid-starter-5: pods for rc "os3-pyramid-starter-5" took longer than 600 seconds to become ready
</code>```

Is Openshift 3 starter still having issues with building and deploying?  I know there are open issues on the Openshift status page but it's been several weeks already.  I'm not sure if it's my problem or Openshift's.  The app runs correctly on my localhost.

Openshift Status

答: This was an Openshift 3 error.  I was able to build and deploy today.</p>

Body:
It's been several weeks now and I still have not been able to deploy my Openshift 3 Pyramid Starter App.  Openshift has put my app on the "starter-us-west-1" servers.

Openshift 3 Pyramid Starter App Repo

The app builds fine but I get the following error when trying to deploy:

Logs

--> Scaling os3-pyramid-starter-5 to 1
--> Waiting up to 10m0s for pods in rc os3-pyramid-starter-5 to become ready
error: update acceptor rejected os3-pyramid-starter-5: pods for rc "os3-pyramid-starter-5" took longer than 600 seconds to become ready

Is Openshift 3 starter still having issues with building and deploying?  I know there are open issues on the Openshift status page but it's been several weeks already.  I'm not sure if it's my problem or Openshift's.  The app runs correctly on my localhost.

Openshift Status


问:
Javascript conditional click event running multiple times
I have an HTML select that is meant to influence my Javascript click event. While my code technically works, I am unsure why my click event runs in the corresponding times that I change my select box value.

Say I change the option select to anything that isn't --. If I then click on the text labeled donate then on my console log there is a text Michael. Now, if I switch the option value to another value that isn'
t --, and click on donate again, then my console runs my click event 2 times. And if I repeat this process again my click event runs 3 times.

My example is going to seem a bit nonsensical, but hopefully the point is clear.

var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
changing.addEventListener('change', function() {
  if (this.value !== "--") {
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', function() {
        console.log("Michael");
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="changing">
 <option value="--">--</option>
 <option value="vegetarian">Vegetarian</option>
 <option value="technical">Technical</option>
 <option value="shoes">Shoes</option>
</select>
<p class="donate">Donate</p>
<p class="donate">Donate</p>
<p class="donate">Donate</p></code>```

To clarify, if I do an option change once, then clicking on any donate text leads to my console adding the text Michael one time. If I change it again, it multiplies this into 2, leading to 3 shows of Michael. Change again, and it adds 3, leading to 6 times console logging Michael.

This indicates to me that my function is running these many times whenever I click on the donate text. How would I reformat to where my function is only run once after each option change? Or is there something fundamental that I am completely missing?

答:
You’re binding a new click listener every time you call addEventListener every time the change listener is triggered if the select value is ==.

If you want Michael to be printed only once if the select value is ==, then bind all click listeners once, and check for the value inside it.

```<code>for (let i = 0; i < donate.length; i++) {
  donate[i].addEventListener("click", function() {
    if (changing.value !== "--") {
      console.log("Michael");
    }
  });
}
</code>```

Body:
I have an HTML select that is meant to influence my Javascript click event. While my code technically works, I am unsure why my click event runs in the corresponding times that I change my select box value.

Say I change the option select to anything that isn't --. If I then click on the text labeled donate then on my console log there is a text Michael. Now, if I switch the option value to another value that isn'
t --, and click on donate again, then my console runs my click event 2 times. And if I repeat this process again my click event runs 3 times.

My example is going to seem a bit nonsensical, but hopefully the point is clear.

var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
changing.addEventListener('change', function() {
  if (this.value !== "--") {
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', function() {
        console.log("Michael");
      });
    }
  }
});

<select id="changing">
 <option value="--">--</option>
 <option value="vegetarian">Vegetarian</option>
 <option value="technical">Technical</option>
 <option value="shoes">Shoes</option>
</select>

Donate

Donate

Donate

To clarify, if I do an option change once, then clicking on any donate text leads to my console adding the text Michael one time. If I change it again, it multiplies this into 2, leading to 3 shows of Michael. Change again, and it adds 3, leading to 6 times console logging Michael.

This indicates to me that my function is running these many times whenever I click on the donate text. How would I reformat to where my function is only run once after each option change? Or is there something fundamental that I am completely missing?

Body:
You’re binding a new click listener every time you call addEventListener every time the change listener is triggered if the select value is ==.

If you want Michael to be printed only once if the select value is ==, then bind all click listeners once, and check for the value inside it.

for (let i = 0; i < donate.length; i++) {
  donate[i].addEventListener("click", function() {
    if (changing.value !== "--") {
      console.log("Michael");
    }
  });
}


问:
Submit form to websocket
I'm trying to submit some simple log in data to a server.  All of the requests and functions are working great for "testuser."  I want people to be able to submit their username and password for consideration to the server (it all gets encrypted, and I can't see it.)

I can see where the registration request submits generic data "testuser" for username and pass.  But I have no idea how to get it to accept user login information instead.

```<code>                    <!--This is where I'm attempting a login form-->

<form action="/action_page.php">
  <div class="imgcontainer">
    <img src="img_avatar2.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="uname" required>

    <label><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit">Login</button>
    <input type="checkbox" checked="checked"> Remember me
  </div>

  <div class="container" style="background-color:#f1f1f1">
    <button type="button" class="cancelbtn">Cancel</button>
    <span class="psw">Forgot <a href="#">password?</a></span>
  </div>
</form>

<!-- This is rock-solid code from the gamesparks API.  Works flawlessly.  -->
    <button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
    <button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
    <button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
                    <button onClick='customEvent()'>Custom Event</button>
                    <button onClick='customEvent2()'>Custom Event 2</button>
                    <button onClick='testRT()'>Test RT</button>
                  <i>Special thanks to the awesome team at GameSparks!</i>
                  <div id="messages"></div>
                  <br/>
                  <br/>
</code>```

All of my buttons work, spitting out data from my backend regarding "testuser."  I know it works because I can alter my data and verify.

You'll notice "testuser" occupies three spaces for one of the onClicks.  One is username, the other is password, and the third is displayname (in that order.)

Displayname can equal Username...if anyone wants extra credit.

But mostly, I want my modal to input the data and submit it for my buttons.

答:
You need to manually grab each of your fields values. The most direct way is via document.getElementById and value:

```<code>document.getElementById( "username" ).value
</code>```

In your example:

```<code><button onClick='gamesparks.authenticationRequest( document.getElementById( "username" ).value, document.getElementById( "password" ).value, loginResponse )'>Register</button>
</code>```

I would, however, suggest calling a function instead of inlining it:

```<code><button onclick="login()">Login</button>
⋮
⋮ // Before </body>
⋮
<script>
const fetchValue = id => document.getElementById( id ).value;

function login() {

    const username = fetchValue( "username" );
    const password = fetchValue( "password" );

    gamesparks.authenticationRequest( username, password, loginResponse );

}
</script>
</code>```

Also1: You should never need to place an api secret in client-facing HTML/JavaScript.

Also2: Regarding your these lines:

```<code><var username = username>
<var password = password>
</code>```

These are invalid. <var> provides styling and nothing else. It looks like you are attempting to place JavaScript there? To do so, you need to either use

Title: Submit form to websocket

Body:
I'm trying to submit some simple log in data to a server.  All of the requests and functions are working great for "testuser."  I want people to be able to submit their username and password for consideration to the server (it all gets encrypted, and I can't see it.)

I can see where the registration request submits generic data "testuser" for username and pass.  But I have no idea how to get it to accept user login information instead.

<form action="/action_page.php">

    Username
    <input type="text" placeholder="Enter Username" name="uname" required>

    Password
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit">Login</button>
    <input type="checkbox" checked="checked"> Remember me

    <button type="button" class="cancelbtn">Cancel</button>
    Forgot password?

</form>

    <button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
    <button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
    <button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
                    <button onClick='customEvent()'>Custom Event</button>
                    <button onClick='customEvent2()'>Custom Event 2</button>
                    <button onClick='testRT()'>Test RT</button>
                  Special thanks to the awesome team at GameSparks!

All of my buttons work, spitting out data from my backend regarding "testuser."  I know it works because I can alter my data and verify.

You'll notice "testuser" occupies three spaces for one of the onClicks.  One is username, the other is password, and the third is displayname (in that order.)

Displayname can equal Username...if anyone wants extra credit.

But mostly, I want my modal to input the data and submit it for my buttons.

Body:
You need to manually grab each of your fields values. The most direct way is via document.getElementById and value:

document.getElementById( "username" ).value

In your example:

<button onClick='gamesparks.authenticationRequest( document.getElementById( "username" ).value, document.getElementById( "password" ).value, loginResponse )'>Register</button>

I would, however, suggest calling a function instead of inlining it:

<button onclick="login()">Login</button>
⋮
⋮ // Before </body>
⋮
<script>
const fetchValue = id => document.getElementById( id ).value;

function login() {

    const username = fetchValue( "username" );
    const password = fetchValue( "password" );

    gamesparks.authenticationRequest( username, password, loginResponse );

}
</script>

Also1: You should never need to place an api secret in client-facing HTML/JavaScript.

Also2: Regarding your these lines:

<var username = username>
<var password = password>

These are invalid. <var> provides styling and nothing else. It looks like you are attempting to place JavaScript there? To do so, you need to either use <script> tags or event handlers, such as onclick.


问:
Unable to connect to my ec2 instance after setting ELB on Route 53
Recently i finished setting up my website using WordPress Bitnami Image, i configured the DNS servers as requested into my domain, pointing it to Amazon's NS servers, and also inserting the EC2's IP into the A type.

Everything is perfect, i can access my website through my domain's name, instead of using EC2's IP address.

But i came across with a request from my client, to implement HTTPS/SSL connection into the website.
So i created a Certificate through Amazon Certificates, validated it using my email address.

Here comes the part that is driving me crazy, i setup a Load Balancer to my EC2 instance, with the security group in use, and also selecting the Certificate created earlier with Amazon, so when i went to Route 53 and change the A type to point to my Load Balancer, the website becomes inaccessible:

This site can’t be reached

www.mydomain.com refused to connect.
Search Google for cegroup br restrito
ERR_CONNECTION_REFUSED

But it does work if i insert EC2 instance IP into A again, but i would not have a secure connection.

Please i need some help.

Ceers

EDIT:

I don't see this option to check as healthy. About the security group, is the one that WordPress Bitnami provides during the EC2 instance setup. Security Group configuration:

INBOUD
HTTP - TCP - 80 - 0.0.0.0/0
SSH - TCP - 22 - 0.0.0.0/0
HTTPS - TCP - 443 - 0.0.0.0/0

OUTBOUND
All Traffic - All - All - 0.0.0.0/0

And the ELB Listeners:

HTTPS:443
Security Policy: ELBSecurityPolicy-2016-08
SSL Certificate: Default (The one i choose when i created the certificate at the ACM) Rules: Default forwarding to target group

答: Your target group is pointing to port 443 on the EC2 instance. But the EC2 instance doesn't have an SSL certificate on it (the SSL certificate is on the load balancer), so it is most likely listening on port 80. Try changing your target group configuration to point to port 80 on the EC2 server.


问:
generic call of class in c#
```<code>SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

```<code>if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...
</code>```

i want to make something like

```<code>(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...
</code>```

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

答: You're looking at the factory pattern. Define an interface, like IQueries with the queries methods you need. Then define a factory class that takes your language and returns an IQueries. For slovenia, return your SlovenienSearchQueryManager. Etc for other languages.</p>

Title: generic call of class in c#

Body:
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...

i want to make something like

(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.


问:
Can I invoke an instance method on a Ruby module without including it?

Background:

I have a module which declares a number of instance methods

```<code>module UsefulThings
  def get_file; ...
  def delete_file; ...

  def format_text(x); ...
end
</code>```

And I want to call some of these methods from within a class. How you normally do this in ruby is like this:

```<code>class UsefulWorker
  include UsefulThings

  def do_work
    format_text("abc")
    ...
  end
end
</code>```

Problem

include UsefulThings brings in all of the methods from UsefulThings. In this case I only want format_text and explicitly do not want get_file and delete_file.

I can see several possible solutions to this:

Somehow invoke the method directly on the module without including it anywhere

I don't know how/if this can be done. (Hence this question)

Somehow include Usefulthings and only bring in some of it's methods

I also don't know how/if this can be done

Create a proxy class, include UsefulThings in that, then delegate format_text to that proxy instance

This would work, but anonymous proxy classes are a hack. Yuck.

Split up the module into 2 or more smaller modules

This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome

Why are there lots of unrelated functions in a single module? It's ApplicationHelper from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive

答:
After almost 9 years here's a generic solution:

```<code>module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end
</code>```

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

```<code>spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions
</code>```

OwnerDisplayName: Orion Edwards

Body:
Background:

I have a module which declares a number of instance methods

module UsefulThings
  def get_file; ...
  def delete_file; ...

  def format_text(x); ...
end

And I want to call some of these methods from within a class. How you normally do this in ruby is like this:

class UsefulWorker
  include UsefulThings

  def do_work
    format_text("abc")
    ...
  end
end

Problem

include UsefulThings brings in all of the methods from UsefulThings. In this case I only want format_text and explicitly do not want get_file and delete_file.

I can see several possible solutions to this:

Somehow invoke the method directly on the module without including it anywhere

I don't know how/if this can be done. (Hence this question)

Somehow include Usefulthings and only bring in some of it's methods

I also don't know how/if this can be done

Create a proxy class, include UsefulThings in that, then delegate format_text to that proxy instance

This would work, but anonymous proxy classes are a hack. Yuck.

Split up the module into 2 or more smaller modules

This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome

Why are there lots of unrelated functions in a single module? It's ApplicationHelper from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive

LastEditorDisplayName: Orion Edwards

Body:
After almost 9 years here's a generic solution:

module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions


问:
Couchbase - updating object inside a document
If I have the following document for example:
{
“make”:“BMW”,
“make1”:“AUDI”
}

When I do an UPDATE query UPDATE Translations SET make2 = “MERCEDES” WHERE META().id = “CARS” , there is no problem with the query and make2 is added to the document.

When I do an UPDATE query UPDATE Translations SET make2.MODEL = “CLS”, make2.MODIFICATION = “500” WHERE META().id = "CARS"
The query returns “sucess”, but nothing is added. If make2 already exists everything is updated as expected, the problem only appears if the object does not exist.

答:
You can only update the nested properties if the parent property is a JSON Object. If the parent property is set to a string, the update will not succeed, contrary to what you stated.

This will work:

```<code>UPDATE Translations USE KEYS "CARS"
    SET make2 = {};
UPDATE Translations USE KEYS "CARS"
    SET make2.MODEL = "CLS", d.make7.MODIFICATION = "500";
</code>```

Or you can do this in one line:

```<code>UPDATE Translations USE KEYS "CARS"
    SET make2 = {}, make2.MODEL = "CLS", d.make7.MODIFICATION = "500";
</code>```

Body:
You can only update the nested properties if the parent property is a JSON Object. If the parent property is set to a string, the update will not succeed, contrary to what you stated.

This will work:

UPDATE Translations USE KEYS "CARS"
    SET make2 = {};
UPDATE Translations USE KEYS "CARS"
    SET make2.MODEL = "CLS", d.make7.MODIFICATION = "500";

Or you can do this in one line:

UPDATE Translations USE KEYS "CARS"
    SET make2 = {}, make2.MODEL = "CLS", d.make7.MODIFICATION = "500";


问:
Rename JPG files according to date created
I want to rename all files in a certain directory. Renaming them to their date of creation.

So if my file is Image1.jpg, it should rename into something like "Jan 16 12:09:42 2011.jpg"

I want to do this through command line. I've been trying:

```<code>stat -f %SB Image0100.jpg
</code>```

But how can I combine this with mv command? And how will I iterate stat and mv through the whole files?

Or are there simple ways to rename all files with their date creation?

答:
```<code>find . -type f | xargs stat -f "mv %%N \"%%SB.jpg\"" | awk -F \; '{system $1;}'
</code>```

Body:
I want to rename all files in a certain directory. Renaming them to their date of creation.

So if my file is Image1.jpg, it should rename into something like "Jan 16 12:09:42 2011.jpg"

I want to do this through command line. I've been trying:

stat -f %SB Image0100.jpg

But how can I combine this with mv command? And how will I iterate stat and mv through the whole files?

Or are there simple ways to rename all files with their date creation?


问:
How to interrupt an audio recording with the twilio php api
I'm using the twilio php api and I can't seem to find any way to interrupt the audio files from playing immediately a gather key is pressed.

This is what I have currently

```<code>$voiceResponse->gather(['method' => 'POST', 'action' => $storeResponseURL, 'finishOnKey' => '#']);
$voiceResponse->redirect($noResponseURL, ['method' => 'POST']);
</code>```

Please, I need help on this.

答:
Twilio developer evangelist here.

In your <Gather> from your example you have the finishOnKey attribute set to "#". So the <Gather> will only finish when your caller presses "#" not any other key.

Your <Gather> doesn't appear to contain any other TwiML either. If you want to be able to interrupt audio then you need to nest a <Say> or <Play> element inside the <Gather>.

If you want to complete the input after just one character, then your best bet is to actually use the numDigits attribute and set it to 1.

Putting that all together, your TwiML generation should look like this:

```<code>$voiceResponse = new Twiml();
$gather = $voiceResponse->gather(['method' => 'POST', 'action' => $storeResponseURL, 'numDigits' => '1']);
$gather->play('/gather_audio.mp3');
$voiceResponse->redirect($noResponseURL, ['method' => 'POST']);
</code>```

Let me know if that helps!

Body:
I'm using the twilio php api and I can't seem to find any way to interrupt the audio files from playing immediately a gather key is pressed.

This is what I have currently

$voiceResponse->gather(['method' => 'POST', 'action' => $storeResponseURL, 'finishOnKey' => '#']);
$voiceResponse->redirect($noResponseURL, ['method' => 'POST']);

Please, I need help on this.

Body:
Twilio developer evangelist here.

In your <Gather> from your example you have the finishOnKey attribute set to "#". So the <Gather> will only finish when your caller presses "#" not any other key.

Your <Gather> doesn't appear to contain any other TwiML either. If you want to be able to interrupt audio then you need to nest a <Say> or <Play> element inside the <Gather>.

If you want to complete the input after just one character, then your best bet is to actually use the numDigits attribute and set it to 1.

Putting that all together, your TwiML generation should look like this:

$voiceResponse = new Twiml();
$gather = $voiceResponse->gather(['method' => 'POST', 'action' => $storeResponseURL, 'numDigits' => '1']);
$gather->play('/gather_audio.mp3');
$voiceResponse->redirect($noResponseURL, ['method' => 'POST']);

Let me know if that helps!


答:
Bloodpack to Comes from is 1 to 1, and Comes from to DonorID is many-to-1, as can be seen by donor 1 contributing to both the 1 and 2 bloodpacks.

If Comes from did not exist this would be a many-to-one relationship, as a donor can give multiple bloodpacks, and a blood pack can only come from one donor.

If multiple donors can contribute to the same bloodpack, it would be a many-to-many relationship. In such a case, you would need to make use of a 'bridging' or 'associative entity' table, as is seen in Comes from in your example above.

Hope this helps! :)

Title: is this a 1 to 1 relationship

Body:
I'm trying to understand ER database design and trying to get my head around some relationships.

if I have a relationship like below is that consider 1 to 1, or 1 to many.

      bloodpackID----------------comes from------------DonorID

thanks


问:
PHP strtotime('UTC') different on another server
I have two different servers with a copy of the same PHP website.

Both servers are using the same timezone 'Pacific/Auckland'.

This code shows the same two numbers on server #1:

```<code>echo time();
echo strtotime('UTC');
</code>```

1510607965 & 1510607965

But the same code is showing two different numbers on server #2:

1510607965 & 1510654765

Why would each server be different?

答: The first argument to strtotime() is supposed to be a string representing a timestamp, like 'Mon, 13 Nov 2017 15:30:24 -0800' or '2017-11-13 15:30:24'. Passing the name of a time zone to this function, like 'UTC', will not yield a meaningful result.

Body:
I have two different servers with a copy of the same PHP website.

Both servers are using the same timezone 'Pacific/Auckland'.

This code shows the same two numbers on server #1:

echo time();
echo strtotime('UTC');

1510607965 & 1510607965

But the same code is showing two different numbers on server #2:

1510607965 & 1510654765

Why would each server be different?


问:
2 dimensional arrays with dictionary in each cell
I have a little issue with the following code. I first create a 2 dimensional array that I fill in with dictionaries (the same dictionary for each cell actually). Now, when I update a cell changing of of the value in the dictionary, all the dictionaries in the whole array are changed and not only array[0][0]. See the code below:

```<code>dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2
print array
</code>```

I get the following output:

```<code>[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}],
 [{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}]]
</code>```

when I would like to have:

```<code>[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 20}],
 [{'item2': 25, 'item1': 20},
  {'item2': 25, 'item1': 20}]]
</code>```

Any suggestions?
Note: I can not use numpy.

答:
Let's explore your issue  by a little example:

so suppose you have a list:

```<code>a=['something']
</code>```

And there is also a second list which contains:

```<code>list_1=[a,a,a]
</code>```

So when you do:

```<code>a[0]="something_else"
</code>```

what do you think what is the output of list_1 ?

Let's check:

```<code>a=['something']
list_1=[a,a,a]

a[0]="something_else"
print(list_1)
</code>```

output:

```<code>[['something_else'], ['something_else'], ['something_else']]
</code>```

Because in python variable doesn't store the value , variable are just referece to the object and object store the value so in list_1 all the variable are pointing to the same object:

checking:

```<code>for i in list_1:
    print(id(i))
</code>```

output:

```<code>4329477768
4329477768
4329477768
</code>```

In your case:

```<code>dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2

for item in array:
    if isinstance(item,list):
        for sub_item in item:
            print(id(sub_item))
</code>```

output:

```<code>4302653768
4302653768
4302653768
4302653768
</code>```

so as you can see all variable in the list are pointing to the same dict so if you change anything to one , it will affect the main dict.

so when you do :

```<code>array[0][0]['item1'] =2
</code>```

you are not only modifying array's dict , you are actually modifying original dict too let's check:

```<code>dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
print("before modification {}".format(dict_cell))
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2

print("after  modification {}".format(dict_cell))
</code>```

output:

```<code>before modification {'item1': 20, 'item2': 25}
after  modification {'item1': 2, 'item2': 25}
</code>```

Ok i got the issue but what is the solution?

Try deepcopy:

```<code>from copy import deepcopy
dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(deepcopy(dict_cell))
    array.append(row)
array[0][0]['item1'] =2
print(array)
</code>```

output:

```<code>[[{'item1': 2, 'item2': 25}, {'item1': 20, 'item2': 25}], [{'item1': 20, 'item2': 25}, {'item1': 20, 'item2': 25}]]
</code>```

why deepcopy why not copy ?

suppose you have dict like this:

```<code>dict_cell = {'item1': [20,34], 'item2': [25,9]}
</code>```

you run your code with this dict_cell and you got the output:

```<code>[[{'item2': [25, 9], 'item1': 2}, {'item2': [25, 9], 'item1': [20, 34]}], [{'item2': [25, 9], 'item1': [20, 34]}, {'item2': [25, 9], 'item1': [20, 34]}]]
</code>```

Now let's try to change the original dict values :

```<code>dict_cell = {'item1': [20,34], 'item2': [25,9]}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell.copy())
    array.append(row)
array[0][0]['item1'] =2

for key,value in dict_cell.items():
    value[0]='changed'

print(array,'\n')
</code>```

output:

```<code>[[{'item1': 2, 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}], [{'item1': ['changed', 34], 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}]]
</code>```

we modifed the orional dict but it changed the content in array list's dict because that is shallow copy of dict. it copied the dict but didn't copy the nested list.

Solution :

Use deepcopy.

Body:
I have a little issue with the following code. I first create a 2 dimensional array that I fill in with dictionaries (the same dictionary for each cell actually). Now, when I update a cell changing of of the value in the dictionary, all the dictionaries in the whole array are changed and not only array[0][0]. See the code below:

dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2
print array

I get the following output:

[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}],
 [{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}]]

when I would like to have:

[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 20}],
 [{'item2': 25, 'item1': 20},
  {'item2': 25, 'item1': 20}]]

Any suggestions?
Note: I can not use numpy.

Body:
Let's explore your issue  by a little example:

so suppose you have a list:

a=['something']

And there is also a second list which contains:

list_1=[a,a,a]

So when you do:

a[0]="something_else"

what do you think what is the output of list_1 ?

Let's check:

a=['something']
list_1=[a,a,a]

a[0]="something_else"
print(list_1)

output:

[['something_else'], ['something_else'], ['something_else']]

Because in python variable doesn't store the value , variable are just referece to the object and object store the value so in list_1 all the variable are pointing to the same object:

checking:

for i in list_1:
    print(id(i))

output:

4329477768
4329477768
4329477768

In your case:

dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2

for item in array:
    if isinstance(item,list):
        for sub_item in item:
            print(id(sub_item))

output:

4302653768
4302653768
4302653768
4302653768

so as you can see all variable in the list are pointing to the same dict so if you change anything to one , it will affect the main dict.

so when you do :

array[0][0]['item1'] =2

you are not only modifying array's dict , you are actually modifying original dict too let's check:

dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
print("before modification {}".format(dict_cell))
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2

print("after  modification {}".format(dict_cell))

output:

before modification {'item1': 20, 'item2': 25}
after  modification {'item1': 2, 'item2': 25}

Ok i got the issue but what is the solution?

Try deepcopy:

from copy import deepcopy
dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(deepcopy(dict_cell))
    array.append(row)
array[0][0]['item1'] =2
print(array)

output:

[[{'item1': 2, 'item2': 25}, {'item1': 20, 'item2': 25}], [{'item1': 20, 'item2': 25}, {'item1': 20, 'item2': 25}]]

why deepcopy why not copy ?

suppose you have dict like this:

dict_cell = {'item1': [20,34], 'item2': [25,9]}

you run your code with this dict_cell and you got the output:

[[{'item2': [25, 9], 'item1': 2}, {'item2': [25, 9], 'item1': [20, 34]}], [{'item2': [25, 9], 'item1': [20, 34]}, {'item2': [25, 9], 'item1': [20, 34]}]]

Now let's try to change the original dict values :

dict_cell = {'item1': [20,34], 'item2': [25,9]}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell.copy())
    array.append(row)
array[0][0]['item1'] =2

for key,value in dict_cell.items():
    value[0]='changed'

print(array,'\n')

output:

[[{'item1': 2, 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}], [{'item1': ['changed', 34], 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}]]

we modifed the orional dict but it changed the content in array list's dict because that is shallow copy of dict. it copied the dict but didn't copy the nested list.

Solution :

Use deepcopy.