问:
Return property directly when class is called (Matlab)
I have a class called foo with only property M,

```<code>classdef foo
    properties
        M
    end

    methods
        function obj = foo(arg1)
            M=arg1;
        end
    end
end
</code>```

and I create the object:

```<code>F=foo(1)
</code>```

In C++ it is possible, that when I call F, that I directly get the value of one chosen variable. In my case I would like to get F.M when I just write F. For example this would allow to write

```<code>size(F)
</code>```

instead of writing

```<code>size(F.M)
</code>```

or defining a method size for my class. Is there a way in MATLAB to achieve this?

Edit: In other words, whenever I write F, I want that MATLAB reads it as F.M.

Edit: I will clarify what I want to acchieve.
My class represents a matrix whose values are multivariate infinite sequences with compact support. Thus I have to do a lot of bookkeeping not to mix up all the indices. Things I want to do with my matrix:

Matrix multiplication.

Convolution.

Upsampling, downsampling.

Everything else which is possible in a vector/matrix space.

I thought this is easier to acchieve when I encapsulate all the meta-data (this are the indices of the 0^th entries of the sequence) together with the data.
Because my class is actually a matrix, most operations work on that class in the same way as on ordinary matrices. Therefore I do not want to code it all over again (Because of code-maintenance, less bugs, code-readability).

In C++ I could do it that way. It seems, my approach to that problem is the wrong one in MATLAB.

答:
You have to overload the function size as I mentioned in my comment.

```<code>classdef foo
    properties
        M
    end

    methods
        function obj = foo(arg)
            obj.M = arg;
        end

        function varargout = size(obj, varargin)
            if nargin == 1
                varargout = size(obj.M);
            elseif nargin == 2 && nargout == 1
                varargout = size(obj.M, varargin{1})
            else
                error('Wrong number of input or output arguments.')
            end
        end
        function ret = mtimes(varargin)
            try
                ret = varargin{1}.M * varargin{2};
            catch
                ret = varargin{1} * varargin{2}.M;
            end
        end
    end

end
</code>```

Console Output:

```<code>>> F=foo(0:3);
>> size(F)

ans =

     1     4

>> size(F, 2)

ans =

     4

>> F*(4:7).'

ans =

    38

>> (4:7).'*F

ans =

     0     4     8    12
     0     5    10    15
     0     6    12    18
     0     7    14    21
</code>```

I could continue but preparing the console output for StackOverflow is horrible...

Body:
I have a class called foo with only property M,

classdef foo
    properties
        M
    end

    methods
        function obj = foo(arg1)
            M=arg1;
        end
    end
end

and I create the object:

F=foo(1)

In C++ it is possible, that when I call F, that I directly get the value of one chosen variable. In my case I would like to get F.M when I just write F. For example this would allow to write

size(F)

instead of writing

size(F.M)

or defining a method size for my class. Is there a way in MATLAB to achieve this?

Edit: In other words, whenever I write F, I want that MATLAB reads it as F.M.

Edit: I will clarify what I want to acchieve.
My class represents a matrix whose values are multivariate infinite sequences with compact support. Thus I have to do a lot of bookkeeping not to mix up all the indices. Things I want to do with my matrix:

Matrix multiplication.

Convolution.

Upsampling, downsampling.

Everything else which is possible in a vector/matrix space.

I thought this is easier to acchieve when I encapsulate all the meta-data (this are the indices of the 0^th entries of the sequence) together with the data.
Because my class is actually a matrix, most operations work on that class in the same way as on ordinary matrices. Therefore I do not want to code it all over again (Because of code-maintenance, less bugs, code-readability).

In C++ I could do it that way. It seems, my approach to that problem is the wrong one in MATLAB.

Body:
You have to overload the function size as I mentioned in my comment.

classdef foo
    properties
        M
    end

    methods
        function obj = foo(arg)
            obj.M = arg;
        end

        function varargout = size(obj, varargin)
            if nargin == 1
                varargout = size(obj.M);
            elseif nargin == 2 && nargout == 1
                varargout = size(obj.M, varargin{1})
            else
                error('Wrong number of input or output arguments.')
            end
        end
        function ret = mtimes(varargin)
            try
                ret = varargin{1}.M * varargin{2};
            catch
                ret = varargin{1} * varargin{2}.M;
            end
        end
    end

end

Console Output:

>> F=foo(0:3);
>> size(F)

ans =

     1     4

>> size(F, 2)

ans =

     4

>> F*(4:7).'

ans =

    38

>> (4:7).'*F

ans =

     0     4     8    12
     0     5    10    15
     0     6    12    18
     0     7    14    21

I could continue but preparing the console output for StackOverflow is horrible...


来源: stackexchange

问:
filemanager plugin - TinyMCE - the server response wasn't JSON format
recently we updated a server from php 5.3 to php 7, actually I don't know if the update causes this issue, but when I go to insert a file on TinyMCE javascirpt I receive this error message:

The server response wasn't JSON format

I haven't found anything on internet about it.

here is Json_data:

```<code>{"method":"fm.insertFiles","params":[{"path0":"{0}/Sage.JPG"}],"id":"c0"}
</code>```

here is TinyMCE configuration:

```<code>    tinyMCE.init({
    // General options
        mode : "exact",
        elements : "msg_body",
    theme : "advanced",
    theme_advanced_resizing_max_width : 530,
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,spellchecker,filemanager",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,|,styleselect,formatselect,|,forecolor,backcolor,<?if ($staff[perm][msg_replies]==1) {?>|,insertfile,link,<?}?>|,spellchecker",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    //External
    extended_valid_elements : "iframe[src|width|height|name|align]",

    // Example content CSS (should be your site CSS)
    content_css : "../style-bijou.css",

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

    // Style formats
    style_formats : [
        {title : 'Bijou Weddings styles'},
        {title : 'Bijou copy', block : 'p', classes : 'copy'},
        {title : 'Bijou copy bold', inline : 'span', classes : 'title'},
        {title : 'Corporate Event styles'},
        {title : 'Event bullets small', block : 'p', classes : 'corpbodybull'},
        {title : 'Event bullets big', block : 'p', classes : 'corpbull'},
        {title : 'Table styles'},
        {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
    ],

    // Replace values for the template plugin
    template_replace_values : {
        username : "Some User",
        staffid : "991234"
    }

});
</code>```

Do you have any idea please?
thanks

答:
I finally found what caused the problem,

The plugin "filemanager" generate a php error, the file History.php located in folder /plugins/filemanager/plugins/History is using a php function called split which is obsoleted for php7.

So I swap the function split with function explode. Now the file inserting is working properly.

Hope this will be useful.

here is the explanation in php.net:
http://php.net/manual/en/function.split.php
and
http://php.net/manual/en/function.explode.php

ContentLicense: CC BY-SA 3.0

Body:
recently we updated a server from php 5.3 to php 7, actually I don't know if the update causes this issue, but when I go to insert a file on TinyMCE javascirpt I receive this error message:

The server response wasn't JSON format

I haven't found anything on internet about it.

here is Json_data:

{"method":"fm.insertFiles","params":[{"path0":"{0}/Sage.JPG"}],"id":"c0"}

here is TinyMCE configuration:

    tinyMCE.init({
    // General options
        mode : "exact",
        elements : "msg_body",
    theme : "advanced",
    theme_advanced_resizing_max_width : 530,
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,spellchecker,filemanager",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,|,styleselect,formatselect,|,forecolor,backcolor,<?if ($staff[perm][msg_replies]==1) {?>|,insertfile,link,<?}?>|,spellchecker",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    //External
    extended_valid_elements : "iframe[src|width|height|name|align]",

    // Example content CSS (should be your site CSS)
    content_css : "../style-bijou.css",

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

    // Style formats
    style_formats : [
        {title : 'Bijou Weddings styles'},
        {title : 'Bijou copy', block : 'p', classes : 'copy'},
        {title : 'Bijou copy bold', inline : 'span', classes : 'title'},
        {title : 'Corporate Event styles'},
        {title : 'Event bullets small', block : 'p', classes : 'corpbodybull'},
        {title : 'Event bullets big', block : 'p', classes : 'corpbull'},
        {title : 'Table styles'},
        {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
    ],

    // Replace values for the template plugin
    template_replace_values : {
        username : "Some User",
        staffid : "991234"
    }

});

Do you have any idea please?
thanks

ContentLicense: CC BY-SA 4.0


问:
Read from file and call function
I have a task in which I need to read from text file and call a function. The text file is following:

```<code>black,20,10,3,1
red,10,20,4,3
blue,10,-20,-4,3
</code>```

My defined function takes five parameters, which are split in the text flile by commas.
This is what I have so far:

```<code>with open(textfile) as source:
    for i in source.readlines():
        a = split(",")
</code>```

But here I have no idea how to call the function with the read line from source.

Any ideas?

答:
I ended up with this and it is working.

```<code>def piirra_tiedostosta(tiedosto):
    with open(tiedosto) as source:
        for i in source.read().splitlines():
        c, a, r, n, w = i.split(",")
        a = int(a)
        r = int(r)
        n = float(n)
        w = int(w.strip())
</code>```

Now I have all the variables separated from eachother, and I can call the function.

f(c, a, r, n, w)

Title: Read from file and call function

Body:
I have a task in which I need to read from text file and call a function. The text file is following:

black,20,10,3,1
red,10,20,4,3
blue,10,-20,-4,3

My defined function takes five parameters, which are split in the text flile by commas.
This is what I have so far:

with open(textfile) as source:
    for i in source.readlines():
        a = split(",")

But here I have no idea how to call the function with the read line from source.

Any ideas?

Body:
I ended up with this and it is working.

def piirra_tiedostosta(tiedosto):
    with open(tiedosto) as source:
        for i in source.read().splitlines():
        c, a, r, n, w = i.split(",")
        a = int(a)
        r = int(r)
        n = float(n)
        w = int(w.strip())

Now I have all the variables separated from eachother, and I can call the function.

f(c, a, r, n, w)


问:
How to separate host list and group hiererachy in ansible's inventory?
I have a big project under Ansible. There are many groups in it, most of them for the sake of clarity. For example, there are groups 'dbaccess', 'java', etc, which help to find hosts which need access to database, to have java installed, etc. Some of them nested (f.e. 'collector' group is a child for 'java' group, as all collectors need java).

It all is kept inside inventory using 'group:children' technique.

But when I want to create staging inventory I have a problem: I need not only provide new hosts in inventory, but also recreate whole group hierarchy.

I wonder if there are any way to separate inventory in such a way that group hierarchy would be kept separate from host list?

Or, may be, there is some other way to organize such hierarchy in Ansible?

(example of my real inventory):

```<code>[collectors]
(host list)
[publishers-http]
(host list)
[publishers-smtp]
(host list)
[central]
(host list)

[java:children]
collectors
publishers-http
central

[postgre_access:children]
collectors
publishers
central

[mongo_access:children]
collectors
publishers-smtp
central

[redis_access:children]
central
publishers
</code>```

I want a way to change host lists for staging but keep relations between groups intact.

答:
Split your inventory into two files -- one named 01_hosts containing:

```<code>[collectors]
(host list)
[publishers-http]
(host list)
[publishers-smtp]
(host list)
[central]
(host list)
</code>```

the other named 02_groups containing:

```<code>[java:children]
collectors
publishers-http
central

[postgre_access:children]
collectors
publishers
central

[mongo_access:children]
collectors
publishers-smtp
central

[redis_access:children]
central
publishers
</code>```

Save them to my_inventory directory, use path to my_inventory as a parameter for the inventory (either in CLI, or in ansible.cfg).

Use symlinks to have a single source for 02_groups.

I suggested 01_ and 02_ prefixes because Ansible reads files from an inventory directory alphabetically and hosts/groups must be defined before groups of groups.

Body:
I have a big project under Ansible. There are many groups in it, most of them for the sake of clarity. For example, there are groups 'dbaccess', 'java', etc, which help to find hosts which need access to database, to have java installed, etc. Some of them nested (f.e. 'collector' group is a child for 'java' group, as all collectors need java).

It all is kept inside inventory using 'group:children' technique.

But when I want to create staging inventory I have a problem: I need not only provide new hosts in inventory, but also recreate whole group hierarchy.

I wonder if there are any way to separate inventory in such a way that group hierarchy would be kept separate from host list?

Or, may be, there is some other way to organize such hierarchy in Ansible?

(example of my real inventory):

[collectors]
(host list)
[publishers-http]
(host list)
[publishers-smtp]
(host list)
[central]
(host list)

[java:children]
collectors
publishers-http
central

[postgre_access:children]
collectors
publishers
central

[mongo_access:children]
collectors
publishers-smtp
central

[redis_access:children]
central
publishers

I want a way to change host lists for staging but keep relations between groups intact.

Body:
Split your inventory into two files -- one named 01_hosts containing:

[collectors]
(host list)
[publishers-http]
(host list)
[publishers-smtp]
(host list)
[central]
(host list)

the other named 02_groups containing:

[java:children]
collectors
publishers-http
central

[postgre_access:children]
collectors
publishers
central

[mongo_access:children]
collectors
publishers-smtp
central

[redis_access:children]
central
publishers

Save them to my_inventory directory, use path to my_inventory as a parameter for the inventory (either in CLI, or in ansible.cfg).

Use symlinks to have a single source for 02_groups.

I suggested 01_ and 02_ prefixes because Ansible reads files from an inventory directory alphabetically and hosts/groups must be defined before groups of groups.


问:
Hiding play button initially
How would I hide the Playbutton when viewing the cover image, and show it after you click on the image?

I've been trying different ways, but can't seem to get it.

Full Code:

https://jsfiddle.net/0yxvpa09/12/

Click on the image to reveal a grid

Screenshot

```<code><div class="playButton ">

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

<script>
  (function iife() {
    "use strict";

    function hideClickedElement(evt) {
      var target = evt.target;
      target.classList.add("hide");
      document.querySelector(".test").classList.remove("hide");
    }
    var cover = document.querySelector(".cover");
    cover.addEventListener("click", hideClickedElement, false);
  }());

</script>
</code>```

答:
(function iife() {
  "use strict";

  function hideClickedElement(evt) {
    var target = evt.target;
    target.classList.add("hide");
    document.querySelector(".test").classList.remove("hide");
    document.querySelector(".playButton").classList.remove("hide");
  }
  document.querySelector(".playButton").classList.add("hide");
  var cover = document.querySelector(".cover");
  cover.addEventListener("click", hideClickedElement, false);
}());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .cover {
    width: 260px;
    height: 168px;
    cursor: pointer;
    background-image: linear-gradient( to right, transparent, transparent 83px, #0059dd 83px, #0059dd 86px, transparent 86px, transparent 174px, #0059dd 174px, #0059dd 177px, transparent 177px, transparent 260px), url("https://i.imgur.com/BBYxKcf.jpg");
    border: 3px solid #0059dd;
    font-family: Tahoma;
    font-weight: bold;
    font-size: 30px;
    color: #0059dd;
    cursor: pointer;
    line-height: 100px;
    text-align: center;
  }

  .links div {
    margin: 0 0 12px 0;
  }

  .links a {
    display: block;
    width: 50px;
    height: 50px;
    background-color: green;
    margin: -50px 0 0;
    transition: 0.5s ease-in-out;
  }

  a.x1 {
    margin: 0
  }

  a.x2 {
    margin-left: 54px
  }

  a.x3 {
    margin-left: 108px
  }

  a.x4 {
    margin-left: 162px
  }

  a.x5 {
    margin-left: 216px
  }

  .links a:hover,
  .links a:active,
  .links a:focus {
    background: blue;
  }

  .scrl a:visited {
    background: orange;
    color: #000000;
  }

  .scrl a:hover {
    background: red;
  }

  .hide {
    display: none;
  }

  .links div:last-child {
    margin-bottom: 0;
  }
  .playButton {
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: #000000;
    fill: #aaff00;
    margin: -112px 0 0 108px;
  }

  .playButton.playing {
    background-color: #000000;
  }</code>```

Links

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

```

Hide your play button div onload using your class hide. then remove it on click of cover element.

Title: Hiding play button initially

Body:
How would I hide the Playbutton when viewing the cover image, and show it after you click on the image?

I've been trying different ways, but can't seem to get it.

Full Code:

https://jsfiddle.net/0yxvpa09/12/

Click on the image to reveal a grid

Screenshot

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

Body:
(function iife() {
  "use strict";

  function hideClickedElement(evt) {
    var target = evt.target;
    target.classList.add("hide");
    document.querySelector(".test").classList.remove("hide");
    document.querySelector(".playButton").classList.remove("hide");
  }
  document.querySelector(".playButton").classList.add("hide");
  var cover = document.querySelector(".cover");
  cover.addEventListener("click", hideClickedElement, false);
}());

  .cover {
    width: 260px;
    height: 168px;
    cursor: pointer;
    background-image: linear-gradient( to right, transparent, transparent 83px, #0059dd 83px, #0059dd 86px, transparent 86px, transparent 174px, #0059dd 174px, #0059dd 177px, transparent 177px, transparent 260px), url("https://i.imgur.com/BBYxKcf.jpg");
    border: 3px solid #0059dd;
    font-family: Tahoma;
    font-weight: bold;
    font-size: 30px;
    color: #0059dd;
    cursor: pointer;
    line-height: 100px;
    text-align: center;
  }

  .links div {
    margin: 0 0 12px 0;
  }

  .links a {
    display: block;
    width: 50px;
    height: 50px;
    background-color: green;
    margin: -50px 0 0;
    transition: 0.5s ease-in-out;
  }

  a.x1 {
    margin: 0
  }

  a.x2 {
    margin-left: 54px
  }

  a.x3 {
    margin-left: 108px
  }

  a.x4 {
    margin-left: 162px
  }

  a.x5 {
    margin-left: 216px
  }

  .links a:hover,
  .links a:active,
  .links a:focus {
    background: blue;
  }

  .scrl a:visited {
    background: orange;
    color: #000000;
  }

  .scrl a:hover {
    background: red;
  }

  .hide {
    display: none;
  }

  .links div:last-child {
    margin-bottom: 0;
  }
  .playButton {
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: #000000;
    fill: #aaff00;
    margin: -112px 0 0 108px;
  }

  .playButton.playing {
    background-color: #000000;
  }

<div class="cover">Links</div>
<div class="test hide">

  <div class="links    ">
    <div>
      <a class="x1" href="" target="_blank"></a>
      <a class="x2" href="" target="_blank"></a>
      <a class="x3" href="" target="_blank"></a>
      <a class="x4" href="" target="_blank"></a>
      <a class="x5" href="" target="_blank"></a>
    </div>

    <div>
      <a class="x1" href="" target="_blank"></a>
      <a class="x2" href="" target="_blank"></a>

      <a class="x4" href="" target="_blank"></a>
      <a class="x5" href="" target="_blank"></a>
    </div>

    <div>
      <a class="x1" href="" target="_blank"></a>
      <a class="x2" href="" target="_blank"></a>
      <a class="x3" href="" target="_blank"></a>
      <a class="x4" href="" target="_blank"></a>
      <a class="x5" href="" target="_blank"></a>
    </div>
  </div>
</div>

<div class="playButton ">

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>
</div>

Hide your play button div onload using your class hide. then remove it on click of cover element.


问:
how to ignore attribute without quotes in xml
i want to count how many times tag1 occurs
givin this 123.xml file ( streaming from the internet)

```<code><startend>

 <tag1 name=myname>
<date>10-10-10</date>
</tag1 >

 <tag1 name=yourname>
   <date>11-10-10</date>
  </tag1 >

 </startend>
</code>```

using : xmlstarlet sel -t -v  "count(//tag1)" 123.xml

output :

AttValue: " or ' expected
attributes construct error

how to ignore that the attribute has no " "  ?

答:
You input XML/HTML structure has invalid tags/attributes and should be recovered beforehand:

xmlstarlet solution:

```<code>xmlstarlet fo -o -R -H -D 123.xml 2>/dev/null | xmlstarlet sel -t -v "count(//tag1)" -n
</code>```

The output:

```<code>2
</code>```

Details:

fo (or format) - Format XML document(s)

-o or --omit-decl - omit xml declaration

-R or --recover - try to recover what is parsable

-D or --dropdtd - remove the DOCTYPE of the input docs

-H or --html - input is HTML

2>/dev/null - suppress errors/warnings

Body:
i want to count how many times tag1 occurs
givin this 123.xml file ( streaming from the internet)

<startend>

 <tag1 name=myname>
<date>10-10-10</date>
</tag1 >

 <tag1 name=yourname>
   <date>11-10-10</date>
  </tag1 >

 </startend>

using : xmlstarlet sel -t -v  "count(//tag1)" 123.xml

output :

AttValue: " or ' expected
attributes construct error

how to ignore that the attribute has no " "  ?

Body:
You input XML/HTML structure has invalid tags/attributes and should be recovered beforehand:

xmlstarlet solution:

xmlstarlet fo -o -R -H -D 123.xml 2>/dev/null | xmlstarlet sel -t -v "count(//tag1)" -n

The output:

2

Details:

fo (or format) - Format XML document(s)

-o or --omit-decl - omit xml declaration

-R or --recover - try to recover what is parsable

-D or --dropdtd - remove the DOCTYPE of the input docs

-H or --html - input is HTML

2>/dev/null - suppress errors/warnings


问:
Spark-shell running a SELECT for a dataframe
I've created a spark scala script to load a file with customers information. Then I have created a case class to map the records and show them up as a table, my script below:

```<code>//spark context
sc
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

//Define the class to map customers coming from the data inputh
case class customer (cusid: Int, name: String, city : String, province: String, postalcode: String)

//load the file info
val customer_file = sc.textFile("file:////home/ingenieroandresangel/scalascripts/customer.txt")
val customer_rdd = customer_file.map(_.split(",")).map(p => customer(p(0).toInt,p(1),p(2),p(3),p(4)))

val cusstomerdf = customer_rdd.toDF()
</code>```

current results:

Now, I need to perform spark sql queries to get back just a column coming from my dataframe, example the column name:

print(cusstomerdf.select("name"))

Nevertheless, the results are not as expected. I need to get back the rows for the column name but instead, I get this  result:

Question: How should I run the right select to get back just the column name on my dataframe??  thanks

答:
The result is correct. You are doing a transformation only as select is a transformation.

If you save it in a parquet file or a csv file you will see the result and can confirm that the column is already selected.

Meanwhile you can see the result on the screen by doing

```<code>val selecteddf = customerdf.select("name")
selecteddf.show(false)
</code>```

which will show the 20 rows of name column

Body:
I've created a spark scala script to load a file with customers information. Then I have created a case class to map the records and show them up as a table, my script below:

//spark context
sc
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

//Define the class to map customers coming from the data inputh
case class customer (cusid: Int, name: String, city : String, province: String, postalcode: String)

//load the file info
val customer_file = sc.textFile("file:////home/ingenieroandresangel/scalascripts/customer.txt")
val customer_rdd = customer_file.map(_.split(",")).map(p => customer(p(0).toInt,p(1),p(2),p(3),p(4)))

val cusstomerdf = customer_rdd.toDF()

current results:

Now, I need to perform spark sql queries to get back just a column coming from my dataframe, example the column name:

print(cusstomerdf.select("name"))

Nevertheless, the results are not as expected. I need to get back the rows for the column name but instead, I get this  result:

Question: How should I run the right select to get back just the column name on my dataframe??  thanks

Body:
The result is correct. You are doing a transformation only as select is a transformation.

If you save it in a parquet file or a csv file you will see the result and can confirm that the column is already selected.

Meanwhile you can see the result on the screen by doing

val selecteddf = customerdf.select("name")
selecteddf.show(false)

which will show the 20 rows of name column


问:
Difference between cypress and a BDD framework like cucumber
can someone explain me the difference between cypress.io as testing framework and a BDD framework like cucumber e.g.
As far as I understand cypress.io is a ui-testing framework for javascript.
tests are written in javascript.
you can use scenarios to describe a flow through the app as e2e-test.
Is that similar to a behavior test or has this framework only focus on the ui?

Someone comes around the corner and says: Cucumber or JBehave is the same as cypress. I fear that's not true. but what are the arguments that can be answered.
I don't develop web-apps and it's hard for me to compare both solutions.

I try to clarify my question:
Imagine there's an application with backend services and a frontend (web-app) that uses these services. The backend represents complex workflows and the whole app shall be tested by a BDD Framework (e.g. cucumber). The major benefit is a kind of up-to-date documentation by feature- and scenario-descriptions. It's the core of a framework like cucumber. A further benefit it's of course the (maybe e2e) test itself. To have value it needs ui-testing to test the whole workflow. e.g. you could use selenium together with cucumber to handle this. I think cypress is a kind of testing framework like selenium, right? Only much better in many ways. But someone could say: "oh ... cypress is the same as cucumber, because you can also define scenarios, etc ... But I believe, when we think about BDD then cypress has to be used in combination with cucumber and not as a new stand-alone BDD-Tool. From my point of view cypress is a great ui-testing framework, but ... not more?! I anncounced my question here to find answers for clarification.

答:
Updated answer

If what you're asking is whether Cypress can be used for more than unit testing the UI, the answer is yes, from the first page of the docs:

Cypress enables you to write all types of tests:
  - End to end tests
  - Integration tests
  - Unit tests

Try reading the rest of the documentation to get an idea of the tool's capabilities; the Stack Overflow community can answer questions for you, but they can not (and certainly will not) do your homework for you.

Also: Try being more concise in your questions, both in the title and in the description. Brevity is often a sign of having a clearly defined problem, while verbosity is not, and your long description doesn't serve your question well.

The core of this question is not the difference between Cypress and Cucumber, it is: "Can Cypress be used for more than just unit testing the GUI? I am also interested in testing stuff like the database [and so on ...]"

A sad fact of Stack Overflow is that you don't any responses if you don't make your question easy to answer. Good luck with taking this constructive criticism to heart and making your upcoming questions readable and concise.

Original answer

I would encourage you to ask questions that can have a clearly defined, factual answer, not one in which the answer depends on subjective evaluations, such as the one I am about to give. But here goes:

To my untrained eye (having no experience with Cucumber and some weeks of experience with Cypress), the main difference between Cucumber and Cypress is that Cucumber seems to be aimed at testing in general, not just for the web, and has to be run using some test framework (such as Selenium): https://cucumber.io/docs Cypress specializes in web-testing and provides everything you need to run it as one installable package, including its own test framework: https://www.cypress.io/how-it-works/


问:
How to override background color of body without changing the existing background color?
how do i change the body background color red without overriding css or removing the css property?
https://i.stack.imgur.com/vNkRh.png</p>

答:
You can't do so. The only way styles are defined is with CSS.

If you want to do it without changing the existing CSS-file, use inline-styling (this will override the property from the file for that element only). If you neither have access to HTML nor CSS, one of the other two posted answers are what you are looking for.


问:
No warning at undefined variables in PyCharm Community 2017.2
I have this piece of code in a Python module open in PyCharm Community Edition 2017.2.

```<code>class Sample(object):
    def __init__(self):
        self.prop1 = 5
        self.prop2 = 10

    def method1(self):
        return foo

    def do_work(self):
        not_defined_func()

s = Sample()
s.method1()

bar = call_func
</code>```

The IDE doesn't give any warnings on some fairly serious issues:

The returned variable foo has not been defined.

I assign not defined variable call_func to the variable bar.

I call not defined function not_defined_func inside the method do_work.

How do I enable PyCharm to highlight these things? I have a fresh installation of PyCharm and have all the Inspections enabled in File > Settings > Editor > Inspections > Python.

答:
See which python interpreter is enabled go to preference > Project > Project Interpreter. Set python interpreter and then apply it.
Also check if inspections are enabled.</p>

Body:
I have this piece of code in a Python module open in PyCharm Community Edition 2017.2.

class Sample(object):
    def __init__(self):
        self.prop1 = 5
        self.prop2 = 10

    def method1(self):
        return foo

    def do_work(self):
        not_defined_func()

s = Sample()
s.method1()

bar = call_func

The IDE doesn't give any warnings on some fairly serious issues:

The returned variable foo has not been defined.

I assign not defined variable call_func to the variable bar.

I call not defined function not_defined_func inside the method do_work.

How do I enable PyCharm to highlight these things? I have a fresh installation of PyCharm and have all the Inspections enabled in File > Settings > Editor > Inspections > Python.


问:
What are some interesting gotchas with non sql databases like Cassandra...?
There has been a lot happening in this area, and while obvious of the technical differences i wanted to hear more about how developers have gotten around the bad bits and taken advatange of the different approach.

A brief summary to avoid boring responses that state the obvious.
   - They are schemaless
   - Faster than SQL

I am particularly interested in:

Cassandra

答:
Interesting gotchas:

They're all very different. Cassandra, MongoDB and CouchDB seem like basically the same thing, but they're not. Expect to have to dig into details of your implementation.

You will need to learn how to map-reduce. (with the DB of your choice)

You will have to restructure your data. The first thing you'll typically encounter is that true "children" data will now be stored with the parent. This will make a ton of programmatic sense, but you'll have to fight your old urges to 'normalize'.

You will have to restructure your data a little more when you realize that your "core" data is not the data you thought it was.

You will probably write a few more for loops than you're used to. Neither good nor bad, this is really a side-effect of realizing that some things you did with sum(field) don't work quite the same b/c you now have the all of the data in your current process.

Things you'll find with MongoDB specifically:
 - You will spend a lot less time administrating. DB & "table" creation are now free & automatic. This is a little trippy at first.
 - You will probably have to extend a bunch of your server monitoring software. Things like Nagios or Scout don't have this tracking built-in (yet).
 - You look at indexes with a much more careful eye. It's easy to get careless with indexes in SQL. Useless indexes in MongoDB can quickly degrade performance.

The biggest gotcha: You will have to "think different".

We've been trapped in a relational world for years. We're used to thinking of data in relational terms. Most of us naturally normalize data as we're designing tables. We like to optimize for "all possible queries" very early on.

NoSQL is very different. You'll start denormalize early. You'll focus exclusively on your most frequently run queries. You'll quickly realize that most slow queries don't really need real-time answers. Those will become map-reduce jobs that update data.

ContentLicense: CC BY-SA 2.5


问:
How to close a SearchView programmatically on back pressed?
I have the same question which I found here which I will re-iterate because the solution is not 100% exactly what I need:

I currently have a SearchView in the action bar of my app. When I click the search icon, the SearchView expands and the keyboard pops up as expected. Clicking the "X" in the SearchView box closes the SearchView as expected. However, when the SearchView is activated and I press the "back" button, my app is exited. This is the correct behavior, but what I am trying to do now is to capture back button press and just have it close the SearchView (not my app) when the SearchView is visible. Is there a way to invoke the SearchView OnCloseListener() programmatically on a back button press? For example, something like this:

Here is the solution:

```<code>@Override
public void onBackPressed() {
  if (!searchView.isIconified()) {
    searchView.setIconified(true);
  } else {
    super.onBackPressed();
  }
}
</code>```

The problem is the solution requires the user to press back not once, but twice: once* to exit the keyboard and **once to close the SearchView.

How can I close the keyboard AND the SearchView at the same time by pressing back once?

edit:

Somone had a similar problem with EditText and the solution was to subclass the EditText view.

答:
I did it like this in the activity where the SearchView is located     </p>

```<code>@Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
        }
    }
</code>```

Body:
I have the same question which I found here which I will re-iterate because the solution is not 100% exactly what I need:

I currently have a SearchView in the action bar of my app. When I click the search icon, the SearchView expands and the keyboard pops up as expected. Clicking the "X" in the SearchView box closes the SearchView as expected. However, when the SearchView is activated and I press the "back" button, my app is exited. This is the correct behavior, but what I am trying to do now is to capture back button press and just have it close the SearchView (not my app) when the SearchView is visible. Is there a way to invoke the SearchView OnCloseListener() programmatically on a back button press? For example, something like this:

Here is the solution:

@Override
public void onBackPressed() {
  if (!searchView.isIconified()) {
    searchView.setIconified(true);
  } else {
    super.onBackPressed();
  }
}

The problem is the solution requires the user to press back not once, but twice: once* to exit the keyboard and **once to close the SearchView.

How can I close the keyboard AND the SearchView at the same time by pressing back once?

edit:

Somone had a similar problem with EditText and the solution was to subclass the EditText view.

Body:
I did it like this in the activity where the SearchView is located

@Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
        }
    }


问:
Explicitly inheriting from 'type' to implement metaclass in python3.x
I was trying to get some intuition about metaclass in Python. I have tried on both Python2.7 and   and Python3.5. In Python3.5 I found every class we define is of type <class 'type'> whether we explicitly inherit or not. But if not inherited from type we can't use that class as a metaclass for another class.

```<code>>>> class foo:
    pass

>>> class Metafoo(type):
    pass

>>> foo
<class '__main__.foo'>
>>> Metafoo
<class '__main__.Metafoo'>
>>> type(foo)
<class 'type'>
>>> type(Metafoo)
<class 'type'>
>>>
>>> class foocls1(metaclass=foo):
    pass
</code>```

doing the above I get the following error:

```<code>Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    class foocls1(metaclass=foo):
TypeError: object() takes no parameters
</code>```

But that is not in the case while using Metafoo as metaclass for the new class

```<code>>>> class foocls3(metaclass=Metafoo):
    pass

>>> foocls3
<class '__main__.foocls3'>
>>> type(foocls3)
<class '__main__.Metafoo'>
</code>```

Can anyone explain why this is the case that we need to explicitly inherit if we want to use a class as metaclass in other class.

答:
"type" is the base class for all class objects in Python 3, and in Python 2 post version 2.2.  (It is just that on Python 2, you are supposed to inherit from object. Classes that do not explicitly inherit from "object" in Python 2 were called "old style classes", and kept for backward compatibility purposes, but were of little use.)

So, what happens is that inheritance: what are the superclasses of a class, and "metaclass" that is "since in Python a class is an object itself, what is the class of that object" are two different things. The classes you inherit from define the order of attribute (and method) lookup on the instances of your class, and therefore you have a common behavior.

The metaclass is rather "the class your class is built with", and although it can serve other purposes, is most used to modify the construction step of your classes itself. Search around and you will see metaclasses mostly implementing the __new__ and __init__ methods. (Although it is ok to have other methods there, but yu have to know what you are doing)

It happens that to build a class some actions are needed that are not required to build normal objects. These actions are performed on the native-code layer (C in CPython) and are not even reproducible in pure Python code, like populating the class's special method slots- the pointers to the functions that implement the __add__, __eq__ and such methods. The only class that does that in CPython is "type". So any code you want to use to build a class, i.e. as a metaclass, will have to at some point call type.__new__ method.  (Just as any thing you want to create a new object in Python will at some point call the code in  object.__new__.).

Your error happened not because Python goes checking whether you made a direct or indirect call to type.__new__ ahead of time. The error: "TypeError: object() takes no parameters" is simply due to the fact that __new__ method of the metaclass is passed 3 parameters (name, bases, namespace), while the same method in object is passed no parameters. (Both get te extra "cls", equivalent to self as well, but this is not counted).

You can use any callable as the metaclass, even an ordinary function. It is just that it will have to take the 3 explicit parameters. Whatever this callable returns is used as the class from that point on, but if at some point you don't call type.__new__ (even indirectly), you don't have a valid class to return.

For example, one could create a simple method just in order to be able to use class bodies as dictionary declarations:

```<code>def dictclass(name, bases, namespace):
    return namespace

class mydict(metaclass=dictclass):
    a = 1
    b = 2
    c = 3

mydict["a"]
</code>```

So, one interesting fact with all that is that type is its own metaclass. (that is hardcoded in the Python implementation). But type itself also inherits from object:

```<code>In [21]: type.__class__
Out[21]: type

In [22]: type.__mro__
Out[22]: (type, object)
</code>```

And just to end this: it is possible to create classes without calling type.__new__ and objects without calling object.__new__, but not ordinarily from pure Python code, as data structures at the C-API level have to be filled for both actions. One could either do a native-code implementation of functions to do it, or hack it with ctypes.

Body:
I was trying to get some intuition about metaclass in Python. I have tried on both Python2.7 and   and Python3.5. In Python3.5 I found every class we define is of type <class 'type'> whether we explicitly inherit or not. But if not inherited from type we can't use that class as a metaclass for another class.

>>> class foo:
    pass

>>> class Metafoo(type):
    pass

>>> foo
<class '__main__.foo'>
>>> Metafoo
<class '__main__.Metafoo'>
>>> type(foo)
<class 'type'>
>>> type(Metafoo)
<class 'type'>
>>>
>>> class foocls1(metaclass=foo):
    pass

doing the above I get the following error:

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    class foocls1(metaclass=foo):
TypeError: object() takes no parameters

But that is not in the case while using Metafoo as metaclass for the new class

>>> class foocls3(metaclass=Metafoo):
    pass

>>> foocls3
<class '__main__.foocls3'>
>>> type(foocls3)
<class '__main__.Metafoo'>

Can anyone explain why this is the case that we need to explicitly inherit if we want to use a class as metaclass in other class.

Body:
"type" is the base class for all class objects in Python 3, and in Python 2 post version 2.2.  (It is just that on Python 2, you are supposed to inherit from object. Classes that do not explicitly inherit from "object" in Python 2 were called "old style classes", and kept for backward compatibility purposes, but were of little use.)

So, what happens is that inheritance: what are the superclasses of a class, and "metaclass" that is "since in Python a class is an object itself, what is the class of that object" are two different things. The classes you inherit from define the order of attribute (and method) lookup on the instances of your class, and therefore you have a common behavior.

The metaclass is rather "the class your class is built with", and although it can serve other purposes, is most used to modify the construction step of your classes itself. Search around and you will see metaclasses mostly implementing the __new__ and __init__ methods. (Although it is ok to have other methods there, but yu have to know what you are doing)

It happens that to build a class some actions are needed that are not required to build normal objects. These actions are performed on the native-code layer (C in CPython) and are not even reproducible in pure Python code, like populating the class's special method slots- the pointers to the functions that implement the __add__, __eq__ and such methods. The only class that does that in CPython is "type". So any code you want to use to build a class, i.e. as a metaclass, will have to at some point call type.__new__ method.  (Just as any thing you want to create a new object in Python will at some point call the code in  object.__new__.).

Your error happened not because Python goes checking whether you made a direct or indirect call to type.__new__ ahead of time. The error: "TypeError: object() takes no parameters" is simply due to the fact that __new__ method of the metaclass is passed 3 parameters (name, bases, namespace), while the same method in object is passed no parameters. (Both get te extra "cls", equivalent to self as well, but this is not counted).

You can use any callable as the metaclass, even an ordinary function. It is just that it will have to take the 3 explicit parameters. Whatever this callable returns is used as the class from that point on, but if at some point you don't call type.__new__ (even indirectly), you don't have a valid class to return.

For example, one could create a simple method just in order to be able to use class bodies as dictionary declarations:

def dictclass(name, bases, namespace):
    return namespace

class mydict(metaclass=dictclass):
    a = 1
    b = 2
    c = 3

mydict["a"]

So, one interesting fact with all that is that type is its own metaclass. (that is hardcoded in the Python implementation). But type itself also inherits from object:

In [21]: type.__class__
Out[21]: type

In [22]: type.__mro__
Out[22]: (type, object)

And just to end this: it is possible to create classes without calling type.__new__ and objects without calling object.__new__, but not ordinarily from pure Python code, as data structures at the C-API level have to be filled for both actions. One could either do a native-code implementation of functions to do it, or hack it with ctypes.


问:
How to stop the <audio> file from playing when i hide the
?
I am trying to make a music player using HTML, CSS and Vanilla Js. I am facing these problems:

1.How to stop the song of first artist from playing when i click on the second artist?

Also, when I start off by clicking on a particular div (Mozart, GnR, etc.), I have to click twice before the player loads up.

I am new to JavaScript, so I am not able to grasp the concept of using play() and pause() functions for my audio file (the "Promise uncaught error"), so it would be great if you explain it to me without relating to this particular concept. Also, if you have some very good documents on the Promise , kindly post the link too!

Thank you. :)

function mozart() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('mozartSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function gnr() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('gnrSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function lz() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('ledzepplinSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function metallica() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('metallicaSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function scorpion() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('scorpionSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function acdc() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('acdcSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function queen() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('queenSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}

body {
  background-color: white;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .maincontent {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
}

.container .maincontent .header {
  width: 100%;
  height: 10%;
  background-color: #8ED2C9;
}

.container .maincontent .mainSec {
  width: 100%;
  height: 90%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
}

.container .maincontent .mainSec .keys {
  width: 10%;
  height: 100%;
  background-color: #FF7A5A;
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  flex-direction: column;
}

.container .maincontent .mainSec .keys .mozart,
.gnr,
.ledzepplin,
.metallica,
.scorpion,
.acdc,
.queen {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  background-color: transparent;
  border: none;
  color: white;
  padding: 10px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-family: Roboto;
  font-size: 18px;
  cursor: pointer;
  border-radius: 5%;
  outline: none;
  transition: 0.5s all ease;
}

button: hover {
  color:
}

.container .maincontent .mainSec .contentSec {
  width: 90%;
  height: 100%;
  background-color: #FFB85F;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .maincontent .mainSec .contentSec #playArea {
  width: 50%;
  height: 60%;
  border-radius: 5px;
  background-color: #fcf4d9;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-family: Roboto;
  color: white;
  display: none;
}

.container .maincontent .mainSec .contentSec #playArea .mozartSong,
.gnrSong,
.ledzepplinSong,
.metallicaSong,
.scorpionSong,
.acdcSong,
.queenSong {
  display: none;
  position: fixed;
}</code>```

<!DOCTYPE html>

  <title>Music Player</title>
  <link rel="stylesheet" type="text/css" href="music.css">

              <button class="Mozart" onclick="mozart()">Mozart</button>

              <button class="Gnr" onclick="gnr()">GnR</button>

              <button class="LedZepplin" onclick="lz()">LedZepplin</button>

              <button class="Metallica" onclick="metallica()">Metallica</button>

              <button class="Scorpion" onclick="scorpion()">Scorpion</button>

              <button class="ACDC" onclick="acdc()">AcDc</button>

              <button class="Queen" onclick="queen()">Queen</button>

              <audio controls>
         <source src="music/mozart.wav" type="audio/wav" id="curSong">
        </audio>

              <audio controls>
         <source src="music/gnr.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/ledzepplin.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/metallica.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/scorpion.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/acdc.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/queen.wav" type="audio/wav">
        </audio>

```

`

答:
As I suggested, you have too many functions with the same functionality.

I've made it a bit easier for you. This will replace the audio tag so the previous audio will stop. Just change path to your song directory

```<code><script>
  var playSong = function(songName) {
    var audio = document.getElementById('playArea');
    var source = document.getElementById('playSong');
    source.src = 'path to your song directory' + songName + '.wav';
    audio.load(); //call this to just preload the audio without playing
    audio.play(); //call this to play the song right away
  }
</script>

<div class="keys">
  <div class="mozart">
    <div class="mozartBtn">
      <button class="Mozart" onclick="playSong('Mozart')">Mozart</button>
    </div>
  </div>
  <!--Mozart div ends-->

  <div class="gnr">
    <div class="gnrBtn">
      <button class="Gnr" onclick="playSong('GnR')">GnR</button>
    </div>
  </div>
  <!--Gnr div ends-->

  <div class="ledzepplin">
    <div class="ledzepplingBtn">
      <button class="LedZepplin" onclick="playSong('LedZepplin')">LedZepplin</button>
    </div>
  </div>
  <!--Led Zepplin div ends-->

  <div class="metallica">
    <div class="metallicaBtn">
      <button class="Metallica" onclick="playSong('Metallica')">Metallica</button>
    </div>
  </div>
  <!--Metallica div ends-->

  <div class="scorpion">
    <div class="scorpionBtn">
      <button class="Scorpion" onclick="playSong('Scorpion')">Scorpion</button>
    </div>
  </div>
  <!--Scorpion div ends-->

  <div class="acdc">
    <div class="acdcBtn">
      <button class="ACDC" onclick="playSong('AcDc')">AcDc</button>
    </div>
  </div>
  <!--ACDC div ends-->

  <div class="queen">
    <div class="queenBtn">
      <button class="Queen" onclick="playSong('Queen')">Queen</button>
    </div>
  </div>
  <!--Queen div ends-->
</div>

<audio id="playArea" controls>
  <source src="music/mozart.wav" type="audio/wav" id="playSong">
</audio>
</code>```

Title: How to stop the <audio> file from playing when i hide the <div>?

Body:
I am trying to make a music player using HTML, CSS and Vanilla Js. I am facing these problems:

1.How to stop the song of first artist from playing when i click on the second artist?

Also, when I start off by clicking on a particular div (Mozart, GnR, etc.), I have to click twice before the player loads up.

I am new to JavaScript, so I am not able to grasp the concept of using play() and pause() functions for my audio file (the "Promise uncaught error"), so it would be great if you explain it to me without relating to this particular concept. Also, if you have some very good documents on the Promise , kindly post the link too!

Thank you. :)

function mozart() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('mozartSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function gnr() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('gnrSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function lz() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('ledzepplinSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function metallica() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('metallicaSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function scorpion() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('scorpionSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function acdc() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('acdcSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

function queen() {
  var playArea = document.getElementById('playArea');
  if (playArea.style.display == 'none') {
    playArea.style.display = 'flex';
  } else {
    playArea.style.display = 'none';
  }

  var playSong = document.getElementsByClassName('queenSong')[0];
  if (playSong.style.display == 'none') {
    playSong.style.display = 'flex';
  } else {
    playSong.style.display = 'none';
  }
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}

body {
  background-color: white;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .maincontent {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
}

.container .maincontent .header {
  width: 100%;
  height: 10%;
  background-color: #8ED2C9;
}

.container .maincontent .mainSec {
  width: 100%;
  height: 90%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
}

.container .maincontent .mainSec .keys {
  width: 10%;
  height: 100%;
  background-color: #FF7A5A;
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  flex-direction: column;
}

.container .maincontent .mainSec .keys .mozart,
.gnr,
.ledzepplin,
.metallica,
.scorpion,
.acdc,
.queen {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  background-color: transparent;
  border: none;
  color: white;
  padding: 10px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-family: Roboto;
  font-size: 18px;
  cursor: pointer;
  border-radius: 5%;
  outline: none;
  transition: 0.5s all ease;
}

button: hover {
  color:
}

.container .maincontent .mainSec .contentSec {
  width: 90%;
  height: 100%;
  background-color: #FFB85F;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .maincontent .mainSec .contentSec #playArea {
  width: 50%;
  height: 60%;
  border-radius: 5px;
  background-color: #fcf4d9;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-family: Roboto;
  color: white;
  display: none;
}

.container .maincontent .mainSec .contentSec #playArea .mozartSong,
.gnrSong,
.ledzepplinSong,
.metallicaSong,
.scorpionSong,
.acdcSong,
.queenSong {
  display: none;
  position: fixed;
}

<!DOCTYPE html>

  <title>Music Player</title>
  <link rel="stylesheet" type="text/css" href="music.css">

              <button class="Mozart" onclick="mozart()">Mozart</button>

              <button class="Gnr" onclick="gnr()">GnR</button>

              <button class="LedZepplin" onclick="lz()">LedZepplin</button>

              <button class="Metallica" onclick="metallica()">Metallica</button>

              <button class="Scorpion" onclick="scorpion()">Scorpion</button>

              <button class="ACDC" onclick="acdc()">AcDc</button>

              <button class="Queen" onclick="queen()">Queen</button>

              <audio controls>
         <source src="music/mozart.wav" type="audio/wav" id="curSong">
        </audio>

              <audio controls>
         <source src="music/gnr.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/ledzepplin.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/metallica.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/scorpion.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/acdc.wav" type="audio/wav">
        </audio>

              <audio controls>
         <source src="music/queen.wav" type="audio/wav">
        </audio>

`

Body:
As I suggested, you have too many functions with the same functionality.

I've made it a bit easier for you. This will replace the audio tag so the previous audio will stop. Just change path to your song directory

<script>
  var playSong = function(songName) {
    var audio = document.getElementById('playArea');
    var source = document.getElementById('playSong');
    source.src = 'path to your song directory' + songName + '.wav';
    audio.load(); //call this to just preload the audio without playing
    audio.play(); //call this to play the song right away
  }
</script>

<div class="keys">
  <div class="mozart">
    <div class="mozartBtn">
      <button class="Mozart" onclick="playSong('Mozart')">Mozart</button>
    </div>
  </div>
  <!--Mozart div ends-->

  <div class="gnr">
    <div class="gnrBtn">
      <button class="Gnr" onclick="playSong('GnR')">GnR</button>
    </div>
  </div>
  <!--Gnr div ends-->

  <div class="ledzepplin">
    <div class="ledzepplingBtn">
      <button class="LedZepplin" onclick="playSong('LedZepplin')">LedZepplin</button>
    </div>
  </div>
  <!--Led Zepplin div ends-->

  <div class="metallica">
    <div class="metallicaBtn">
      <button class="Metallica" onclick="playSong('Metallica')">Metallica</button>
    </div>
  </div>
  <!--Metallica div ends-->

  <div class="scorpion">
    <div class="scorpionBtn">
      <button class="Scorpion" onclick="playSong('Scorpion')">Scorpion</button>
    </div>
  </div>
  <!--Scorpion div ends-->

  <div class="acdc">
    <div class="acdcBtn">
      <button class="ACDC" onclick="playSong('AcDc')">AcDc</button>
    </div>
  </div>
  <!--ACDC div ends-->

  <div class="queen">
    <div class="queenBtn">
      <button class="Queen" onclick="playSong('Queen')">Queen</button>
    </div>
  </div>
  <!--Queen div ends-->
</div>

<audio id="playArea" controls>
  <source src="music/mozart.wav" type="audio/wav" id="playSong">
</audio>


问:
How to get the refrence of list of directives used inside ng-content in the parent component in angular 2
I am trying to create a data table component for which i have created data-table component, col-header directive and col-body directive. the idea is to get the label of column header from col-header directive and the value from col-body directive and then data-table component renders the data table. But the problem is

I'am unable to get the value that I'm passing as @Input to the directive .

I'm unabe to get the refrence of the col-header directive indata-table component by using @ContentChildren

Please consider that I just started learning angular 2 and m not very good at it.
My code setup is as follows

DataTableComponent.ts

```<code>       @Component({
         selector: 'data-table',
         template: `
                  <table class="table table-bordered table-striped">
                       <thead>
                          <tr *ngFor="let header of headders ">
                            <ng-template></ng-template>
                             <td>{{header.label}}</td>
                          </tr>
                        </thead>
                       <tbody>
                           <ng-template></ng-template>
                       </tbody>
                       </table>,
           styleUrls: ['./data-table.component.css']
         })
         export class DataTableComponent implements OnInit {
         @ContentChildren(Header) headers: QueryList<Header>;
      }
     @Input() items: User[];
     ngOnInit() {
       }
    ngOnChanges(changes: SimpleChanges): void {
   console.log(changes)
    console.log(this.headers)

   }
 }
</code>```

ColHeaderComponent.ts

```<code>            @Directive({
                   selector: 'col-header',
            })
            export class Header implements OnInit {
                 constructor() {
                  }
                 @Input() label: string;
                 @Input() value: any;
                ngOnInit() {
                   console.log(this.label)
                  }
               ngOnChanges(changes: SimpleChanges): void {
                   let chng = changes['label'];
                  console.log(chng)
                   }
               }
</code>```

and I an using it as follows

```<code>     <data-table [items]="users">
          <col-header [label]="Name"></col-header>
         <col-header [label]="Password"></col-header>
         <col-body [column]="username"></col-body>
          <col-body [column]="password"></col-body>
     </data-table>
</code>```

I haven't written any thing about col-body directive because i'm yet to reach there. Please review code with patience because there may be many mistakes.

I just want simple idea on how to on how to get value to and from component using @Input and how to get refrence of child directive using @ContentChildren

Thanks

答:
Try this</p>

```<code> @ContentChildren(forwardRef(() => Header), {descendants: true}) headers: QueryList<Header>;
</code>```

Body:
I am trying to create a data table component for which i have created data-table component, col-header directive and col-body directive. the idea is to get the label of column header from col-header directive and the value from col-body directive and then data-table component renders the data table. But the problem is

I'am unable to get the value that I'm passing as @Input to the directive .

I'm unabe to get the refrence of the col-header directive indata-table component by using @ContentChildren

Please consider that I just started learning angular 2 and m not very good at it.
My code setup is as follows

DataTableComponent.ts

       @Component({
         selector: 'data-table',
         template: `

                            <ng-template></ng-template>
                             {{header.label}}

                           <ng-template></ng-template>

,
           styleUrls: ['./data-table.component.css']
         })
         export class DataTableComponent implements OnInit {
         @ContentChildren(Header) headers: QueryList;
      }
     @Input() items: User[];
     ngOnInit() {
       }
    ngOnChanges(changes: SimpleChanges): void {
   console.log(changes)
    console.log(this.headers)

   }
 }

ColHeaderComponent.ts

            @Directive({
                   selector: 'col-header',
            })
            export class Header implements OnInit {
                 constructor() {
                  }
                 @Input() label: string;
                 @Input() value: any;
                ngOnInit() {
                   console.log(this.label)
                  }
               ngOnChanges(changes: SimpleChanges): void {
                   let chng = changes['label'];
                  console.log(chng)
                   }
               }

and I an using it as follows

     <data-table [items]="users">
          <col-header [label]="Name"></col-header>
         <col-header [label]="Password"></col-header>
         <col-body [column]="username"></col-body>
          <col-body [column]="password"></col-body>
     </data-table>

I haven't written any thing about col-body directive because i'm yet to reach there. Please review code with patience because there may be many mistakes.

I just want simple idea on how to on how to get value to and from component using @Input and how to get refrence of child directive using @ContentChildren

Thanks

Body:
Try this

 @ContentChildren(forwardRef(() => Header), {descendants: true}) headers: QueryList<Header>;


问:
Javascript can't get element's value, value equals undefined
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

```<code><table>
    <tr>
        <td class="normal" id="11" value="0" onclick="alterar('11');">0</td>
        <td class="normal" id="12" value="1" onclick="alterar('12');">1</td>
        <td class="normal" id="13" value="2" onclick="alterar('13');">2</td>
        <td class="normal" id="14" value="X" onclick="alterar('14');">X</td>
        <td class="normal" id="15" value="1" onclick="alterar('15');">1</td>
        <td class="normal" id="16" value="0" onclick="alterar('16');">0</td>
        <td class="normal" id="17" value="0" onclick="alterar('17');">0</td>
    </tr>
        <td class="normal" id="21" value="0" onclick="alterar('21');">0</td>
        <td class="normal" id="22" value="1" onclick="alterar('22');">1</td>
        <td class="normal" id="23" value="2" onclick="alterar('23');">2</td>
        <td class="normal" id="24" value="X" onclick="alterar('24');">X</td>
        <td class="normal" id="25" value="1" onclick="alterar('25');">1</td>
        <td class="normal" id="26" value="0" onclick="alterar('26');">0</td>
        <td class="normal" id="27" value="0" onclick="alterar('27');">0</td>
    </tr>
        <td class="normal" id="31" value="0" onclick="alterar('31');">0</td>
        <td class="normal" id="32" value="1" onclick="alterar('32');">1</td>
        <td class="normal" id="33" value="2" onclick="alterar('33');">2</td>
        <td class="normal" id="34" value="X" onclick="alterar('34');">X</td>
        <td class="normal" id="35" value="1" onclick="alterar('35');">1</td>
        <td class="normal" id="36" value="0" onclick="alterar('36');">0</td>
        <td class="normal" id="37" value="0" onclick="alterar('37');">0</td>
    </tr>
        <td class="normal" id="41" value="0" onclick="alterar('41');">0</td>
        <td class="normal" id="42" value="1" onclick="alterar('42');">1</td>
        <td class="normal" id="43" value="2" onclick="alterar('43');">2</td>
        <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
        <td class="normal" id="45" value="1" onclick="alterar('45');">1</td>
        <td class="normal" id="46" value="0" onclick="alterar('46');">0</td>
        <td class="normal" id="47" value="0" onclick="alterar('47');">0</td>
    </tr>
</table>
</code>```

My javascript code looks like this:

```<code>function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>
</code>```

And if for example, I'd use the square "44", which value is "X", it tells me that

```<code>    <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
</code>```

I'd like to thank everyone in advance for their times.

答:
```<code>function alterar(id){

//var id = document.getElementById(obj).id;
var value = document.getElementById(id).innerText;

if(value == 'X'){
    ......
} else {
    ........
    }
}

</script>
</code>```

this will work because you are already sending id then why you need to get id again

Body:
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

My javascript code looks like this:

function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>

And if for example, I'd use the square "44", which value is "X", it tells me that

    X

I'd like to thank everyone in advance for their times.

Body:
function alterar(id){

//var id = document.getElementById(obj).id;
var value = document.getElementById(id).innerText;

if(value == 'X'){
    ......
} else {
    ........
    }
}

</script>

this will work because you are already sending id then why you need to get id again


问:
Error in initialization of custom array adapter

I am trying to make a custom listview. The list is declared as below

```<code>List<DocRow> doctors = new ArrayList<>();
</code>```

This list is then being populated.

My custom array adapter is in a separate class with its constructor declared as below.

```<code>public class DocAdapter extends ArrayAdapter<DocRow>{
    Context context;
    int resource;
    ArrayList<DocRow> doctors;
    private LayoutInflater inflater;

    public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }
</code>```

Now in my main activity, I am trying to create a new custom array adapter by passing off my list (which is a valid parameter), it isn't accepted. The code for creation and setting of adapter for linking the listview with the list is below.

```<code>DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);
</code>```

Can anyone explain what is the issue? The link for error screenshot is above. I tried searching for this specific issue, but haven't been able to find a solution that works.

答:
A parent class's reference can store subclass's object, but the reverse is not true.

Here, in the constructor of your adapter, you have ArrayList<DocRow> as your parameter type, but your doctors list is of type List<DocRow>. You, you're passing a List<> object to an ArrayList<> reference.

To solve it, either change your doctors variable type to ArrayList<>, or your constructor parameter type to List<>

Body:
I am trying to make a custom listview. The list is declared as below

List<DocRow> doctors = new ArrayList<>();

This list is then being populated.

My custom array adapter is in a separate class with its constructor declared as below.

public class DocAdapter extends ArrayAdapter<DocRow>{
    Context context;
    int resource;
    ArrayList<DocRow> doctors;
    private LayoutInflater inflater;

    public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }

Now in my main activity, I am trying to create a new custom array adapter by passing off my list (which is a valid parameter), it isn't accepted. The code for creation and setting of adapter for linking the listview with the list is below.

DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);

Can anyone explain what is the issue? The link for error screenshot is above. I tried searching for this specific issue, but haven't been able to find a solution that works.


答:
The element referred to by document.getElementById(id) is a cell of table, i.e. a  element.

Since it doesn't have a value attribute you can't get it. Which explains why you are getting undefined when you try to access it.

To access the text in the cell, you should access innerText instead of value.
Like:

```<code>var value = document.getElementById(id).innerText;
</code>```

Title: Javascript can't get element's value, value equals undefined

Body:
The element referred to by document.getElementById(id) is a cell of table, i.e. a <td> element.

Since it doesn't have a value attribute you can't get it. Which explains why you are getting undefined when you try to access it.

To access the text in the cell, you should access innerText instead of value.
Like:

var value = document.getElementById(id).innerText;


问:
Replicating a figure of an article in MATLAB
I want to replicate a figure from this article. More specifically, I want to replicate Figure number 4, which I believe is the representation of Equation 9.

So far I have come up with this code:

```<code>% implementing equation 9 and figure 4
step   = 0.01;    t = 1:step:3600;
d      = 3;     % dimension
N      = 8000;  % number of molecules
H      = 0.01;  % H = [0.01,0.1,1] is in mol/micrometer^3
H      = H*6.02214078^5; % hence I scaled the Avogadro's number (right or wrong?)
D      = 10;    % diffusion coefficient in micrometer^2/sec

u(1)   =  1./(1.^(d/2)); % inner function in equation 9; first pulse

for i = 2:numel(t)/1000
    u(i)     =  u(i-1)+(1./(i.^(d/2))); %  u-> the pulse number
    lmda(i)  = (1/(4*pi*D))*((N/(H)).*sum(u)).^(2/d);
end

figure;plot(lmda)
</code>```

But I am not able to replicate it.

Equation 9

For details on the parameters, refer to the above code. The authors did mention that the summation in equation 9 is a Reimann Zeta series. Wonder if that has anything to do with the result?

Figure 4, which I am trying to replicate:

Could someone kindly tell me the mistake I am making?

P.s: This is not a homework.

答:
Problem 1: You think you are scaling by Avogadro's number on this line

```<code>H = H*6.02214078^5;
</code>```

In fact, you're scaling by approximately 7920=6.022^5. If you wanted to scale by the Avogadro number then you should do:

```<code>H = H * 6.02214078e23 % = 6.02214078 * 10^23 : the Avogadro number
</code>```

Problem 2: You aren't plotting against t, you're plotting against the sample number which doesn't really make sense (unless your t happened to be in integer seconds). Remove the /1000 from your loop

```<code>for i = 2:numel(t)
    % ...
end
% Then plot
plot(t, lmda)
</code>```

At this stage we can see something is really wrong. Now that we're scaling by the correct Avo number, the orders of magnitude are way out. I suggest that you trust the H in figure 4 and the H in equation 9 are the same H, it would be very confusing if the author intended anything different!

On that basis, I would suggest you are using the wrong D, N, or time between pulses. I've set up the pulse timing a bit clearer in my code below. I've also streamlined your loop somewhat using vectorisation, and removed the H scaling.

If you tweak it so dtPulses=100 as well as D=100, then the plots are almost identical. You perhaps need to consider how these two numbers affect the result...

```<code>% implementing equation 9 and figure 4
d = 3;     % dimension
N = 8000;  % number of molecules
D = 100;   % diffusion coefficient in micrometer^2/sec

dtPulses = 10; % Seconds between pulses
tPulses = 1:dtPulses:3600; % Time array to plot against
nt = numel(tPulses);
i = 1:nt;  % pulse numbers
u = 1 ./ (i.^(d/2)); % inner function in equation 9: individual pulse
for k = 2:nt % Running sum
    u(k) = u(k-1)+u(k);
end
% Now plot for different H (mol/micrometer^3)
H = [0.01, 0.1, 1];
figure; hold on; linestyles = {':k', '--k', '-k'};
for nH = 1:3
    lmda = ((1/(4*pi*D))*(N/H(nH)).*u).^(2/d);
    plot(tPulses, lmda, linestyles{nH}, 'linewidth', 2)
end
</code>```

Body:
I want to replicate a figure from this article. More specifically, I want to replicate Figure number 4, which I believe is the representation of Equation 9.

So far I have come up with this code:

% implementing equation 9 and figure 4
step   = 0.01;    t = 1:step:3600;
d      = 3;     % dimension
N      = 8000;  % number of molecules
H      = 0.01;  % H = [0.01,0.1,1] is in mol/micrometer^3
H      = H*6.02214078^5; % hence I scaled the Avogadro's number (right or wrong?)
D      = 10;    % diffusion coefficient in micrometer^2/sec

u(1)   =  1./(1.^(d/2)); % inner function in equation 9; first pulse

for i = 2:numel(t)/1000
    u(i)     =  u(i-1)+(1./(i.^(d/2))); %  u-> the pulse number
    lmda(i)  = (1/(4*pi*D))*((N/(H)).*sum(u)).^(2/d);
end

figure;plot(lmda)

But I am not able to replicate it.

Equation 9

For details on the parameters, refer to the above code. The authors did mention that the summation in equation 9 is a Reimann Zeta series. Wonder if that has anything to do with the result?

Figure 4, which I am trying to replicate:

Could someone kindly tell me the mistake I am making?

P.s: This is not a homework.

Body:
Problem 1: You think you are scaling by Avogadro's number on this line

H = H*6.02214078^5;

In fact, you're scaling by approximately 7920=6.022^5. If you wanted to scale by the Avogadro number then you should do:

H = H * 6.02214078e23 % = 6.02214078 * 10^23 : the Avogadro number

Problem 2: You aren't plotting against t, you're plotting against the sample number which doesn't really make sense (unless your t happened to be in integer seconds). Remove the /1000 from your loop

for i = 2:numel(t)
    % ...
end
% Then plot
plot(t, lmda)

At this stage we can see something is really wrong. Now that we're scaling by the correct Avo number, the orders of magnitude are way out. I suggest that you trust the H in figure 4 and the H in equation 9 are the same H, it would be very confusing if the author intended anything different!

On that basis, I would suggest you are using the wrong D, N, or time between pulses. I've set up the pulse timing a bit clearer in my code below. I've also streamlined your loop somewhat using vectorisation, and removed the H scaling.

If you tweak it so dtPulses=100 as well as D=100, then the plots are almost identical. You perhaps need to consider how these two numbers affect the result...

% implementing equation 9 and figure 4
d = 3;     % dimension
N = 8000;  % number of molecules
D = 100;   % diffusion coefficient in micrometer^2/sec

dtPulses = 10; % Seconds between pulses
tPulses = 1:dtPulses:3600; % Time array to plot against
nt = numel(tPulses);
i = 1:nt;  % pulse numbers
u = 1 ./ (i.^(d/2)); % inner function in equation 9: individual pulse
for k = 2:nt % Running sum
    u(k) = u(k-1)+u(k);
end
% Now plot for different H (mol/micrometer^3)
H = [0.01, 0.1, 1];
figure; hold on; linestyles = {':k', '--k', '-k'};
for nH = 1:3
    lmda = ((1/(4*pi*D))*(N/H(nH)).*u).^(2/d);
    plot(tPulses, lmda, linestyles{nH}, 'linewidth', 2)
end


问:
android studio, 2 projects with same installer file icon
I'm working on two projects, all two have different icon for .apk installer and app (same file for apk and link), but now, one app show the same .apk icon of the other file.
Eg. app 1 have icon x, app 2 have icon y. After i create new project for the app 2, app 1 icon change in y. How can i solve it?</p>

答: Try to "Clean project" and "Rebuild project" on "Build" menu.</p>


问:
S3 move files year/month wise
I have a bucket (s3://Bucket1) and there are millions of files in that with format like below:

```<code>s3://Bucket1/yyyy-mm-dd/
</code>```

I want to move these files like

```<code>s3://Bucket1/year/mm
</code>```

Any help, script, method will be really helpful.

I have tried aws s3 cp s3://Bucket1/ s3://Bucket1/ --include "2017-01-01*" but this is not working good and plus I have to put extra stuff to delete files.

答:
The basic steps are:

Get a list of objects

Copy the objects to the new name

Delete the old objects

Get a list of objects

Given that you have millions of files, the best way to start is to use Amazon S3 Inventory to obtain a CSV file of all the objects.

Copy the objects to the new name

Then, write a script that reads the CSV file and issues a copy() command to copy the file to the new location. This could be written in any language that has an AWS SDK (eg Python).

Delete the old objects

Rather than individually deleting the objects, use S3 object lifecycle management to delete the old files. The benefits of using this method are:

There is no charge for the delete (whereas issuing millions of delete commands would involve a charge)

It can be done after the files have been copied, providing a chance to verify that all the files have been correctly copied (by checking the next S3 inventory output)

You could use the AWS CLI to issue a aws s3 mv command, which will combine the copy and delete -- effectively providing a rename function. However, shell scripts aren't that easy and if things fail half-way the files will be in a mixed state. That's why I prefer the "copy all objects, and only then delete" method more.

Title: S3 move files year/month wise

Body:
I have a bucket (s3://Bucket1) and there are millions of files in that with format like below:

s3://Bucket1/yyyy-mm-dd/

I want to move these files like

s3://Bucket1/year/mm

Any help, script, method will be really helpful.

I have tried aws s3 cp s3://Bucket1/ s3://Bucket1/ --include "2017-01-01*" but this is not working good and plus I have to put extra stuff to delete files.


问:
Summing one ArrayList of Integers to another ArrayList of Integers, gives error: variable expected
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

```<code>likes = new ArrayList<Integer>();
</code>```

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

```<code>likes = new ArrayList<>(Collections.nCopies(6, 0));
</code>```

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

```<code>public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}
</code>```

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

答:
you are trying to assign value to a method, try something like :  </p>

```<code>    int oldLikesCount = this.likes.get(i);
    this.likes.set(i,oldLikesCount +likes.get(i));
</code>```

Body:
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

likes = new ArrayList<Integer>();

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

likes = new ArrayList<>(Collections.nCopies(6, 0));

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

Body:
you are trying to assign value to a method, try something like :

    int oldLikesCount = this.likes.get(i);
    this.likes.set(i,oldLikesCount +likes.get(i));


问:
Replace everything not in the String
I know when I use .replace I can replace a specified String for another string. For example:

```<code>String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);
</code>```

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

答:
There is no such library. You can do this like:</p>

```<code> String replaceOthers(String required, String fullString) {
    String result = fullString;
    try (Scanner scanner = new Scanner(fullString)) {
        while (scanner.hasNext()) {
            String current = scanner.next();
            if (!current.equals(required)) {
                result = result.replace(current, "");
            }
        }
        return result;
    }
}
</code>```

Title: Replace everything not in the String

Body:
I know when I use .replace I can replace a specified String for another string. For example:

String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

Body:
There is no such library. You can do this like:

 String replaceOthers(String required, String fullString) {
    String result = fullString;
    try (Scanner scanner = new Scanner(fullString)) {
        while (scanner.hasNext()) {
            String current = scanner.next();
            if (!current.equals(required)) {
                result = result.replace(current, "");
            }
        }
        return result;
    }
}


问:
Correctly storing in data structure in Python
```<code>alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10
</code>```

These are some of the keywords and their 'values' that I need to store in a
data structure, preferably a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

```<code>line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()
</code>```

And I tried to convert it to a list form by doing this:

```<code>   list=[line]
</code>```

However, when I print the list, I get this:

```<code>   ['amazed,10']
   ['amazing,10']
   ['bad,1']
   ['best,10']
   ['better,7']
   ['excellent,10']
</code>```

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking for a better way to store the words and its 'value'

Thanks in advance!

答:
A dictionnary is what you need here:
You could do something like:

```<code>line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip().split(',')
   out[line[0]] = line[1]
</code>```

out will look like

```<code>{ 'amazed' : 10, 'amazing': 10, 'bad':1 ...}
</code>```

and the values can be accessed out['amazed'] will return 10

Body:
alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10

These are some of the keywords and their 'values' that I need to store in a
data structure, preferably a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()

And I tried to convert it to a list form by doing this:

   list=[line]

However, when I print the list, I get this:

   ['amazed,10']
   ['amazing,10']
   ['bad,1']
   ['best,10']
   ['better,7']
   ['excellent,10']

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking for a better way to store the words and its 'value'

Thanks in advance!

Body:
A dictionnary is what you need here:
You could do something like:

line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip().split(',')
   out[line[0]] = line[1]

out will look like

{ 'amazed' : 10, 'amazing': 10, 'bad':1 ...}

and the values can be accessed out['amazed'] will return 10


问:
Server load Database vs. File Operation
I am trying to figure out which bears a heavier load on a system:

A database operation

OR a File operation (AKA reading an XML file)

Thanks in advance!

答:
Usually file operations are slower than DB operations.

If you want to store a data collection in an XML file (ie. an XML database) I would unrecommend it, strongly. DBMSs implement lots of performance optimizations via indexes and caches: most of DB data is held in memory.

If you want to write large payloads to DB columns, it's not more efficient than having a column that points to a file and store the raw data inside the file.

Title: Server load Database vs. File Operation