问:
Replace multiple lines of console output with the contents of a Python array
Didn't know how to correctly write the title, so i will try to explain it here. I am making a game, similar to tic tac toe. The play field is 4x4 and i am saving it as an array. I want to make changes in the array during the game, but it will not print out the array each time, rather it makes changes statically.
Lets say at the beginning i print out the whole field and under it the user is asked to type a position. He gives it and the changes are being done in the first printed playfield, without calling it again in the shell. Kinda sloppy explanation, sorry about that.

```<code>play_field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

def print_playfield():
   for rows in play_field:
       print(*['{:<4}'.format(each) for each in rows])
</code>```

This is the function, which will display the playfield.I've done it with tkinter already, wanna try it without.

答:
You could try using the curses module

https://docs.python.org/3/library/curses.html

Body:
Didn't know how to correctly write the title, so i will try to explain it here. I am making a game, similar to tic tac toe. The play field is 4x4 and i am saving it as an array. I want to make changes in the array during the game, but it will not print out the array each time, rather it makes changes statically.
Lets say at the beginning i print out the whole field and under it the user is asked to type a position. He gives it and the changes are being done in the first printed playfield, without calling it again in the shell. Kinda sloppy explanation, sorry about that.

play_field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

def print_playfield():
   for rows in play_field:
       print(*['{:<4}'.format(each) for each in rows])

This is the function, which will display the playfield.I've done it with tkinter already, wanna try it without.


来源: stackexchange

问:
Angular async not resolving timeouts
It looks like Angular's async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well.
 Unfortunately, I haven't been able to reproduce this bug on any kind of Plunkr or JSFiddle.

The easiest way to recreate it is to simple create a fresh new Angular CLI app and paste this code into the app.component.spec.ts:

```<code>import { async } from "@angular/core/testing";

describe("test async", () => {

   let count: number = 0;

   beforeEach(async(() => {
       count++;
       console.log('async before test ' + count);
       setTimeout(() => {
           console.log('timeout before test ' + count);
       }, 1000);
   }))

   it("async test 1", async(() => {
       console.log('starting test 1');
       setTimeout(() => {
           console.log('test 1 finished');
           console.log('expected count: 1, actual count: ' + count);
           expect(count).toBe(1, "should be test 1");
       }, 2000);
   }));

   it("async test 2", async(() => {
       console.log('starting test 2');
       setTimeout(() => {
           console.log('test 2 finished');
           console.log('expected count: 2, actual count: ' + count);
           expect(count).toBe(2, "should be test 2");
       }, 2000);
   }));

   it("async test 3", async(() => {
       console.log('starting test 3');
       setTimeout(() => {
           console.log('test 3 finished');
           console.log('expected count: 3, actual count: ' + count);
           expect(count).toBe(3, "should be test 3");
       }, 2000);
   }));
});
</code>```

If you then run this test, you should see the output as follows:

```<code>async before test 1
timeout before test 1
starting test 1
async before test 2
timeout before test 2
starting test 2
async before test 3
test 1 finished
expected count: 1, actual count: 3
timeout before test 3
starting test 3
test 2 finished
expected count: 2, actual count: 3
test 3 finished
expected count: 3, actual count: 3
</code>```

But that is incorrect from my understanding because the timeouts in the tests should complete before the next test starts, which is the whole point of async.

This is what the output would look like if it was working correctly:

```<code>async before test 1
timeout before test 1
starting test 1
test 1 finished
expected count: 1, actual count: 1
async before test 2
timeout before test 2
starting test 2
test 2 finished
expected count: 2, actual count: 2
async before test 3
timeout before test 3
starting test 3
test 3 finished
expected count: 3, actual count: 3
</code>```

Any help would be greatly appreciated, thanks!

答: As of writing this, it's a bug with Angular.  I've found 2 tickets confirming this: #16647 and #12115</p>

ContentLicense: CC BY-SA 3.0

Title: Angular async not resolving timeouts

Body:
It looks like Angular's async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well.
 Unfortunately, I haven't been able to reproduce this bug on any kind of Plunkr or JSFiddle.

The easiest way to recreate it is to simple create a fresh new Angular CLI app and paste this code into the app.component.spec.ts:

import { async } from "@angular/core/testing";

describe("test async", () => {

   let count: number = 0;

   beforeEach(async(() => {
       count++;
       console.log('async before test ' + count);
       setTimeout(() => {
           console.log('timeout before test ' + count);
       }, 1000);
   }))

   it("async test 1", async(() => {
       console.log('starting test 1');
       setTimeout(() => {
           console.log('test 1 finished');
           console.log('expected count: 1, actual count: ' + count);
           expect(count).toBe(1, "should be test 1");
       }, 2000);
   }));

   it("async test 2", async(() => {
       console.log('starting test 2');
       setTimeout(() => {
           console.log('test 2 finished');
           console.log('expected count: 2, actual count: ' + count);
           expect(count).toBe(2, "should be test 2");
       }, 2000);
   }));

   it("async test 3", async(() => {
       console.log('starting test 3');
       setTimeout(() => {
           console.log('test 3 finished');
           console.log('expected count: 3, actual count: ' + count);
           expect(count).toBe(3, "should be test 3");
       }, 2000);
   }));
});

If you then run this test, you should see the output as follows:

async before test 1
timeout before test 1
starting test 1
async before test 2
timeout before test 2
starting test 2
async before test 3
test 1 finished
expected count: 1, actual count: 3
timeout before test 3
starting test 3
test 2 finished
expected count: 2, actual count: 3
test 3 finished
expected count: 3, actual count: 3

But that is incorrect from my understanding because the timeouts in the tests should complete before the next test starts, which is the whole point of async.

This is what the output would look like if it was working correctly:

async before test 1
timeout before test 1
starting test 1
test 1 finished
expected count: 1, actual count: 1
async before test 2
timeout before test 2
starting test 2
test 2 finished
expected count: 2, actual count: 2
async before test 3
timeout before test 3
starting test 3
test 3 finished
expected count: 3, actual count: 3

Any help would be greatly appreciated, thanks!


问:
How can I pass parameters to gcc in Rust with Cargo?
I'm trying to build rust-sfml with cargo, but my gcc fails to find required libraries.

I want to solve this by passing -L options to gcc, but I can't find any convenient way for doing it.

Is there any possible simple solutions except using a build script?

$ cargo run
   Compiling sfml v0.9.3 (https://github.com/jeremyletang/rust-sfml#358f076a)
error: linking with `gcc` failed: exit code: 1
note: "gcc" "-Wl,--enable-long-section-names" "-fno-use-linker-plugin" "-Wl,--nxcompat" "-static-libgcc" "-m64" "-L" "C:\Program Files\Rust stable 1.1\bin\rustlib\x86_64-pc-windows-gnu\lib" "-o" "D:\Programming\Rust\test_proj\target\debug\deps\sfml-4cd3c268d09fd120.dll" "D:\Programming\Rust\test_proj\target\debug\deps\sfml-4cd3c268d09fd120.o" "D:\Programming\Rust\test_proj\target\debug\deps\sfml-4cd3c268d09fd120.metadata.o" "D:\Programming\Rust\test_proj\target\debug\deps\libbitflags-ab4a647a363172d8.rlib" "D:\Programming\Rust\test_proj\target\debug\deps\liblibc-2eda841eb12a3090.rlib" "-L" "C:\Program Files\Rust stable 1.1\bin\rustlib\x86_64-pc-windows-gnu\lib" "-lstd-7d23ff90" "-L" "D:\Programming\Rust\test_proj\target\debug\deps" "-L" "D:\Programming\Rust\test_proj\target\debug\deps" "-L" "C:\Program Files\Rust stable 1.1\bin\rustlib\x86_64-pc-windows-gnu\lib" "-L" "D:\Programming\Rust\test_proj\.rust\bin\x86_64-pc-windows-gnu" "-L" "D:\Programming\Rust\test_proj\bin\x86_64-pc-windows-gnu" "-Wl,--whole-archive" "-Wl,-Bstatic" "-Wl,--no-whole-archive" "-Wl,-Bdynamic" "-lcsfml-system" "-lcsfml-window" "-lcsfml-audio" "-lcsfml-graphics" "-lcsfml-network" "-lws2_32" "-luserenv" "-shared" "-lcompiler-rt"
note: ld: cannot find -lcsfml-system
ld: cannot find -lcsfml-window
ld: cannot find -lcsfml-audio
ld: cannot find -lcsfml-graphics
ld: cannot find -lcsfml-network
```

答: Set an environment variable LIBRARY_PATH which contains the directory you're trying to reference.</p>


问:
How to load data in 1 modal using Twig
I made a HTML Table which contains data from database. If I click the Title of one table row, a modal should open which contains the data of the row.

For now i solved it this way:

```<code><table>
{% for item in items %}
<tr>
    <td>
        <td><a href="#" data-toggle="modal" data-target="modal{{ item.id }}">{{ item.name }}</a></td>
    </td>
</tr>
{% endfor %}
</table>

{% for item in items %}
<div class="modal" id="modal{{ item.id }}">
  <div class="modal-dialog" role="document">
      <div class="modal-content">
      <h5 class="modal-title">ID: {{ item.id }}</h5>
      ...
      </div>
  </div>
</div>
</code>```

It is working now, no way. But as you can see, for each item in the array a modal will be created. So for example if I have 9000 Items in the array. I will have 9000 Modals in HTML. I guess thats not good so Im searching a way for using only 1 modal and including its content based on the ID.

How can I do this or what is the best way to do this using twig and PHP (not symfony framework, only twig engine) ?

I am using Bootstrap 4 for my Modal / Table.

EDIT:

@entio linked me to a similar Question, so I tried it out.
First I followed entio's Answer to encode my $tickets (the Array which contains all the data) to json:

```<code>{% autoescape %}
    var globalDataObject = {{ tickets|json_encode()|raw }};
{% endautoescape %}
</code>```

The Json Object looks like this:

```<code>0:
    0: "93"
    1: "3"
    2: "Testticket"
    3: "0"
    4: ""
    5: "2017-12-08 14:43:21"
    6: "0000-00-00 00:00:00"
    7: "2017-12-08 14:43:21"
    8: "test"
    9: "Test"
    description: "test"
    subject: "Testticket"
    closed_at: "0000-00-00 00:00:00"
    closemessage: null
    device: "Test"
    customerid: "3"
    last_answer: "2017-12-08 14:43:21"
    opened_at: "2017-12-08 14:43:21"
    state: "0"
    ticketid: "93"
1:
    0: "94"
[...]
</code>```

My problem now is that I don't know how to get access to this json Object.
The answer of entio's linked question doesn't help me out. My current Code (copy % paste with some changes of the linked answer):

```<code><script type="text/javascript">
    {% autoescape %}
    var globalDataObject = {{ tickets|json_encode()|raw }};
    {% endautoescape %}

    (function($) {
    var myModal = $('#ticketModal');
    $('#subject').on('click', function(){
        $.ajax({
          type: 'GET',
          url: 'home.php?ticketid='+$(this).data('id'),
          dataType: 'json',
          success: function(data){
            htmlData = '<h1>Test:'+data.subject';
            myModal.find('.modal-body').html(htmlData);
            modal.modal('show);
          }
       });
       return false;
   });
})(jQuery);
</script>
</code>```

The HTML Code of my Table Rows are changed to:

```<code><td><a href="#" id="subject" data-id="{{ ticket.ticketid }}">{{ ticket.subject}}</a></td>
</code>```

So the data-id for all the rows in the tabel are the database id's.
How I can search for the right Item in the Json now and open a Modal containing data from the json object ?

The current Javascript Code is not working. I guess it's because I never get access to the globalDataObject.

答:
If you don't wanna involve JS then you have to generate all the nodes.

Otherwise, you can just pass an object with all your data to JS and let it dynamically create modal on click event. Parsing to json can be done with json_encode filter:

```<code><script type="text/javascript">
    var globalDataObject = {{ yourDataObject|json_encode() }};
</script>
</code>```

This is somewhat related so you can learn from it's answers:
Load JSON data into a Bootstrap modal

Title: How to load data in 1 modal using Twig

Body:
I made a HTML Table which contains data from database. If I click the Title of one table row, a modal should open which contains the data of the row.

For now i solved it this way:

{% for item in items %}

        {{ item.name }}

{% endfor %}

{% for item in items %}

ID: {{ item.id }}

      ...

It is working now, no way. But as you can see, for each item in the array a modal will be created. So for example if I have 9000 Items in the array. I will have 9000 Modals in HTML. I guess thats not good so Im searching a way for using only 1 modal and including its content based on the ID.

How can I do this or what is the best way to do this using twig and PHP (not symfony framework, only twig engine) ?

I am using Bootstrap 4 for my Modal / Table.

EDIT:

@entio linked me to a similar Question, so I tried it out.
First I followed entio's Answer to encode my $tickets (the Array which contains all the data) to json:

{% autoescape %}
    var globalDataObject = {{ tickets|json_encode()|raw }};
{% endautoescape %}

The Json Object looks like this:

0:
    0: "93"
    1: "3"
    2: "Testticket"
    3: "0"
    4: ""
    5: "2017-12-08 14:43:21"
    6: "0000-00-00 00:00:00"
    7: "2017-12-08 14:43:21"
    8: "test"
    9: "Test"
    description: "test"
    subject: "Testticket"
    closed_at: "0000-00-00 00:00:00"
    closemessage: null
    device: "Test"
    customerid: "3"
    last_answer: "2017-12-08 14:43:21"
    opened_at: "2017-12-08 14:43:21"
    state: "0"
    ticketid: "93"
1:
    0: "94"
[...]

My problem now is that I don't know how to get access to this json Object.
The answer of entio's linked question doesn't help me out. My current Code (copy % paste with some changes of the linked answer):

The HTML Code of my Table Rows are changed to:

{{ ticket.subject}}

So the data-id for all the rows in the tabel are the database id's.
How I can search for the right Item in the Json now and open a Modal containing data from the json object ?

The current Javascript Code is not working. I guess it's because I never get access to the globalDataObject.

Body:
If you don't wanna involve JS then you have to generate all the nodes.

Otherwise, you can just pass an object with all your data to JS and let it dynamically create modal on click event. Parsing to json can be done with json_encode filter:

<script type="text/javascript">
    var globalDataObject = {{ yourDataObject|json_encode() }};
</script>

This is somewhat related so you can learn from it's answers:
Load JSON data into a Bootstrap modal


问:
on keydown execute function and and pause the execution of the next function JS
For now I have that when key is down it changes colours, and as soon as it is up it changes back. But this is really quick and kinda causes migraine effect.

I want to do so when the key is pressed it would keep the changes for a second or two and then changes back to original colours without pausing any other function that is not inside these ones.

$(window).on('keydown', function (e) {
    if (e.keyCode == 39 || e.keyCode == 32) {
      $('body').css('background', '#26A65B');
      $('#word').css('color', '#415A77');
    }
    if(e.keyCode == 37) {
      $('body').css('background', '#D64541');
      $('#word').css('color', '#415A77');
    }
  });
$(window).on ('keyup', function (e) {
    if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
      $('body').css('background', '#415A77');
      $('#word').css('color', '#ed7d3a');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
Something among this lines should help you. You have to put some flag variable as helper, because only setTimeout would not help you,, cause each new keydown would just break setTimeout and then increase chances of migraine effects :)

Test it with left and right arrow keys:

$('body').focus();
var flag = false;
$(window).on('keydown', function (e) {
    if (flag) return;
    if (e.keyCode == 39 || e.keyCode == 32) {
      $('body').css('background', '#26A65B');
      $('#word').css('color', '#415A77');
    }
    if(e.keyCode == 37) {
      $('body').css('background', '#D64541');
      $('#word').css('color', '#415A77');
    }
  });
$(window).on ('keyup', function (e) {
    if( flag ) return;
    if( ! flag ) flag = true;
    setTimeout( function(){
      flag = false;
      if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
        $('body').css('background', '#415A77');
        $('#word').css('color', '#ed7d3a');
      }
    }, 2000);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
Something among this lines should help you. You have to put some flag variable as helper, because only setTimeout would not help you,, cause each new keydown would just break setTimeout and then increase chances of migraine effects :)

Test it with left and right arrow keys:

$('body').focus();
var flag = false;
$(window).on('keydown', function (e) {
    if (flag) return;
    if (e.keyCode == 39 || e.keyCode == 32) {
      $('body').css('background', '#26A65B');
      $('#word').css('color', '#415A77');
    }
    if(e.keyCode == 37) {
      $('body').css('background', '#D64541');
      $('#word').css('color', '#415A77');
    }
  });
$(window).on ('keyup', function (e) {
    if( flag ) return;
    if( ! flag ) flag = true;
    setTimeout( function(){
      flag = false;
      if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
        $('body').css('background', '#415A77');
        $('#word').css('color', '#ed7d3a');
      }
    }, 2000);
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
CSS3 specifications on w3.org
http://www.w3.org/TR/css3-roadmap/

Hasn't CSS3 been out since a while now? Why is most of the specification not complete?

Is there a complete reference anywhere on the web (or in a book)?

答:
This work takes time, a lot to be done.

Check "CSS3 for Web Designers"
http://books.alistapart.com/products/css3-for-web-designers

ContentLicense: CC BY-SA 2.5

Title: CSS3 specifications on w3.org


问:
"Failed to import pydot" throws in kerasR
I use the package keras under R and I would like to know if there was a command like python with plot_model () which allows to display its neuron network

```<code>library(keras)
</code>```

for example I would like to display this neural network under R

```<code>  model <- keras_model_sequential()
  model %>%
    layer_dense(units = 5, input_shape = 2) %>%
    layer_activation("relu") %>%
    layer_dense(units = 1)
</code>```

I install package kerasR for use the function plot_model(), but i have this error.

```<code>> library(kerasR)
> plot_model(model)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.

Detailed traceback:
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 131, in plot_model
    dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 52, in model_to_dot
    _check_pydot()
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 27, in _check_pydot
    raise ImportError('Failed to import pydot. You must install pydot'
</code>```

I'm use windows 10 64 bits, i use RStudio with Anaconda

In [4] pydot.Dot.create(pydot.Dot())

```<code>Out[4]: b"%!PS-Adobe-3.0\r\n%%Creator: graphviz version 2.38.0 (20140413.2041)\r\n%%Title: G\r\n%%Pages: (atend)\r\n%%BoundingBox: (atend)\r\n%%EndComments\r\nsave\r\n%%BeginProlog\r\n/DotDict 200 dict def\r\nDotDict begin\r\n\r\n/setupLatin1 {\r\nmark\r\n/EncodingVector 256 array def\r\n EncodingVector 0\r\n\r\nISOLatin1Encoding 0 255 getinterval putinterval\r\nEncodingVector 45 /hyphen put\r\n\r\n% Set up ISO Latin 1 character encoding\r\n/starnetISO {\r\n        dup dup findfont dup length dict begin\r\n        { 1 index /FID ne { def }{ pop pop } ifelse\r\n        } forall\r\n        /Encoding EncodingVector def\r\n        currentdict end definefont\r\n} def\r\n/Times-Roman starnetISO def\r\n/Times-Italic starnetISO def\r\n/Times-Bold starnetISO def\r\n/Times-BoldItalic starnetISO def\r\n/Helvetica starnetISO def\r\n/Helvetica-Oblique starnetISO def\r\n/Helvetica-Bold starnetISO def\r\n/Helvetica-BoldOblique starnetISO def\r\n/Courier starnetISO def\r\n/Courier-Oblique starnetISO def\r\n/Courier-Bold starnetISO def\r\n/Courier-BoldOblique starnetISO def\r\ncleartomark\r\n} bind def\r\n\r\n%%BeginResource: procset graphviz 0 0\r\n/coord-font-family /Times-Roman def\r\n/default-font-family /Times-Roman def\r\n/coordfont coord-font-family findfont 8 scalefont def\r\n\r\n/InvScaleFactor 1.0 def\r\n/set_scale {\r\n       dup 1 exch div /InvScaleFactor exch def\r\n       scale\r\n} bind def\r\n\r\n% styles\r\n/solid { [] 0 setdash } bind def\r\n/dashed { [9 InvScaleFactor mul dup ] 0 setdash } bind def\r\n/dotted { [1 InvScaleFactor mul 6 InvScaleFactor mul] 0 setdash } bind def\r\n/invis {/fill {newpath} def /stroke {newpath} def /show {pop newpath} def} bind def\r\n/bold { 2 setlinewidth } bind def\r\n/filled { } bind def\r\n/unfilled { } bind def\r\n/rounded { } bind def\r\n/diagonals { } bind def\r\n/tapered { } bind def\r\n\r\n% hooks for setting color \r\n/nodecolor { sethsbcolor } bind def\r\n/edgecolor { sethsbcolor } bind def\r\n/graphcolor { sethsbcolor } bind def\r\n/nopcolor {pop pop pop} bind def\r\n\r\n/beginpage {\t% i j npages\r\n\t/npages exch def\r\n\t/j exch def\r\n\t/i exch def\r\n\t/str 10 string def\r\n\tnpages 1 gt {\r\n\t\tgsave\r\n\t\t\tcoordfont setfont\r\n\t\t\t0 0 moveto\r\n\t\t\t(\\() show i str cvs show (,) show j str cvs show (\\)) show\r\n\t\tgrestore\r\n\t} if\r\n} bind def\r\n\r\n/set_font {\r\n\tfindfont exch\r\n\tscalefont setfont\r\n} def\r\n\r\n% draw text fitted to its expected width\r\n/alignedtext {\t\t\t% width text\r\n\t/text exch def\r\n\t/width exch def\r\n\tgsave\r\n\t\twidth 0 gt {\r\n\t\t\t[] 0 setdash\r\n\t\t\ttext stringwidth pop width exch sub text length div 0 text ashow\r\n\t\t} if\r\n\tgrestore\r\n} def\r\n\r\n/boxprim {\t\t\t\t% xcorner ycorner xsize ysize\r\n\t\t4 2 roll\r\n\t\tmoveto\r\n\t\t2 copy\r\n\t\texch 0 rlineto\r\n\t\t0 exch rlineto\r\n\t\tpop neg 0 rlineto\r\n\t\tclosepath\r\n} bind def\r\n\r\n/ellipse_path {\r\n\t/ry exch def\r\n\t/rx exch def\r\n\t/y exch def\r\n\t/x exch def\r\n\tmatrix currentmatrix\r\n\tnewpath\r\n\tx y translate\r\n\trx ry scale\r\n\t0 0 1 0 360 arc\r\n\tsetmatrix\r\n} bind def\r\n\r\n/endpage { showpage } bind def\r\n/showpage { } def\r\n\r\n/layercolorseq\r\n\t[\t% layer color sequence - darkest to lightest\r\n\t\t[0 0 0]\r\n\t\t[.2 .8 .8]\r\n\t\t[.4 .8 .8]\r\n\t\t[.6 .8 .8]\r\n\t\t[.8 .8 .8]\r\n\t]\r\ndef\r\n\r\n/layerlen layercolorseq length def\r\n\r\n/setlayer {/maxlayer exch def /curlayer exch def\r\n\tlayercolorseq curlayer 1 sub layerlen mod get\r\n\taload pop sethsbcolor\r\n\t/nodecolor {nopcolor} def\r\n\t/edgecolor {nopcolor} def\r\n\t/graphcolor {nopcolor} def\r\n} bind def\r\n\r\n/onlayer { curlayer ne {invis} if } def\r\n\r\n/onlayers {\r\n\t/myupper exch def\r\n\t/mylower exch def\r\n\tcurlayer mylower lt\r\n\tcurlayer myupper gt\r\n\tor\r\n\t{invis} if\r\n} def\r\n\r\n/curlayer 0 def\r\n\r\n%%EndResource\r\n%%EndProlog\r\n%%BeginSetup\r\n14 default-font-family set_font\r\n1 setmiterlimit\r\n% /arrowlength 10 def\r\n% /arrowwidth 5 def\r\n\r\n% make sure pdfmark is harmless for PS-interpreters other than Distiller\r\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse\r\n% make '<<' and '>>' safe on PS Level 1 devices\r\n/languagelevel where {pop languagelevel}{1} ifelse\r\n2 lt {\r\n    userdict (<<) cvn ([) cvn load put\r\n    userdict (>>) cvn ([) cvn load put\r\n} if\r\n\r\n%%EndSetup\r\nsetupLatin1\r\n%%Page: 1 1\r\n%%PageBoundingBox: 36 36 44 44\r\n%%PageOrientation: Portrait\r\n0 0 1 beginpage\r\ngsave\r\n36 36 8 8 boxprim clip newpath\r\n1 1 set_scale 0 rotate 40 40 translate\r\nendpage\r\nshowpage\r\ngrestore\r\n%%PageTrailer\r\n%%EndPage: 1\r\n%%Trailer\r\n%%Pages: 1\r\n%%BoundingBox: 36 36 44 44\r\nend\r\nrestore\r\n%%EOF\r\n"
</code>```

答:
You should install the Python libraries:

```<code>pip install pydot graphviz
</code>```

And also you need to download the graphviz binaries, and these are not installed with Python.

On Ubuntu you can install them with apt:

```<code>apt-get install -y graphviz libgraphviz-dev
</code>```

On osX with brew:

```<code>brew install graphviz
</code>```

For Windows and other operating systems, the instructions can be found at http://www.graphviz.org/

Body:
I use the package keras under R and I would like to know if there was a command like python with plot_model () which allows to display its neuron network

library(keras)

for example I would like to display this neural network under R

  model <- keras_model_sequential()
  model %>%
    layer_dense(units = 5, input_shape = 2) %>%
    layer_activation("relu") %>%
    layer_dense(units = 1)

I install package kerasR for use the function plot_model(), but i have this error.

> library(kerasR)
> plot_model(model)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.

Detailed traceback:
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 131, in plot_model
    dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 52, in model_to_dot
    _check_pydot()
  File "C:\Users\Idriss\ANACON~1\envs\R-TENS~1\lib\site-packages\keras\utils\vis_utils.py", line 27, in _check_pydot
    raise ImportError('Failed to import pydot. You must install pydot'

I'm use windows 10 64 bits, i use RStudio with Anaconda

In [4] pydot.Dot.create(pydot.Dot())

Out[4]: b"%!PS-Adobe-3.0\r\n%%Creator: graphviz version 2.38.0 (20140413.2041)\r\n%%Title: G\r\n%%Pages: (atend)\r\n%%BoundingBox: (atend)\r\n%%EndComments\r\nsave\r\n%%BeginProlog\r\n/DotDict 200 dict def\r\nDotDict begin\r\n\r\n/setupLatin1 {\r\nmark\r\n/EncodingVector 256 array def\r\n EncodingVector 0\r\n\r\nISOLatin1Encoding 0 255 getinterval putinterval\r\nEncodingVector 45 /hyphen put\r\n\r\n% Set up ISO Latin 1 character encoding\r\n/starnetISO {\r\n        dup dup findfont dup length dict begin\r\n        { 1 index /FID ne { def }{ pop pop } ifelse\r\n        } forall\r\n        /Encoding EncodingVector def\r\n        currentdict end definefont\r\n} def\r\n/Times-Roman starnetISO def\r\n/Times-Italic starnetISO def\r\n/Times-Bold starnetISO def\r\n/Times-BoldItalic starnetISO def\r\n/Helvetica starnetISO def\r\n/Helvetica-Oblique starnetISO def\r\n/Helvetica-Bold starnetISO def\r\n/Helvetica-BoldOblique starnetISO def\r\n/Courier starnetISO def\r\n/Courier-Oblique starnetISO def\r\n/Courier-Bold starnetISO def\r\n/Courier-BoldOblique starnetISO def\r\ncleartomark\r\n} bind def\r\n\r\n%%BeginResource: procset graphviz 0 0\r\n/coord-font-family /Times-Roman def\r\n/default-font-family /Times-Roman def\r\n/coordfont coord-font-family findfont 8 scalefont def\r\n\r\n/InvScaleFactor 1.0 def\r\n/set_scale {\r\n       dup 1 exch div /InvScaleFactor exch def\r\n       scale\r\n} bind def\r\n\r\n% styles\r\n/solid { [] 0 setdash } bind def\r\n/dashed { [9 InvScaleFactor mul dup ] 0 setdash } bind def\r\n/dotted { [1 InvScaleFactor mul 6 InvScaleFactor mul] 0 setdash } bind def\r\n/invis {/fill {newpath} def /stroke {newpath} def /show {pop newpath} def} bind def\r\n/bold { 2 setlinewidth } bind def\r\n/filled { } bind def\r\n/unfilled { } bind def\r\n/rounded { } bind def\r\n/diagonals { } bind def\r\n/tapered { } bind def\r\n\r\n% hooks for setting color \r\n/nodecolor { sethsbcolor } bind def\r\n/edgecolor { sethsbcolor } bind def\r\n/graphcolor { sethsbcolor } bind def\r\n/nopcolor {pop pop pop} bind def\r\n\r\n/beginpage {\t% i j npages\r\n\t/npages exch def\r\n\t/j exch def\r\n\t/i exch def\r\n\t/str 10 string def\r\n\tnpages 1 gt {\r\n\t\tgsave\r\n\t\t\tcoordfont setfont\r\n\t\t\t0 0 moveto\r\n\t\t\t(\\() show i str cvs show (,) show j str cvs show (\\)) show\r\n\t\tgrestore\r\n\t} if\r\n} bind def\r\n\r\n/set_font {\r\n\tfindfont exch\r\n\tscalefont setfont\r\n} def\r\n\r\n% draw text fitted to its expected width\r\n/alignedtext {\t\t\t% width text\r\n\t/text exch def\r\n\t/width exch def\r\n\tgsave\r\n\t\twidth 0 gt {\r\n\t\t\t[] 0 setdash\r\n\t\t\ttext stringwidth pop width exch sub text length div 0 text ashow\r\n\t\t} if\r\n\tgrestore\r\n} def\r\n\r\n/boxprim {\t\t\t\t% xcorner ycorner xsize ysize\r\n\t\t4 2 roll\r\n\t\tmoveto\r\n\t\t2 copy\r\n\t\texch 0 rlineto\r\n\t\t0 exch rlineto\r\n\t\tpop neg 0 rlineto\r\n\t\tclosepath\r\n} bind def\r\n\r\n/ellipse_path {\r\n\t/ry exch def\r\n\t/rx exch def\r\n\t/y exch def\r\n\t/x exch def\r\n\tmatrix currentmatrix\r\n\tnewpath\r\n\tx y translate\r\n\trx ry scale\r\n\t0 0 1 0 360 arc\r\n\tsetmatrix\r\n} bind def\r\n\r\n/endpage { showpage } bind def\r\n/showpage { } def\r\n\r\n/layercolorseq\r\n\t[\t% layer color sequence - darkest to lightest\r\n\t\t[0 0 0]\r\n\t\t[.2 .8 .8]\r\n\t\t[.4 .8 .8]\r\n\t\t[.6 .8 .8]\r\n\t\t[.8 .8 .8]\r\n\t]\r\ndef\r\n\r\n/layerlen layercolorseq length def\r\n\r\n/setlayer {/maxlayer exch def /curlayer exch def\r\n\tlayercolorseq curlayer 1 sub layerlen mod get\r\n\taload pop sethsbcolor\r\n\t/nodecolor {nopcolor} def\r\n\t/edgecolor {nopcolor} def\r\n\t/graphcolor {nopcolor} def\r\n} bind def\r\n\r\n/onlayer { curlayer ne {invis} if } def\r\n\r\n/onlayers {\r\n\t/myupper exch def\r\n\t/mylower exch def\r\n\tcurlayer mylower lt\r\n\tcurlayer myupper gt\r\n\tor\r\n\t{invis} if\r\n} def\r\n\r\n/curlayer 0 def\r\n\r\n%%EndResource\r\n%%EndProlog\r\n%%BeginSetup\r\n14 default-font-family set_font\r\n1 setmiterlimit\r\n% /arrowlength 10 def\r\n% /arrowwidth 5 def\r\n\r\n% make sure pdfmark is harmless for PS-interpreters other than Distiller\r\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse\r\n% make '<<' and '>>' safe on PS Level 1 devices\r\n/languagelevel where {pop languagelevel}{1} ifelse\r\n2 lt {\r\n    userdict (<<) cvn ([) cvn load put\r\n    userdict (>>) cvn ([) cvn load put\r\n} if\r\n\r\n%%EndSetup\r\nsetupLatin1\r\n%%Page: 1 1\r\n%%PageBoundingBox: 36 36 44 44\r\n%%PageOrientation: Portrait\r\n0 0 1 beginpage\r\ngsave\r\n36 36 8 8 boxprim clip newpath\r\n1 1 set_scale 0 rotate 40 40 translate\r\nendpage\r\nshowpage\r\ngrestore\r\n%%PageTrailer\r\n%%EndPage: 1\r\n%%Trailer\r\n%%Pages: 1\r\n%%BoundingBox: 36 36 44 44\r\nend\r\nrestore\r\n%%EOF\r\n"

Body:
You should install the Python libraries:

pip install pydot graphviz

And also you need to download the graphviz binaries, and these are not installed with Python.

On Ubuntu you can install them with apt:

apt-get install -y graphviz libgraphviz-dev

On osX with brew:

brew install graphviz

For Windows and other operating systems, the instructions can be found at http://www.graphviz.org/


问:
Fill-out HTML form and submit GET request Python 3
Hi Python enthusiasts,

I am struggling passing arguments using urllib.request in Python 3 to fill-out and submit a HTML form.

The critical part of the html code looks something like:

```<code><H1>Header</H1>
<form method="get" action="/bin/formula.php">
<ul>
 <li>Overview <A HREF="/kathegory.php">Kathegory</A>
 <li><A HREF="/bin/search.php">Search</A>
 <li><A HREF="/bin/formula.php">Formula</A>
<li>go to:
  <input type="text" name="id" size=10 maxlength=10>
  <input type="submit" value="go">**
</ul>
</form>
<ul>
 <li><A HREF="history.php">History</A>
</ul>
<P>
<HR>
</code>```

When filling-out the form manually on the website (e.g. 1) http://example.com, the resulting page would be called http://example.com/bin/formula.php?id=1

My approach in Python so far was:

```<code>from bs4 import BeautifulSoup
import urllib.request
import urllib.parse

h = {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
payload = {'id': '1'}
url = 'http://example.com'

data = urllib.parse.urlencode(payload)
#data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data, h)
print(req.__dict__)

with urllib.request.urlopen(req) as response:
the_page = response.read()

print(the_page)
</code>```

without success.

Any advice from more experienced users is very much appreciated!

Cheers

答: Use the very popular Requests ("HTTP for Humans") package instead: http://docs.python-requests.org</p>

Body:
Hi Python enthusiasts,

I am struggling passing arguments using urllib.request in Python 3 to fill-out and submit a HTML form.

The critical part of the html code looks something like:

Header

<form method="get" action="/bin/formula.php">

Overview Kathegory

Search

Formula

go to:
  <input type="text" name="id" size=10 maxlength=10>
  <input type="submit" value="go">**

</form>

History

When filling-out the form manually on the website (e.g. 1) http://example.com, the resulting page would be called http://example.com/bin/formula.php?id=1

My approach in Python so far was:

from bs4 import BeautifulSoup
import urllib.request
import urllib.parse

h = {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
payload = {'id': '1'}
url = 'http://example.com'

data = urllib.parse.urlencode(payload)
#data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data, h)
print(req.__dict__)

with urllib.request.urlopen(req) as response:
the_page = response.read()

print(the_page)

without success.

Any advice from more experienced users is very much appreciated!

Cheers


答:
Use a timeout on each keyup. If there's already a timeout running, clear it and set another.

let timeout = null;
$(window).on('keydown',(e => {
  if (e.keyCode == 39 || e.keyCode == 32) {
    $('body').css('background', '#26A65B');
    $('#word').css('color', '#415A77');
  }
  if (e.keyCode == 37) {
    $('body').css('background', '#D64541');
    $('#word').css('color', '#415A77');
  }
}));
$(window).on('keyup',(e => {
  if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
    if (timeout !== null) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      $('body').css('background', '#415A77');
      $('#word').css('color', '#ed7d3a');
    }, 2000);
  }
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="word">Hello</div></code>```

Title: on keydown execute function and and pause the execution of the next function JS

Body:
For now I have that when key is down it changes colours, and as soon as it is up it changes back. But this is really quick and kinda causes migraine effect.

I want to do so when the key is pressed it would keep the changes for a second or two and then changes back to original colours without pausing any other function that is not inside these ones.

$(window).on('keydown', function (e) {
    if (e.keyCode == 39 || e.keyCode == 32) {
      $('body').css('background', '#26A65B');
      $('#word').css('color', '#415A77');
    }
    if(e.keyCode == 37) {
      $('body').css('background', '#D64541');
      $('#word').css('color', '#415A77');
    }
  });
$(window).on ('keyup', function (e) {
    if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
      $('body').css('background', '#415A77');
      $('#word').css('color', '#ed7d3a');
    }
});

Body:
Use a timeout on each keyup. If there's already a timeout running, clear it and set another.

let timeout = null;
$(window).on('keydown',(e => {
  if (e.keyCode == 39 || e.keyCode == 32) {
    $('body').css('background', '#26A65B');
    $('#word').css('color', '#415A77');
  }
  if (e.keyCode == 37) {
    $('body').css('background', '#D64541');
    $('#word').css('color', '#415A77');
  }
}));
$(window).on('keyup',(e => {
  if (e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 37) {
    if (timeout !== null) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      $('body').css('background', '#415A77');
      $('#word').css('color', '#ed7d3a');
    }, 2000);
  }
}));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="word">Hello</div>


问:
Is there ever a reason to use asm volatile for PTX with no side-effects?
The CUDA documentation on inline PTX, section 1.2.3 Incorrect optimization, says:

The compiler assumes that an asm() statement has no side effects except to change the output operands. To ensure that the asm is not deleted or moved during generation of PTX, you should use the volatile keyword, e.g.:

```<code>asm volatile ("mov.u32 %0, %%clock;" : "=r"(x));
</code>```

If my inline PTX does indeed have no side-effects outside of registers, should I just never use volatile or are there cases in which I might still want to have it?

答:
Assuming the rules are the same as "regular" (non-CUDA) GNU C inline assembly which uses the same constraint syntax:

If you want it to re-run the instruction(s) every time the source executes the statement, use volatile.  (This is probably what you want to re-read the %clock every time).

If you want to let the compiler hoist it out of a loop, or just CSE between two results of this statement before and after a block, then don't use volatile.

GNU C non-volatile extended-asm statements are treated as pure functions of their inputs.  (Having no outputs implicitly makes a statement volatile.)  This includes the case of a pure function with no inputs: by omitting volatile you're telling the compiler it produces the same output every time.

This could be appropriate for reading a CPU control register that you aren't planning to modify, or for loading a value from a memory location you haven't told the compiler about.  It's definitely not what you want for reading a clock.

I.e. reading something that isn't the same every time counts as a side-effect.

Body:
The CUDA documentation on inline PTX, section 1.2.3 Incorrect optimization, says:

The compiler assumes that an asm() statement has no side effects except to change the output operands. To ensure that the asm is not deleted or moved during generation of PTX, you should use the volatile keyword, e.g.:

asm volatile ("mov.u32 %0, %%clock;" : "=r"(x));

If my inline PTX does indeed have no side-effects outside of registers, should I just never use volatile or are there cases in which I might still want to have it?


问:
Accessing a folder from ClassLoader
I have a JAVA EE app. with this structure:

```<code>/iberiaApp
/iberiaApp/configFiles/hotel
/iberiaApp/config.jsp
/iberiaApp/WEB-INF/classes
</code>```

inside config.jsp I have this piece of code:

```<code> <%=FileReader.readFiles("configFiles/hotel")%>;
</code>```

and

```<code>public static List<String> readFiles (String folder) throws URISyntaxException {

    ClassLoader classLoader = FileReader.class.getClassLoader();

    URI uri = classLoader.getResource(folder).toURI();
</code>```

But I got a nullpointer getting the URI (classLoader.getResource(folder) is returning null)

答:
Look a these notes from: https://stackoverflow.com/a/3160706/1715121

Several notes:

You should prefer the ClassLoader as returned by [Thread#getContextClassLoader()][1].

```<code>ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
</code>```

This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

```<code>classLoader.getResource("/configFiles/hotel");
</code>```

Title: Accessing a folder from ClassLoader

Body:
I have a JAVA EE app. with this structure:

/iberiaApp
/iberiaApp/configFiles/hotel
/iberiaApp/config.jsp
/iberiaApp/WEB-INF/classes

inside config.jsp I have this piece of code:

 <%=FileReader.readFiles("configFiles/hotel")%>;

and

public static List<String> readFiles (String folder) throws URISyntaxException {

    ClassLoader classLoader = FileReader.class.getClassLoader();

    URI uri = classLoader.getResource(folder).toURI();

But I got a nullpointer getting the URI (classLoader.getResource(folder) is returning null)

Body:
Look a these notes from: https://stackoverflow.com/a/3160706/1715121

Several notes:

You should prefer the ClassLoader as returned by [Thread#getContextClassLoader()][1].

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

classLoader.getResource("/configFiles/hotel");


问:
struts 2 tiles NoSuchDefinitionException
I am getting this exception when using struts 2 with tiles

org.apache.tiles.definition.NoSuchDefinitionException: /index.jsp

//tiles.xml

```<code><tiles-definitions>
<definition name="baseLayout" template="/index.jsp">
    <put-attribute name="title" value="/Template" />
    <put-attribute name="header" value="/Header.jsp" />
    <put-attribute name="menu" value="/Menu.jsp" />
    <put-attribute name="body" value="/body.jsp" />
    <put-attribute name="footer" value="/Footer.jsp" />
</definition>
<tiles-definitions>
</code>```

//index.jsp

```<code><%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<tiles:insertAttribute name="header"/>
<tiles:insertAttribute name="footer"/>
</body>
</html>
</code>```

//web.xml

```<code><listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.
DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
</code>```

//struts.xml

```<code>    <package name="default" namespace="/test" extends="struts-default">
    <result-types>
    <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>

    <action name="login" class="com.medics.action.LoginAction">
        <result name="SUCCESS" type="tiles">/index.jsp</result>
    </action>
    </package>
</code>```

I have searched a lot but found nothing

答:
```<code>org.apache.tiles.definition.NoSuchDefinitionException: /index.jsp
</code>```

Means that there is no tiles definition, that is no definition of the name "/index.jsp"

When using struts and tiles... Your request comes into struts then out to tiles where tiles composes the view so you shouldn't have any tiles definitions called "anything.jsp".

So just replace

```<code><result name="SUCCESS" type="tiles">/index.jsp</result>
</code>```

with

```<code><result name="SUCCESS" type="tiles">baseLayout/result>
</code>```

Now that is resolved... I would rename index.jsp, template.jsp (I think it's less confusing), why do you have a put-attribute called "/Template" ?

Now to fix the issue I recommended that you change the struts2 result target to "baseLayout" but this is probably not what you mean, so you probably want to use your baseLayout definition for new pages so add a new definition:

```<code><definition name="index" extends="baseLayout">
  <put-attribute name="title" value="My Title for Index" />
  <put-attribute name="body" value="/index.jsp" />
</definition>
</code>```

Now the above will take that value in defaultTemplate and add (or if the name is the same, override) what was in the base template creating a page for index.jsp, and now your struts.xml should have

```<code> <result name="SUCCESS" type="tiles">index</result>
</code>```

Body:
I am getting this exception when using struts 2 with tiles

org.apache.tiles.definition.NoSuchDefinitionException: /index.jsp

//tiles.xml

<tiles-definitions>
<definition name="baseLayout" template="/index.jsp">
    <put-attribute name="title" value="/Template" />
    <put-attribute name="header" value="/Header.jsp" />
    <put-attribute name="menu" value="/Menu.jsp" />
    <put-attribute name="body" value="/body.jsp" />
    <put-attribute name="footer" value="/Footer.jsp" />
</definition>
<tiles-definitions>

//index.jsp

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title></title>

<tiles:insertAttribute name="header"/>
<tiles:insertAttribute name="footer"/>

//web.xml

<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.
DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

//struts.xml

    <package name="default" namespace="/test" extends="struts-default">
    <result-types>
    <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>

    <action name="login" class="com.medics.action.LoginAction">
        <result name="SUCCESS" type="tiles">/index.jsp</result>
    </action>
    </package>

I have searched a lot but found nothing

Body:
org.apache.tiles.definition.NoSuchDefinitionException: /index.jsp

Means that there is no tiles definition, that is no definition of the name "/index.jsp"

When using struts and tiles... Your request comes into struts then out to tiles where tiles composes the view so you shouldn't have any tiles definitions called "anything.jsp".

So just replace

<result name="SUCCESS" type="tiles">/index.jsp</result>

with

<result name="SUCCESS" type="tiles">baseLayout/result>

Now that is resolved... I would rename index.jsp, template.jsp (I think it's less confusing), why do you have a put-attribute called "/Template" ?

Now to fix the issue I recommended that you change the struts2 result target to "baseLayout" but this is probably not what you mean, so you probably want to use your baseLayout definition for new pages so add a new definition:

<definition name="index" extends="baseLayout">
  <put-attribute name="title" value="My Title for Index" />
  <put-attribute name="body" value="/index.jsp" />
</definition>

Now the above will take that value in defaultTemplate and add (or if the name is the same, override) what was in the base template creating a page for index.jsp, and now your struts.xml should have

 <result name="SUCCESS" type="tiles">index</result>


问:
My Python function isn't working as wanted
I am making a function that takes a string and replace "put" and "get" with "xput()" and "xget()". I know it isn't the most efficient, but I want to start with making it work. It currently replace the words ad puts the brackets, but it puts brackets on every newline and I don't see why. Can someone help me?

Code:

```<code>import re

def replaceFunctions(string):
    split=re.split('(\n)', string)
    for i in range (0,len(split)):
        split[i] = re.split('(")',split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('( )', split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('(\t)', split[i])

    split = [item for sublist in split for item in sublist]
    split.append("\n")

    for i in range (0,len(split)):
        if split[i] == "put":
            split[i] = "xput ("
            for o in range (i,len(split)):
                if split[o] == "\n":
                    split[o] = ")\n"
                    break

        else:
            if split[i] == "get":
                split[i] = "xget ("
                for o in range (i,len(split)):
                    if split[o] == "\n":
                        split[o] = ")\n"
                        break

    string = ""

    for i in range (0,len(split)):
        string += split[i]

    return string

print "get (put)"
print replaceFunctions("get (put)")

print "put \"put this\"\nput put (get)\n\n\nput\n"
print replaceFunctions("put \"put this\"\nput put (get)\n\n\nput")
</code>```

Output:

```<code>get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))
)
)
xput ()
</code>```

Desired Output:

```<code>get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))

xput ()
</code>```

Thanks in advance!

答:
would this work?</p>

```<code>>>> txt = 'this is a text with get, some more get and even a put or two put'
>>> txt.replace('get', 'xget()').replace('put', 'xput()')
'this is a text with xget(), some more xget() and even a xput() or two xput()'
</code>```

Body:
I am making a function that takes a string and replace "put" and "get" with "xput()" and "xget()". I know it isn't the most efficient, but I want to start with making it work. It currently replace the words ad puts the brackets, but it puts brackets on every newline and I don't see why. Can someone help me?

Code:

import re

def replaceFunctions(string):
    split=re.split('(\n)', string)
    for i in range (0,len(split)):
        split[i] = re.split('(")',split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('( )', split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('(\t)', split[i])

    split = [item for sublist in split for item in sublist]
    split.append("\n")

    for i in range (0,len(split)):
        if split[i] == "put":
            split[i] = "xput ("
            for o in range (i,len(split)):
                if split[o] == "\n":
                    split[o] = ")\n"
                    break

        else:
            if split[i] == "get":
                split[i] = "xget ("
                for o in range (i,len(split)):
                    if split[o] == "\n":
                        split[o] = ")\n"
                        break

    string = ""

    for i in range (0,len(split)):
        string += split[i]

    return string

print "get (put)"
print replaceFunctions("get (put)")

print "put \"put this\"\nput put (get)\n\n\nput\n"
print replaceFunctions("put \"put this\"\nput put (get)\n\n\nput")

Output:

get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))
)
)
xput ()

Desired Output:

get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))

xput ()

Thanks in advance!

Body:
would this work?

>>> txt = 'this is a text with get, some more get and even a put or two put'
>>> txt.replace('get', 'xget()').replace('put', 'xput()')
'this is a text with xget(), some more xget() and even a xput() or two xput()'


问:
Hadoop Mapreduce, How do I rewrite a txt file inputted in the mapper with map reduce output?
I am trying to create a map reduce program to perform the k-means algorithm. I know using map reduce isn't the best way to do iterative algorithms.
I have created the mapper and reducer classes.
In the mapper code I read an input file. When a map reduce has completed I want the results to be stored in the same input file. How do i make the output file overwrite the inputted file from the mapper?
Also so I make the map reduce iterate until the values from the old input file and new input file converge i.e. the difference between the values is less than 0.1

My code is:

```<code> import java.io.IOException;
 import java.util.StringTokenizer;
 import java.util.*;
 import org.apache.hadoop.io.*;
 import org.apache.hadoop.mapreduce.Mapper;
 import java.io.FileReader;
 import java.io.BufferedReader;
 import java.util.ArrayList;

public class kmeansMapper extends Mapper<Object, Text, DoubleWritable,
DoubleWritable> {
private final static String centroidFile = "centroid.txt";
private List<Double> centers = new ArrayList<Double>();

public void setup(Context context) throws IOException{
        BufferedReader br = new BufferedReader(new
        FileReader(centroidFile));
        String contentLine;
        while((contentLine = br.readLine())!=null){
            centers.add(Double.parseDouble(contentLine));
        }
}

public void map(Object key, Text input, Context context) throws IOException,
InterruptedException {

        String[] fields = input.toString().split("  ");
        Double rating = Double.parseDouble(fields[2]);
        Double distance = centers.get(0) - rating;
        int position = 0;
        for(int i=1; i<centers.size(); i++){
            Double cDistance = Math.abs(centers.get(i) - rating);
            if(cDistance< distance){
                position = i;
                distance = cDistance;
            }
        }
        Double closestCenter = centers.get(position);
        context.write(new DoubleWritable(closestCenter),new
DoubleWritable(rating)); //outputs closestcenter and rating value

        }
}
import java.io.IOException;
import java.lang.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Reducer;
import java.util.*;

public class kmeansReducer extends Reducer<DoubleWritable, DoubleWritable,
DoubleWritable, Text> {

public void reduce(DoubleWritable key, Iterable<DoubleWritable> values,
Context context)// get count // get total //get values in a string
          throws IOException, InterruptedException {
            Iterator<DoubleWritable> v = values.iterator();
            double total = 0;
            double count = 0;
            String value = ""; //value is the rating
            while (v.hasNext()){
              double i = v.next().get();
              value = value + " " + Double.toString(i);
              total = total + i;
              ++count;
            }
            double nCenter = total/count;
  context.write(new DoubleWritable(nCenter), new Text(value));
}
}
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class run
{

 public static void runJob(String[] input, String output) throws Exception {

    Configuration conf = new Configuration();

  Job job = new Job(conf);
  Path toCache = new Path("input/centroid.txt");
  job.addCacheFile(toCache.toUri());
  job.setJarByClass(run.class);
  job.setMapperClass(kmeansMapper.class);
  job.setReducerClass(kmeansReducer.class);
  job.setMapOutputKeyClass(DoubleWritable.class);
  job.setMapOutputValueClass(DoubleWritable.class);

  job.setNumReduceTasks(1);
  Path outputPath = new Path(output);
  FileInputFormat.setInputPaths(job, StringUtils.join(input, ","));
  FileOutputFormat.setOutputPath(job, outputPath);
  outputPath.getFileSystem(conf).delete(outputPath,true);
  job.waitForCompletion(true);

}

public static void main(String[] args) throws Exception {
   runJob(Arrays.copyOfRange(args, 0, args.length-1), args[args.length-1]);

}

}
</code>```

Thanks

答:
I know you put the disclaimer.. but please switch to Spark or some other framework that can solve problems in-memory. Your life will be so much better.

If you really want to do this, just iteratively run the code in runJob and use a temporary file name for input. You can see this question on moving files in hadoop to achieve this. You'll need a FileSystem instance and a temp file for input:

```<code>FileSystem fs = FileSystem.get(new Configuration());
Path tempInputPath = Paths.get('/user/th/kmeans/tmp_input';
</code>```

Broadly speaking, after each iteration is finished, do

```<code>fs.delete(tempInputPath)
fs.rename(outputPath, tempInputPath)
</code>```

Of course for the very first iteration you must set the input path to be the input paths provided when running the job. Subsequent iterations can use the tempInputPath, which will be the output of the previous iteration.

Body:
I am trying to create a map reduce program to perform the k-means algorithm. I know using map reduce isn't the best way to do iterative algorithms.
I have created the mapper and reducer classes.
In the mapper code I read an input file. When a map reduce has completed I want the results to be stored in the same input file. How do i make the output file overwrite the inputted file from the mapper?
Also so I make the map reduce iterate until the values from the old input file and new input file converge i.e. the difference between the values is less than 0.1

My code is:

 import java.io.IOException;
 import java.util.StringTokenizer;
 import java.util.*;
 import org.apache.hadoop.io.*;
 import org.apache.hadoop.mapreduce.Mapper;
 import java.io.FileReader;
 import java.io.BufferedReader;
 import java.util.ArrayList;

public class kmeansMapper extends Mapper<Object, Text, DoubleWritable,
DoubleWritable> {
private final static String centroidFile = "centroid.txt";
private List<Double> centers = new ArrayList<Double>();

public void setup(Context context) throws IOException{
        BufferedReader br = new BufferedReader(new
        FileReader(centroidFile));
        String contentLine;
        while((contentLine = br.readLine())!=null){
            centers.add(Double.parseDouble(contentLine));
        }
}

public void map(Object key, Text input, Context context) throws IOException,
InterruptedException {

        String[] fields = input.toString().split("  ");
        Double rating = Double.parseDouble(fields[2]);
        Double distance = centers.get(0) - rating;
        int position = 0;
        for(int i=1; i<centers.size(); i++){
            Double cDistance = Math.abs(centers.get(i) - rating);
            if(cDistance< distance){
                position = i;
                distance = cDistance;
            }
        }
        Double closestCenter = centers.get(position);
        context.write(new DoubleWritable(closestCenter),new
DoubleWritable(rating)); //outputs closestcenter and rating value

        }
}
import java.io.IOException;
import java.lang.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Reducer;
import java.util.*;

public class kmeansReducer extends Reducer<DoubleWritable, DoubleWritable,
DoubleWritable, Text> {

public void reduce(DoubleWritable key, Iterable<DoubleWritable> values,
Context context)// get count // get total //get values in a string
          throws IOException, InterruptedException {
            Iterator<DoubleWritable> v = values.iterator();
            double total = 0;
            double count = 0;
            String value = ""; //value is the rating
            while (v.hasNext()){
              double i = v.next().get();
              value = value + " " + Double.toString(i);
              total = total + i;
              ++count;
            }
            double nCenter = total/count;
  context.write(new DoubleWritable(nCenter), new Text(value));
}
}
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class run
{

 public static void runJob(String[] input, String output) throws Exception {

    Configuration conf = new Configuration();

  Job job = new Job(conf);
  Path toCache = new Path("input/centroid.txt");
  job.addCacheFile(toCache.toUri());
  job.setJarByClass(run.class);
  job.setMapperClass(kmeansMapper.class);
  job.setReducerClass(kmeansReducer.class);
  job.setMapOutputKeyClass(DoubleWritable.class);
  job.setMapOutputValueClass(DoubleWritable.class);

  job.setNumReduceTasks(1);
  Path outputPath = new Path(output);
  FileInputFormat.setInputPaths(job, StringUtils.join(input, ","));
  FileOutputFormat.setOutputPath(job, outputPath);
  outputPath.getFileSystem(conf).delete(outputPath,true);
  job.waitForCompletion(true);

}

public static void main(String[] args) throws Exception {
   runJob(Arrays.copyOfRange(args, 0, args.length-1), args[args.length-1]);

}

}

Thanks

Body:
I know you put the disclaimer.. but please switch to Spark or some other framework that can solve problems in-memory. Your life will be so much better.

If you really want to do this, just iteratively run the code in runJob and use a temporary file name for input. You can see this question on moving files in hadoop to achieve this. You'll need a FileSystem instance and a temp file for input:

FileSystem fs = FileSystem.get(new Configuration());
Path tempInputPath = Paths.get('/user/th/kmeans/tmp_input';

Broadly speaking, after each iteration is finished, do

fs.delete(tempInputPath)
fs.rename(outputPath, tempInputPath)

Of course for the very first iteration you must set the input path to be the input paths provided when running the job. Subsequent iterations can use the tempInputPath, which will be the output of the previous iteration.


问:
Get void output to variable
I have 2 .java files in my project and i want in one of them to show (in a textarea for example) the value of an Enumeration located in the other .java file.

This is the code of the first (or main) .java file - frm1.java:
(Just showing what i consider the most relevant part of the code, but if necessary, I can put it completely)

```<code>// Things HERE
    ListNets interfaceLoader = new ListNets();
    txtrBlabla.setText(names);
</code>```

Where the txtrBlabla is the name given for the JTextArea and ListNets the name for the second .java file.

And here the second .java file's content - ListNets.java:

```<code>public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    public static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString(); //<-- This line is the only thing not "copy-pasted"
     }
}
</code>```

As you can see, the second code is just a copy&paste.
I've tried loads of ways to get the enumeration's result into a variable and then trying to set it into the textarea using the txtrBlabla.setText(names); line, but always get the error message:

names cannot be resolved into a variable

In the main java file.
I had also seen that's something related to "voids" but no results trying it.
I've also tried changing the variable but neither i get it working.

Note:
I'm an starter in JAVA but i really want to understand why this doesn't work.
Sorry for the spelling and thanks in advance.

EDIT:
Also tried putting everything in the same .java file as follows:

```<code>public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString();
     }

        txtrBlabla.setText(displayInterfaceInformation.names);
</code>```

答:
Actually this line is not needed:

```<code>String names = inetAddresses.toString();
</code>```

Rather I would convert the enumeration of InetAddress objects to a string and then return it for later usage. Something along the lines:

```<code>public static String getNetworkInformation(NetworkInterface netint) throws SocketException {
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    StringJoiner joiner = new StringJoiner(",");
    while(inetAddresses.hasMoreElements()) {
        InetAddress inetAddress = inetAddresses.nextElement();
        joiner.add(inetAddress.toString());
    }
    return joiner.toString();
}
</code>```

By the way: trying to convert a java.util.Enumeration to string by calling toString() does not produce any meaningful string in Java.

You could try out this code here in JDoodle. This source code in this Doodle prints out the output to the console, but in your case you just need to output it to the UI.

Title: Get void output to variable

Body:
I have 2 .java files in my project and i want in one of them to show (in a textarea for example) the value of an Enumeration located in the other .java file.

This is the code of the first (or main) .java file - frm1.java:
(Just showing what i consider the most relevant part of the code, but if necessary, I can put it completely)

// Things HERE
    ListNets interfaceLoader = new ListNets();
    txtrBlabla.setText(names);

Where the txtrBlabla is the name given for the JTextArea and ListNets the name for the second .java file.

And here the second .java file's content - ListNets.java:

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    public static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString(); //<-- This line is the only thing not "copy-pasted"
     }
}

As you can see, the second code is just a copy&paste.
I've tried loads of ways to get the enumeration's result into a variable and then trying to set it into the textarea using the txtrBlabla.setText(names); line, but always get the error message:

names cannot be resolved into a variable

In the main java file.
I had also seen that's something related to "voids" but no results trying it.
I've also tried changing the variable but neither i get it working.

Note:
I'm an starter in JAVA but i really want to understand why this doesn't work.
Sorry for the spelling and thanks in advance.

EDIT:
Also tried putting everything in the same .java file as follows:

public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString();
     }

        txtrBlabla.setText(displayInterfaceInformation.names);

Body:
Actually this line is not needed:

String names = inetAddresses.toString();

Rather I would convert the enumeration of InetAddress objects to a string and then return it for later usage. Something along the lines:

public static String getNetworkInformation(NetworkInterface netint) throws SocketException {
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    StringJoiner joiner = new StringJoiner(",");
    while(inetAddresses.hasMoreElements()) {
        InetAddress inetAddress = inetAddresses.nextElement();
        joiner.add(inetAddress.toString());
    }
    return joiner.toString();
}

By the way: trying to convert a java.util.Enumeration to string by calling toString() does not produce any meaningful string in Java.

You could try out this code here in JDoodle. This source code in this Doodle prints out the output to the console, but in your case you just need to output it to the UI.


问:
Configure ASP.NET Session State at runtime
We have an ASP.NET web site that uses SQL Server session state.  The state is configured in Web.config like:

```<code><sessionState mode="SQLServer" sqlConnectionString="data source=TheServer;
    User ID=TheUser;password=ThePassword;" cookieless="false" timeout="480"/>
</code>```

But there are three environments (development / staging / production).  All the other connection strings are configured like:

```<code><configuration>
    <connectionStrings>
        <add name="Development_Db1" connectionString="..."/>
        <add name="Production_Db1" connectionString="..."/>
    </connectionStrings>
</configuration>
</code>```

At runtime, we pick one to connect to the database based on hostname.  Unfortunately, the Session State connection string appears to be hard coded in web.config.

Is there a way to configure SQL Server session state at runtime, or make it refer to a connection string from the connectionStrings section?

答:
As it turned out, there was a fairly easy way of doing this.  Session State provides a feature called Partitioning, where you can spread your state over multiple SQL Servers.  You can provide a function to select the SQL Server based on the session id (SID).  The trick is that you can use this feature with ONE server, just to choose the server dynamically.

The web.config configuration looks like:

```<code><sessionState mode="SQLServer"
              partitionResolverType="YourNamespace.PartitionResolver"
              cookieless="false"
              timeout="60" />
</code>```

The function that chooses the SQL Server looks like:

```<code>public class PartitionResolver : IPartitionResolver
{
    public void Initialize() {}

    // The key is a SID (session identifier)
    public String ResolvePartition(Object key)
    {
        return <grab your config here>;
    }
}
</code>```

This approach allowed us to continue using one web.config for both production and development.

Body:
We have an ASP.NET web site that uses SQL Server session state.  The state is configured in Web.config like:

<sessionState mode="SQLServer" sqlConnectionString="data source=TheServer;
    User ID=TheUser;password=ThePassword;" cookieless="false" timeout="480"/>

But there are three environments (development / staging / production).  All the other connection strings are configured like:

<configuration>
    <connectionStrings>
        <add name="Development_Db1" connectionString="..."/>
        <add name="Production_Db1" connectionString="..."/>
    </connectionStrings>
</configuration>

At runtime, we pick one to connect to the database based on hostname.  Unfortunately, the Session State connection string appears to be hard coded in web.config.

Is there a way to configure SQL Server session state at runtime, or make it refer to a connection string from the connectionStrings section?

Body:
As it turned out, there was a fairly easy way of doing this.  Session State provides a feature called Partitioning, where you can spread your state over multiple SQL Servers.  You can provide a function to select the SQL Server based on the session id (SID).  The trick is that you can use this feature with ONE server, just to choose the server dynamically.

The web.config configuration looks like:

<sessionState mode="SQLServer"
              partitionResolverType="YourNamespace.PartitionResolver"
              cookieless="false"
              timeout="60" />

The function that chooses the SQL Server looks like:

public class PartitionResolver : IPartitionResolver
{
    public void Initialize() {}

    // The key is a SID (session identifier)
    public String ResolvePartition(Object key)
    {
        return <grab your config here>;
    }
}

This approach allowed us to continue using one web.config for both production and development.

ContentLicense: CC BY-SA 4.0


问:
Sending device to device push notifications over server with nodejs
I want to build a server using nodejs:

to send push notifications between groups of devices

Messages of a group should not reach devices of the other groups

An admin (eg. in an institute) should be able to create a group

I already created a solution using onesignal where one device sends a message to onesignal which then transfers it to all selected devices.
There all we had to do was sending a request:

```<code>server.post('/', function (req, res) {
myClient.sendNotification(firstNotification, function (err, httpResponse, data) {
    if (err) {
        console.log('Something went wrong...');
    } else {
        console.log(data, httpResponse.statusCode);
    }
});
</code>```

});

But I don't want to be dependent on third party software. This functionality should now run over my local server.

Can you give me some tips and ideas how to go about that? (architecture, data management)?

Best Regards

ZAtrue

答:
You really should look into Socket.io.

On your client side you can listen for broadcasts a socket sends and react to it by (for example) firing a push notification on your device.

I would recommend to look at the socket.io documentation and the provided examples.

Regarding your groups, you could look into socket.io's namespace and rooms.

Body:
I want to build a server using nodejs:

to send push notifications between groups of devices

Messages of a group should not reach devices of the other groups

An admin (eg. in an institute) should be able to create a group

I already created a solution using onesignal where one device sends a message to onesignal which then transfers it to all selected devices.
There all we had to do was sending a request:

server.post('/', function (req, res) {
myClient.sendNotification(firstNotification, function (err, httpResponse, data) {
    if (err) {
        console.log('Something went wrong...');
    } else {
        console.log(data, httpResponse.statusCode);
    }
});

});

But I don't want to be dependent on third party software. This functionality should now run over my local server.

Can you give me some tips and ideas how to go about that? (architecture, data management)?

Best Regards

ZAtrue


问:
Converting emojis to Unicode and vice versa in python 3
I am trying to convert an emoji into its Unicode in python 3. For example I would have the emoji  and from this would like to get the corresponding unicode 'U+1F600'. Similarly I would like to convert the 'U+1F600' back to . Now I have read the documentation and tried several options but pythons behaviour confuses me here.

```<code>>>> x = ''
>>> y = x.encode('utf-8')
>>> y
b'\xf0\x9f\x98\x80'
</code>```

The emoji is converted to a byte object.

```<code>>>> z = y.decode('utf-8')
>>> z
''
</code>```

Converted the byte object back to the emoji, so far so good.

Now, taking the unicode for the emoji:

```<code>>>> c = '\U0001F600'
>>> d = c.encode('utf-8')
>>> d
>>> b'\xf0\x9f\x98\x80'
</code>```

This prints out the byte encoding again.

```<code>>>> d.decode('utf-8')
>>> ''
</code>```

This prints the emoji out again. I really can't figure out how to convert solely between the Unicode and the emoji.

答:
'' is already a Unicode object. UTF-8 is not Unicode, it's a byte encoding for Unicode. To get the codepoint number of a Unicode character, you can use the ord function. And to print it in the form you want you can format it as hex. Like this:

```<code>s = ''
print('U+{:X}'.format(ord(s)))
</code>```

output

```<code>U+1F600
</code>```

If you have Python 3.6+, you can make it even shorter (and more efficient) by using an f-string:

```<code>s = ''
print(f'U+{ord(s):X}')
</code>```

BTW, if you want to create a Unicode escape sequence like '\U0001F600' there's the 'unicode-escape' codec. However, it returns a bytes string, and you may wish to convert that back to text. You could use the 'UTF-8' codec for that, but you might as well just use the 'ASCII' codec, since it's guaranteed to only contain valid ASCII.

```<code>s = ''
print(s.encode('unicode-escape'))
print(s.encode('unicode-escape').decode('ASCII'))
</code>```

output

```<code>b'\\U0001f600'
\U0001f600
</code>```

I suggest you take a look at this short article by Stack Overflow co-founder Joel Spolsky The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

Body:
I am trying to convert an emoji into its Unicode in python 3. For example I would have the emoji  and from this would like to get the corresponding unicode 'U+1F600'. Similarly I would like to convert the 'U+1F600' back to . Now I have read the documentation and tried several options but pythons behaviour confuses me here.

>>> x = ''
>>> y = x.encode('utf-8')
>>> y
b'\xf0\x9f\x98\x80'

The emoji is converted to a byte object.

>>> z = y.decode('utf-8')
>>> z
''

Converted the byte object back to the emoji, so far so good.

Now, taking the unicode for the emoji:

>>> c = '\U0001F600'
>>> d = c.encode('utf-8')
>>> d
>>> b'\xf0\x9f\x98\x80'

This prints out the byte encoding again.

>>> d.decode('utf-8')
>>> ''

This prints the emoji out again. I really can't figure out how to convert solely between the Unicode and the emoji.

Body:
'' is already a Unicode object. UTF-8 is not Unicode, it's a byte encoding for Unicode. To get the codepoint number of a Unicode character, you can use the ord function. And to print it in the form you want you can format it as hex. Like this:

s = ''
print('U+{:X}'.format(ord(s)))

output

U+1F600

If you have Python 3.6+, you can make it even shorter (and more efficient) by using an f-string:

s = ''
print(f'U+{ord(s):X}')

BTW, if you want to create a Unicode escape sequence like '\U0001F600' there's the 'unicode-escape' codec. However, it returns a bytes string, and you may wish to convert that back to text. You could use the 'UTF-8' codec for that, but you might as well just use the 'ASCII' codec, since it's guaranteed to only contain valid ASCII.

s = ''
print(s.encode('unicode-escape'))
print(s.encode('unicode-escape').decode('ASCII'))

output

b'\\U0001f600'
\U0001f600

I suggest you take a look at this short article by Stack Overflow co-founder Joel Spolsky The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).


问:
Using javascript within HTML and only internal CSS
I'm working on a page to put on my firewall that displays various output depending on category I'm blocking.

I've spent about the last day trying to understand why the simple javascript I'm attempting to use is not resulting in my case statements properly rendering the results I want to see.

I can't use any external CSS in this case, and forgive the crazy colors. I like to use them to tell where all my
s are positioned while hacking together things like this.

Is the issue that my

答:
Is this what you're attempting to do? The changes:

You have various syntax errors in the javascript i.e opening and closing braces, semicolons not used for terminating expressions, etc.

For setting the second innerHTML, more like appending to the previous reason you need to use "+=" instead of "=". Hope, it helps.

var cat = "Adult";
switch (cat) {
  case "Adult":
    var blockReason = "Inappropriate adult content detected";
    break;
  case "Web-based Email":
    var blockReason = "Due to regulatory reasons we are unable to allow access to unaudited communication channels over web";
    break;
  case "Online Storage and Backup":
    var blockReason = "Websites providing online storage of files for free and as a service not permitted";
    break;
  case "Manually Blocked URLs":
  var blockReason = "URL has been manually blocked outside of predefined categories";
}

document.getElementById("blockReason").innerHTML = "Block Reason: "+blockReason;

var cat = 'Category1';
switch (cat) {
  case 'Category1':
    var blockRs = "Reason1";
    break;

  case 'Category2':
    var blockRs = "Reason2";
    break;

  case 'Category3':
    var blockRs = "Reason3";
    break;

  case 'Category4':
  var blockRs = "Reason4";
  break;
}

document.getElementById('blockReason').innerHTML += "Block Reason: " + blockRs;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  padding: 0;
}

body {
  border: 0;
}

.nav {
  width: 100%;
  background-color: #002856;
  color: white;
}

.nav h1 {
  text-align: center;
  margin-top: -.04em;
  font-family: Helvetica, Arial, sans-serif;
}

.content-wrapper {
  background-color: blue;
  height: 40em;
}

.content-pane1 {
  background-color: red;
  height: 15em;
}

.content-pane2 {
  background-color: orange;
  height: 20em;
}

.footer {
  background-color: #80CA9D;
  height: 3.6em;
}</code>```

 Website Access Has Been Blocked

 Here is content-wrapper text

Access to the website address you were trying to visit has been blocked in accordance with policies.

Please call the for help on *somenumber, or email someaddress@example.com, and provide the following information if you believe this is in error.

Block Reason:

Category:
      <category> </category>

User\IP:
      <user> </user>

Webpage:
      <url> </url>

      You can also independently submit a re-categorization request at the following vendor website:
      https://www.someaddress.com/

        Blah blah explanation blah blah

        Additionally, you can blah blah more information here.

 Footer text
```
</div>
</div>
</p>

<p>Entire code as requested: </p>

```<!DOCTYPE html>

        <title></title>

 Website Access Has Been Blocked

 Here is content-wrapper text

Access to the website address you were trying to visit has been blocked in accordance with policies.

Please call the for help on *somenumber, or email someaddress@example.com, and provide the following information if you believe this is in error.

Block Reason:

Category:
                    <category> </category>

User\IP:
                    <user> </user>

Webpage:
                    <url> </url>

                    You can also independently submit a re-categorization request at the following vendor website:
                    https://www.someaddress.com/

                        Blah blah explanation blah blah

                        Additionally, you can blah blah more information here.

 Footer text

```

Body:
Is this what you're attempting to do? The changes:

You have various syntax errors in the javascript i.e opening and closing braces, semicolons not used for terminating expressions, etc.

For setting the second innerHTML, more like appending to the previous reason you need to use "+=" instead of "=". Hope, it helps.

var cat = "Adult";
switch (cat) {
  case "Adult":
    var blockReason = "Inappropriate adult content detected";
    break;
  case "Web-based Email":
    var blockReason = "Due to regulatory reasons we are unable to allow access to unaudited communication channels over web";
    break;
  case "Online Storage and Backup":
    var blockReason = "Websites providing online storage of files for free and as a service not permitted";
    break;
  case "Manually Blocked URLs":
  var blockReason = "URL has been manually blocked outside of predefined categories";
}

document.getElementById("blockReason").innerHTML = "<b>Block Reason: </b>"+blockReason;

var cat = 'Category1';
switch (cat) {
  case 'Category1':
    var blockRs = "Reason1";
    break;

  case 'Category2':
    var blockRs = "Reason2";
    break;

  case 'Category3':
    var blockRs = "Reason3";
    break;

  case 'Category4':
  var blockRs = "Reason4";
  break;
}

document.getElementById('blockReason').innerHTML += "<b>Block Reason: </b>" + blockRs;

html,
body {
  margin: 0;
  padding: 0;
}

body {
  border: 0;
}

.nav {
  width: 100%;
  background-color: #002856;
  color: white;
}

.nav h1 {
  text-align: center;
  margin-top: -.04em;
  font-family: Helvetica, Arial, sans-serif;
}

.content-wrapper {
  background-color: blue;
  height: 40em;
}

.content-pane1 {
  background-color: red;
  height: 15em;
}

.content-pane2 {
  background-color: orange;
  height: 20em;
}

.footer {
  background-color: #80CA9D;
  height: 3.6em;
}

<div class="nav">
  <h1> Website Access Has Been Blocked</h1>
</div>
<div class="content-wrapper"> Here is content-wrapper text
  <div class="content-pane1">
    <p>Access to the website address you were trying to visit has been blocked in accordance with policies.</p>
    <p>Please call the for help on <b>*somenumber</b>, or email someaddress@example.com, and provide the following information if you believe this is in error.</p>

    <p id="blockReason"><b>Block Reason: </b></p>
    <p><b>Category:</b>
      <category> </category>
    </p>
    <p><b>User\IP:</b>
      <user> </user>
    </p>
    <p><b>Webpage:</b>
      <url> </url>
    </p>
  </div>
  <div class="content-pane2">
    <p>
      You can also independently submit a re-categorization request at the following vendor website:
      <a href="https://www.someaddress.com/">https://www.someaddress.com/</a>
      <p>
        Blah blah explanation blah blah
      </p>
      <p>
        Additionally, you can blah blah more information here.
      </p>
  </div>
</div>
<div class="footer"> Footer text </div>

Entire code as requested:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <style>
            html,
        body {
        margin: 0;
        padding: 0;
        }
        body {
        border: 0;
        }
        .nav {
        width: 100%;
        background-color: #002856;
        color: white;
        }
        .nav h1 {
        text-align: center;
        margin-top: -.04em;
        font-family: Helvetica, Arial, sans-serif;
        }
        .content-wrapper {
        background-color: blue;
        height: 40em;
        }
        .content-pane1 {
        background-color: red;
        height: 15em;
        }
        .content-pane2 {
        background-color: orange;
        height: 20em;
        }
        .footer {
        background-color: #80CA9D;
        height: 3.6em;
        }
        </style>
    </head>
    <body>
        <div class="nav">
            <h1> Website Access Has Been Blocked</h1>
        </div>
        <div class="content-wrapper"> Here is content-wrapper text
            <div class="content-pane1">
                <p>Access to the website address you were trying to visit has been blocked in accordance with policies.</p>
                <p>Please call the for help on <b>*somenumber</b>, or email someaddress@example.com, and provide the following information if you believe this is in error.</p>
                <p id="blockReason"><b>Block Reason: </b></p>
                <p><b>Category:</b>
                    <category> </category>
                </p>
                <p><b>User\IP:</b>
                    <user> </user>
                </p>
                <p><b>Webpage:</b>
                    <url> </url>
                </p>
            </div>
            <div class="content-pane2">
                <p>
                    You can also independently submit a re-categorization request at the following vendor website:
                    <a href="https://www.someaddress.com/">https://www.someaddress.com/</a>
                    <p>
                        Blah blah explanation blah blah
                    </p>
                    <p>
                        Additionally, you can blah blah more information here.
                    </p>
                </div>
            </div>
            <div class="footer"> Footer text </div>
            <script >
                var cat = "Adult";
            switch (cat) {
            case "Adult":
            var blockReason = "Inappropriate adult content detected";
            break;
            case "Web-based Email":
            var blockReason = "Due to regulatory reasons we are unable to allow access to unaudited communication channels over web";
            break;
            case "Online Storage and Backup":
            var blockReason = "Websites providing online storage of files for free and as a service not permitted";
            break;
            case "Manually Blocked URLs":
            var blockReason = "URL has been manually blocked outside of predefined categories";
            }
            document.getElementById("blockReason").innerHTML = "<b>Block Reason: </b>"+blockReason;
            var cat = 'Category1';
            switch (cat) {
            case 'Category1':
            var blockRs = "Reason1";
            break;
            case 'Category2':
            var blockRs = "Reason2";
            break;
            case 'Category3':
            var blockRs = "Reason3";
            break;
            case 'Category4':
            var blockRs = "Reason4";
            break;
            }
            document.getElementById('blockReason').innerHTML += "<b>Block Reason: </b>" + blockRs;
            </script>
        </body>
    </html>


问:
Memory allocation?
I have code that looks like the one below. It shows the current date and date after 100 days. However, I've noticed that result turns out to be same. So I thought maybe the addresses of structure or variable were same.

I put "%p" of variable now, later, lnow, and tnow and the result on the very bottom shows that structure pointer of lnow and tnow are both 02B51AA0 while variable later and now have different address.
Now, if I move lnow = localtime(&later) into different location, after first switch statement, then address changes and it works perfectly. Could you explain why this happens?

```<code>#include <stdio.h>
#include <time.h>
struct tm* tnow;
struct tm* lnow;

int main(void)
{
    time_t now = time(NULL);

    time_t later = now + 100*24*3600;
    printf("%p\t%p\n", &now, &later);
    lnow = localtime(&later);
    tnow = localtime(&now);
    printf("%p\t%p\n", lnow, tnow);
    printf("%d.%d.%d\t", tnow->tm_year+1900, tnow->tm_mon+1, tnow->tm_mday);
    switch (tnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    printf("%d.%d.%d\t", lnow->tm_year+1900, lnow->tm_mon+1, lnow->tm_mday);
    switch (lnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    return 0;
}
</code>```

Results:

```<code>0061FF2C 0061FF28
02B51AA0 02B51AA0
2017.12.8 ELSE
2017.12.8 ELSE
</code>```

答:
The standard C library has 3 functions ctime(), gmtime(), localtime() that all use the same static struct tm object.  A call to anyone of them or a repeated call, will re-use that same object.

The calls below return either NULL (if the conversion failed) or a pointer to the same object.  The  struct tm object may be over written  each call.

Execution of any of the functions that return a pointer to one of these object types may overwrite the information in any object of the same type pointed to by the value returned from any previous call to any of them ...  C11dr §7.27.3 1

```<code>struct tm *lnow = localtime(&later);
struct tm *tnow = localtime(&now);
struct tm *foo = gmtime(&now);
</code>```

To retain the result, copy the object referenced by the returned pointer.  Error checking is a good idea too.

```<code>struct tm *tm_ptr = localtime(&later);
if (tm_ptr == NULL) {
  fprintf(stderr, "Bad later time\n");
  exit(EXIT_FAILURE);
}
struct tm lnow = *tm_ptr;  // copy the broken-down time
switch (lnow.tm_wday)
  ...
</code>```

Title: Memory allocation?

Body:
I have code that looks like the one below. It shows the current date and date after 100 days. However, I've noticed that result turns out to be same. So I thought maybe the addresses of structure or variable were same.

I put "%p" of variable now, later, lnow, and tnow and the result on the very bottom shows that structure pointer of lnow and tnow are both 02B51AA0 while variable later and now have different address.
Now, if I move lnow = localtime(&later) into different location, after first switch statement, then address changes and it works perfectly. Could you explain why this happens?

#include <stdio.h>
#include <time.h>
struct tm* tnow;
struct tm* lnow;

int main(void)
{
    time_t now = time(NULL);

    time_t later = now + 100*24*3600;
    printf("%p\t%p\n", &now, &later);
    lnow = localtime(&later);
    tnow = localtime(&now);
    printf("%p\t%p\n", lnow, tnow);
    printf("%d.%d.%d\t", tnow->tm_year+1900, tnow->tm_mon+1, tnow->tm_mday);
    switch (tnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    printf("%d.%d.%d\t", lnow->tm_year+1900, lnow->tm_mon+1, lnow->tm_mday);
    switch (lnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    return 0;
}

Results:

0061FF2C 0061FF28
02B51AA0 02B51AA0
2017.12.8 ELSE
2017.12.8 ELSE

Body:
The standard C library has 3 functions ctime(), gmtime(), localtime() that all use the same static struct tm object.  A call to anyone of them or a repeated call, will re-use that same object.

The calls below return either NULL (if the conversion failed) or a pointer to the same object.  The  struct tm object may be over written  each call.

Execution of any of the functions that return a pointer to one of these object types may overwrite the information in any object of the same type pointed to by the value returned from any previous call to any of them ...  C11dr §7.27.3 1

struct tm *lnow = localtime(&later);
struct tm *tnow = localtime(&now);
struct tm *foo = gmtime(&now);

To retain the result, copy the object referenced by the returned pointer.  Error checking is a good idea too.

struct tm *tm_ptr = localtime(&later);
if (tm_ptr == NULL) {
  fprintf(stderr, "Bad later time\n");
  exit(EXIT_FAILURE);
}
struct tm lnow = *tm_ptr;  // copy the broken-down time
switch (lnow.tm_wday)
  ...