问:
Show/hide optgroup based on checkboxes
So basically I want a solution like in this question here but with the "master" being <checkbox> not <select>.

So for example I have four checkboxes and a select with four optgroups. I want to show only these optgroups which are selected with the checkboxes.

I am very new to javascript and can't think of a solution. I tried adapting the solution of the question I posted but without success. I also couldn't find the exact same problem on the internet.

Thanks for your help.

Edit:

Here is the code (though redundant imo):

```<code><input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>

<select name="services">
    <optgroup label="Application">                      <!-- Shown -->
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">           <!-- Hidden -->
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">                         <!-- Hidden -->
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">                         <!-- Shown -->
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>
</code>```

And of course it should adjust itself based on changed selections.

And here the Javascript (ctrl + c, ctrl + v from other question):

```<code>$(document).ready(function () {
    $("checkbox[name='serviceType']:eq(0)").on("change",
        function () {
            console.log(this.value);
            $("select[name='services']:eq(0)")
                .find("optgroup,option")
                .hide()
                .filter("[label='" + this.value + "'],[label = '" + this.value + "'] > *")
                .show();
        });
});
</code>```

答:
The simplest solution, using jQuery, I can think of is the following:

```<code>// selecting all <input> elements whose 'type' attribute
// is equal to 'checkbox,' binding an event-listener to
// the 'change' event on those elements which executes the
// supplied anonymous function:
$('input[type=checkbox]').on('change', function() {

  // here we first find the <label> element(s) which are
  // attached (via either the 'for' attribute-value or by
  // nesting the <input> within the <label> element); we
  // check that this labels property is true/truthy using
  // a ternary operator. If there are <label> elements
  // available via the labels property, we select the first
  // otherwise we select the nextElementSibling of the
  // <input> (this approach does require a predictable HTML)
  // and will require change should the structure change:
  let label = this.labels.length ? this.labels[0] : this.nextElementSibling;

  // here select the <optgroup> element(s) whose 'label'
  // attribute-value is equal to the text of the <label>
  // element's textContent property, with leading and
  // trailing white-space removed (using String.prototype.trim():
  $('optgroup[label="' + label.textContent.trim() + '"]')

    // we then toggle the display of the retrieved elements,
    // using the supplied switch (this.checked), which will
    // show elements if 'this.checked' evaluates to true, and
    // hide them if it evaluates to false:
    .toggle(this.checked);

// here we trigger the 'change' event on the elements matching
// the initial selector, in order to hide, or show, the relevant
// <optgroup> elements on page-load:
}).change();
</code>```

$('input[type=checkbox]').on('change', function() {
  let label = this.labels.length ? this.labels[0] : this.nextElementSibling;
  $('optgroup[label="' + label.textContent.trim() + '"]').toggle(this.checked);
}).change();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label::after {
  content: '';
  display: block;
}</code>```

<input type="checkbox" id="1" name="serviceType" checked="checked" />
Application
<input type="checkbox" id="2" name="serviceType" />
Infrastructure Service
<input type="checkbox" id="3" name="serviceType" />
Platform
<input type="checkbox" id="4" name="serviceType" checked="checked" />
Software

<select name="services">
  <optgroup label="Application">

    <option value="Office">Office</option>
    <option value="SAP">SAP</option>
  </optgroup>
  <optgroup label="Infrastructure Service">

    <option value="Router">Router</option>
    <option value="Switch">Switch</option>
  </optgroup>
  <optgroup label="Platform">

    <option value="Server">Server</option>
    <option value="Client">Client</option>
  </optgroup>
  <optgroup label="Software">

    <option value="Word">Word</option>
    <option value="Excel">Excel</option>
  </optgroup>
</select>```
</div>
</div>
</p>

<p>JS Fiddle demo.</p>

<p>Alternatively, the above could be quite easily rewritten to use the DOM API or 'plain' JavaScript:</p>

```// here we create a named function to handle the
// events:
function toggleIfChecked() {

  // we cache the 'this' element node, supplied from
  // EventTarget.addEventListener():
  let el = this,

    // as before we retrieve the relevant  element,
    // and, as before, it's equally fragile should the
    // HTML structure change:
    label = el.labels.length ? el.labels[0] : el.nextElementSibling,

    // we retrieve the relevant textContent from the ,
    // and - again - remove leading/trailing white-space:
    text = label.textContent.trim(),

    // here we hard-code the relevant <select> element within
    // which to search, retrieving it via
    // document.querySelector() which retrieves the first
    // element matching the supplied selector or, if no
    // such element is found, returns null:
    select = document.querySelector('select[name=services]');

  // we use Array.from() to convert the Array-like NodeList
  // returned from wrapped call to document.querySelectorAll()
  // into an Array, which allows us to use Array methods on
  // the returned Array of element nodes:
  Array.from(

    // as above we retrieve all <optgroup> elements whose
    // 'label' attribute is equal to the textContent retrieved
    // earlier:
    select.querySelectorAll('optgroup[label="' + text + '"]')

  // using Array.prototype.forEach() to iterate over the
  // Array of nodes, using arrow function syntax:
  ).forEach(

    // 'optgroup' is the current element node of the Array of
    // elements over which we're iterating; the ternary operator
    // returns 'block' (if the changed-<input> element is checked)
    // or 'none' (if the changed-<input> element is not checked);
    // this allows us to set the display property of the
    // <optgroup>'s 'style' CSSStyleDeclarationObject according
    // to the un/checked state of the changed-<input> element:
    optgroup => optgroup.style.display = el.checked ? 'block' : 'none'
  );
}

// creating an Event Object to refer to the 'change' event:
let changeEvent = new Event('change');

// using Array.from() again, to convert the nodeList
// from document.querySelectorAll() into an Array of
// nodes in order to use Array.prototype.forEach():
Array.from(

  // selecting all <input> elements whose type is set
  // to 'checkbox':
  document.querySelectorAll('input[type=checkbox]')

// iterating over the Array:
).forEach(

  // 'input' is the current <input> element of the Array of
  // <input> elements within the Array over which we're
  // iterating:
  input => {

    // because we're performing multiple actions in this
    // Arrow function expression, we're wrapping those
    // actions - or statements - in a block-scope;
    // first: we bind the toggleIfChecked() (note the lack
    // of parentheses in the call to addEventListener()),
    // to handle the 'change' event on the <input> element:
    input.addEventListener('change', toggleIfChecked);

    // then we dispatch the changeEvent Event object
    // in order to trigger that event-listener; causing
    // the function to be fired on page-load, and setting
    // the visibility of the relevant <optgroup> to the
    // appropriate state (shown or hidden):
    input.dispatchEvent(changeEvent);
  }
);
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleIfChecked() {
  let el = this,
    label = el.labels.length ? el.labels[0] : el.nextElementSibling,
    text = label.textContent.trim(),
    select = document.querySelector('select[name=services]');

  Array.from(
    select.querySelectorAll('optgroup[label="' + text + '"]')
  ).forEach(
    optgroup => optgroup.style.display = el.checked ? 'block' : 'none'
  );
}

let changeEvent = new Event('change');

Array.from(
  document.querySelectorAll('input[type=checkbox]')
).forEach(
  input => {
    input.addEventListener('change', toggleIfChecked);
    input.dispatchEvent(changeEvent);
  }
);</code>```

label::after {
  content: '';
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>

<select name="services">
  <optgroup label="Application">
    <!-- Shown -->
    <option value="Office">Office</option>
    <option value="SAP">SAP</option>
  </optgroup>
  <optgroup label="Infrastructure Service">
    <!-- Hidden -->
    <option value="Router">Router</option>
    <option value="Switch">Switch</option>
  </optgroup>
  <optgroup label="Platform">
    <!-- Hidden -->
    <option value="Server">Server</option>
    <option value="Client">Client</option>
  </optgroup>
  <optgroup label="Software">
    <!-- Shown -->
    <option value="Word">Word</option>
    <option value="Excel">Excel</option>
  </optgroup>
</select></code>```

JS Fiddle demo.

References:

CSS:

Attribute-selectors selector.

JavaScript:

Array.from().

Array.forEach().

Arrow functions.

Conditional ('ternary') Operator.

document.querySelector().

document.querySelectorAll().

Event().

EventTarget.addEventListener().

EventTarget.dispatchEvent().

HTMLElement.style.

HTMLInputElement.labels property.

Node.textContent.

NodeList.length.

NonDocumentTypeChildNode.nextElementSibling.

String.prototype.trim().

jQuery:

change().

on().

toggle().

Title: Show/hide optgroup based on checkboxes

Body:
So basically I want a solution like in this question here but with the "master" being <checkbox> not <select>.

So for example I have four checkboxes and a select with four optgroups. I want to show only these optgroups which are selected with the checkboxes.

I am very new to javascript and can't think of a solution. I tried adapting the solution of the question I posted but without success. I also couldn't find the exact same problem on the internet.

Thanks for your help.

Edit:

Here is the code (though redundant imo):

<input type="checkbox" id="1" name="serviceType" checked="checked" />
Application
<input type="checkbox" id="2" name="serviceType" />
Infrastructure Service
<input type="checkbox" id="3" name="serviceType" />
Platform
<input type="checkbox" id="4" name="serviceType" checked="checked" />
Software

<select name="services">
    <optgroup label="Application">
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>

And of course it should adjust itself based on changed selections.

And here the Javascript (ctrl + c, ctrl + v from other question):

$(document).ready(function () {
    $("checkbox[name='serviceType']:eq(0)").on("change",
        function () {
            console.log(this.value);
            $("select[name='services']:eq(0)")
                .find("optgroup,option")
                .hide()
                .filter("[label='" + this.value + "'],[label = '" + this.value + "'] > *")
                .show();
        });
});

Body:
The simplest solution, using jQuery, I can think of is the following:

// selecting all <input> elements whose 'type' attribute
// is equal to 'checkbox,' binding an event-listener to
// the 'change' event on those elements which executes the
// supplied anonymous function:
$('input[type=checkbox]').on('change', function() {

  // here we first find the <label> element(s) which are
  // attached (via either the 'for' attribute-value or by
  // nesting the <input> within the <label> element); we
  // check that this labels property is true/truthy using
  // a ternary operator. If there are <label> elements
  // available via the labels property, we select the first
  // otherwise we select the nextElementSibling of the
  // <input> (this approach does require a predictable HTML)
  // and will require change should the structure change:
  let label = this.labels.length ? this.labels[0] : this.nextElementSibling;

  // here select the <optgroup> element(s) whose 'label'
  // attribute-value is equal to the text of the <label>
  // element's textContent property, with leading and
  // trailing white-space removed (using String.prototype.trim():
  $('optgroup[label="' + label.textContent.trim() + '"]')

    // we then toggle the display of the retrieved elements,
    // using the supplied switch (this.checked), which will
    // show elements if 'this.checked' evaluates to true, and
    // hide them if it evaluates to false:
    .toggle(this.checked);

// here we trigger the 'change' event on the elements matching
// the initial selector, in order to hide, or show, the relevant
// <optgroup> elements on page-load:
}).change();

$('input[type=checkbox]').on('change', function() {
  let label = this.labels.length ? this.labels[0] : this.nextElementSibling;
  $('optgroup[label="' + label.textContent.trim() + '"]').toggle(this.checked);
}).change();

label::after {
  content: '';
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>

<select name="services">
  <optgroup label="Application">
    <!-- Shown -->
    <option value="Office">Office</option>
    <option value="SAP">SAP</option>
  </optgroup>
  <optgroup label="Infrastructure Service">
    <!-- Hidden -->
    <option value="Router">Router</option>
    <option value="Switch">Switch</option>
  </optgroup>
  <optgroup label="Platform">
    <!-- Hidden -->
    <option value="Server">Server</option>
    <option value="Client">Client</option>
  </optgroup>
  <optgroup label="Software">
    <!-- Shown -->
    <option value="Word">Word</option>
    <option value="Excel">Excel</option>
  </optgroup>
</select>

JS Fiddle demo.

Alternatively, the above could be quite easily rewritten to use the DOM API or 'plain' JavaScript:

// here we create a named function to handle the
// events:
function toggleIfChecked() {

  // we cache the 'this' element node, supplied from
  // EventTarget.addEventListener():
  let el = this,

    // as before we retrieve the relevant <label> element,
    // and, as before, it's equally fragile should the
    // HTML structure change:
    label = el.labels.length ? el.labels[0] : el.nextElementSibling,

    // we retrieve the relevant textContent from the <label>,
    // and - again - remove leading/trailing white-space:
    text = label.textContent.trim(),

    // here we hard-code the relevant <select> element within
    // which to search, retrieving it via
    // document.querySelector() which retrieves the first
    // element matching the supplied selector or, if no
    // such element is found, returns null:
    select = document.querySelector('select[name=services]');

  // we use Array.from() to convert the Array-like NodeList
  // returned from wrapped call to document.querySelectorAll()
  // into an Array, which allows us to use Array methods on
  // the returned Array of element nodes:
  Array.from(

    // as above we retrieve all <optgroup> elements whose
    // 'label' attribute is equal to the textContent retrieved
    // earlier:
    select.querySelectorAll('optgroup[label="' + text + '"]')

  // using Array.prototype.forEach() to iterate over the
  // Array of nodes, using arrow function syntax:
  ).forEach(

    // 'optgroup' is the current element node of the Array of
    // elements over which we're iterating; the ternary operator
    // returns 'block' (if the changed-<input> element is checked)
    // or 'none' (if the changed-<input> element is not checked);
    // this allows us to set the display property of the
    // <optgroup>'s 'style' CSSStyleDeclarationObject according
    // to the un/checked state of the changed-<input> element:
    optgroup => optgroup.style.display = el.checked ? 'block' : 'none'
  );
}

// creating an Event Object to refer to the 'change' event:
let changeEvent = new Event('change');

// using Array.from() again, to convert the nodeList
// from document.querySelectorAll() into an Array of
// nodes in order to use Array.prototype.forEach():
Array.from(

  // selecting all <input> elements whose type is set
  // to 'checkbox':
  document.querySelectorAll('input[type=checkbox]')

// iterating over the Array:
).forEach(

  // 'input' is the current <input> element of the Array of
  // <input> elements within the Array over which we're
  // iterating:
  input => {

    // because we're performing multiple actions in this
    // Arrow function expression, we're wrapping those
    // actions - or statements - in a block-scope;
    // first: we bind the toggleIfChecked() (note the lack
    // of parentheses in the call to addEventListener()),
    // to handle the 'change' event on the <input> element:
    input.addEventListener('change', toggleIfChecked);

    // then we dispatch the changeEvent Event object
    // in order to trigger that event-listener; causing
    // the function to be fired on page-load, and setting
    // the visibility of the relevant <optgroup> to the
    // appropriate state (shown or hidden):
    input.dispatchEvent(changeEvent);
  }
);

function toggleIfChecked() {
  let el = this,
    label = el.labels.length ? el.labels[0] : el.nextElementSibling,
    text = label.textContent.trim(),
    select = document.querySelector('select[name=services]');

  Array.from(
    select.querySelectorAll('optgroup[label="' + text + '"]')
  ).forEach(
    optgroup => optgroup.style.display = el.checked ? 'block' : 'none'
  );
}

let changeEvent = new Event('change');

Array.from(
  document.querySelectorAll('input[type=checkbox]')
).forEach(
  input => {
    input.addEventListener('change', toggleIfChecked);
    input.dispatchEvent(changeEvent);
  }
);

label::after {
  content: '';
  display: block;
}

<input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>

<select name="services">
  <optgroup label="Application">
    <!-- Shown -->
    <option value="Office">Office</option>
    <option value="SAP">SAP</option>
  </optgroup>
  <optgroup label="Infrastructure Service">
    <!-- Hidden -->
    <option value="Router">Router</option>
    <option value="Switch">Switch</option>
  </optgroup>
  <optgroup label="Platform">
    <!-- Hidden -->
    <option value="Server">Server</option>
    <option value="Client">Client</option>
  </optgroup>
  <optgroup label="Software">
    <!-- Shown -->
    <option value="Word">Word</option>
    <option value="Excel">Excel</option>
  </optgroup>
</select>

JS Fiddle demo.

References:

CSS:

Attribute-selectors selector.

JavaScript:

Array.from().

Array.forEach().

Arrow functions.

Conditional ('ternary') Operator.

document.querySelector().

document.querySelectorAll().

Event().

EventTarget.addEventListener().

EventTarget.dispatchEvent().

HTMLElement.style.

HTMLInputElement.labels property.

Node.textContent.

NodeList.length.

NonDocumentTypeChildNode.nextElementSibling.

String.prototype.trim().

jQuery:

change().

on().

toggle().


来源: stackexchange

问:
Difference between Lock.withLock and synchronized in Kotlin
Is there a difference (other than preference) between

```<code>someLock.withLock {
    sharedResource.operation()
}
</code>```

and

```<code>synchronized(someLock) {
    sharedResource.operation()
}
</code>```

in Kotlin?

答:
The extension withLock works on Lock instances like ReentrantLock, whereas synchronized may be used with any object.

```<code>val lock = ReentrantLock()
fun syncWithLockTest(): Int = lock.withLock { 123 }

val anyLock = Any()
fun syncWithArbitraryObjTest(): Int = synchronized(anyLock) { 123 }

</code>```

Note that synchronized is a function in Kotlin which returns a value. This makes it more powerful than Java's synchronized keyword.
Technically it doesn’t make a difference on which object you lock, as long as you use the same object for all relevant code blocks that need be synchronized with each other and don't expose it publicly.

ContentLicense: CC BY-SA 3.0

Body:
Is there a difference (other than preference) between

someLock.withLock {
    sharedResource.operation()
}

and

synchronized(someLock) {
    sharedResource.operation()
}

in Kotlin?

Body:
The extension withLock works on Lock instances like ReentrantLock, whereas synchronized may be used with any object.

val lock = ReentrantLock()
fun syncWithLockTest(): Int = lock.withLock { 123 }

val anyLock = Any()
fun syncWithArbitraryObjTest(): Int = synchronized(anyLock) { 123 }

Note that synchronized is a function in Kotlin which returns a value. This makes it more powerful than Java's synchronized keyword.
Technically it doesn’t make a difference on which object you lock, as long as you use the same object for all relevant code blocks that need be synchronized with each other and don't expose it publicly.

ContentLicense: CC BY-SA 4.0


问:
How to add text reference to other listings?

I want to add a comment into the columns when the listings has it. Could anyone please help me?

```<code><dl class="listings">
<dt>Apple</dt>
<dd>Delicious</dd>
<dt>Green Apple</dt>
<dd>Love it!</dd>
</dl>
<table>
<tr>
<td>Apple, Orange, Banana</td>
<td>Green Apple, Lemon</td>
</tr>
</table>

$(document).ready(function () {
        $(".listings").find('dt').each(function() {
            var title = $(this).html();
            var comment = $(this).next().html();
            $('table td').filter(":contains('"+title+"')").each(function(){
                $(this).html('<span>'+title+'</span><span>'+comment+'</span>');
            });
        });
    });
</code>```

Expected

```<code>Apple Delicious, Orange, Banana
Green Apple Love it!, Lemon
</code>```

Result

```<code>Apple Delicious
Apple Delicious
</code>```

答:
Here is my take on it- You can use split to split each word with a comma as the deliminator.

Then use indexOf to look through the array and see if you have a match from your title and the td word

if so then add your html and put it back the way it was with join(",")

$(document).ready(function() {
  $(".listings").find('dt').each(function() {
    var title = $(this).html();
    var comment = $(this).next().html();
    $('table td').each(function() {
      // split the td text into an array using , a the deliminator
      var split = $(this).text().trim().split(",");
      // indexOf will let us know if the title is in this array
      var index = split.indexOf(title);
      // if its in the array then add the comment
      if (index > -1) {
        // we have a match in this
        split[index] = '' + title + ' ' + comment + ''
        // put the array back to the way it was with a ,
        $(this).html(split.join(", "));
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
  <dt>Apple</dt>
  <dd>Delicious</dd>
  <dt>Green Apple</dt>
  <dd>Love it!</dd>
</dl>
<table>
  <tr>
    <td>Apple, Orange, Banana</td>
  </tr>
  <tr>
    <td>Green Apple, Lemon</td>
  </tr>
</table></code>```

Body:
I want to add a comment into the columns when the listings has it. Could anyone please help me?

Apple

Delicious

Green Apple

Love it!

Apple, Orange, Banana
Green Apple, Lemon

$(document).ready(function () {
        $(".listings").find('dt').each(function() {
            var title = $(this).html();
            var comment = $(this).next().html();
            $('table td').filter(":contains('"+title+"')").each(function(){
                $(this).html(''+title+''+comment+'');
            });
        });
    });

Expected

Apple Delicious, Orange, Banana
Green Apple Love it!, Lemon

Result

Apple Delicious
Apple Delicious

Body:
Here is my take on it- You can use split to split each<td> word with a comma as the deliminator.

Then use indexOf to look through the array and see if you have a match from your title and the td word

if so then add your html and put it back the way it was with join(",")

$(document).ready(function() {
  $(".listings").find('dt').each(function() {
    var title = $(this).html();
    var comment = $(this).next().html();
    $('table td').each(function() {
      // split the td text into an array using , a the deliminator
      var split = $(this).text().trim().split(",");
      // indexOf will let us know if the title is in this array
      var index = split.indexOf(title);
      // if its in the array then add the comment
      if (index > -1) {
        // we have a match in this <td>
        split[index] = '<span>' + title + '</span> <span>' + comment + '</span>'
        // put the array back to the way it was with a ,
        $(this).html(split.join(", "));
      }
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
  <dt>Apple</dt>
  <dd>Delicious</dd>
  <dt>Green Apple</dt>
  <dd>Love it!</dd>
</dl>
<table>
  <tr>
    <td>Apple, Orange, Banana</td>
  </tr>
  <tr>
    <td>Green Apple, Lemon</td>
  </tr>
</table>


问:
How to cleanly pass down keyword args?
When writing functions that call other sub-functions I often want to allow the caller to pass in arbitrary keyword arguments for those subfunctions. However, the current way that I implement this is messy and I am looking for a more clear, concise, and maintainable way.

Below is an example of how I currently implement this:

```<code>def foo(a, print_line="Hello World!"):
    print a, print_line

def bar(a, number=2, multiple=4):
    print a, number * multiple

def baz(a, **kwargs):
    if "print_line" in kwargs:
        foo(a, print_line=kwargs["print_line"])
    else:
        foo(a)

    bar_kwargs = dict()
    if "number" in kwargs:
        bar_kwargs["number"] = kwargs["number"]
    if "multiple" in kwargs:
        bar_kwargs["multiple"] = kwargs["multiple"]
    bar(a, **bar_kwargs)
</code>```

This method is error-prone and I need to implement every kwarg that I want to express. I can sometimes get away with foo(a, print_line=kwargs.get("print_line", False) but I would like to preserve the default argument of the kwarg.

答:
Instead of processing the keyword arguments for each sub-function in the main function, let the sub-functions handle that logic themselves. This allows you to clearly separate each concern in your program.

```<code>def foo(a, **kwargs):
    print a, kwargs.get('print_line', 'Hello World')

def bar(a, number=2, multiple=4):
    print a, kwargs.get('number', 2) * kwargs.get('multiple', 4)

def baz(a, **kwargs):
    foo(a, **kwargs)
    bar(a, **kwargs)
</code>```

You would then call baz like so, only having to pass in specific keyword argument values if you want the keyword argument to have different value than the default:

```<code>baz('a', print_line='Hello World', number=2, multiple=4)
# or...
baz('a', number=2, multiple=4)
# or...
baz('a', print_line='Hello World')
# or...
baz('a')
</code>```

Title: How to cleanly pass down keyword args?

Body:
When writing functions that call other sub-functions I often want to allow the caller to pass in arbitrary keyword arguments for those subfunctions. However, the current way that I implement this is messy and I am looking for a more clear, concise, and maintainable way.

Below is an example of how I currently implement this:

def foo(a, print_line="Hello World!"):
    print a, print_line

def bar(a, number=2, multiple=4):
    print a, number * multiple

def baz(a, **kwargs):
    if "print_line" in kwargs:
        foo(a, print_line=kwargs["print_line"])
    else:
        foo(a)

    bar_kwargs = dict()
    if "number" in kwargs:
        bar_kwargs["number"] = kwargs["number"]
    if "multiple" in kwargs:
        bar_kwargs["multiple"] = kwargs["multiple"]
    bar(a, **bar_kwargs)

This method is error-prone and I need to implement every kwarg that I want to express. I can sometimes get away with foo(a, print_line=kwargs.get("print_line", False) but I would like to preserve the default argument of the kwarg.

Body:
Instead of processing the keyword arguments for each sub-function in the main function, let the sub-functions handle that logic themselves. This allows you to clearly separate each concern in your program.

def foo(a, **kwargs):
    print a, kwargs.get('print_line', 'Hello World')

def bar(a, number=2, multiple=4):
    print a, kwargs.get('number', 2) * kwargs.get('multiple', 4)

def baz(a, **kwargs):
    foo(a, **kwargs)
    bar(a, **kwargs)

You would then call baz like so, only having to pass in specific keyword argument values if you want the keyword argument to have different value than the default:

baz('a', print_line='Hello World', number=2, multiple=4)
# or...
baz('a', number=2, multiple=4)
# or...
baz('a', print_line='Hello World')
# or...
baz('a')


问:
Delete html tags from text during xslt transformation
I am doing xslt transformation and I have a problem. The text that I have to transform have some html tags, but instead of < and > I have < and >. I want to change content from all tags from

ici-import/issue/article/languageVersion/abstract

and transform it into a new element: abstract, deleting the html tags

That is my code I was trying to implement:

```<code><xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="ici-import/issue/article/languageVersion/">
        <xsl:variable name="StripHTML">
            <![CDATA[<\s*\w.*?>|<\s*/\s*\w\s*.*?>]]>
        </xsl:variable>
        <xsl:analyze-string select="abstract" regex="{$StripHTML}">
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>
</code>```

My current xslt:

```<code><xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <ici-import>
            <journal issn="2299-3711" />
            <issue>
                <xsl:for-each select="issue/section">
                    <xsl:for-each select="article">
                        <article>
                            <languageVersion>
                                <xsl:if test="abstract != ''">
                                    <abstract>
                                        <xsl:value-of select="abstract"/>
                                    </abstract>
                                </xsl:if>
                            </languageVersion>
                        </article>
                    </xsl:for-each>
                </xsl:for-each>
            </issue>
        </ici-import>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
If the contents you have escaped is an XML fragment then in XSLT 3 (as supported by Saxon 9.8 HE or Altova 2017 and 2018) you could simply parse the contents and push it through a mode that only copies text through.

Here is an example:

```<code><?xml version="1.0" encoding="utf-8" ?>
<root>
    <data><![CDATA[<section id="s1">
    <h2>Test</h2>
    <p style="font-size: 120%">This is some text.</p>
</section>
<section>
  <h2>Another test</h2>
  <p>This is some text.</p>
  </section>]]></data>
</root>
</code>```

is transformed by Saxon 9.8 HE and the XSLT

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    exclude-result-prefixes="xs math map array"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:mode name="strip" on-no-match="text-only-copy"/>

  <xsl:template match="data">
      <xsl:copy>
          <xsl:apply-templates select="parse-xml-fragment(.)" mode="strip"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

into

```<code><?xml version="1.0" encoding="UTF-8"?><root>
    <data>
    Test
    This is some text.

  Another test
  This is some text.
  </data>
</root>
</code>```

If the contents is not XML but HTML then you could import a local copy of David Carlisle's HTML parser written in XSLT 2 and use that to parse the contents and push it through a mode that only copies text through:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    xmlns:htmlparser="data:,dpc"
    exclude-result-prefixes="xs math map array htmlparser"
    version="3.0">

  <!-- adjust to local copy of file -->
  <xsl:import href="https://github.com/davidcarlisle/web-xslt/raw/master/htmlparse/htmlparse.xsl"/>

  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:mode name="strip" on-no-match="text-only-copy"/>

  <xsl:template match="data">
      <xsl:copy>
          <xsl:apply-templates select="htmlparser:htmlparse(.)/node()" mode="strip"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

Using Saxon 9.8 HE that transforms

```<code><?xml version="1.0" encoding="utf-8" ?>
<root>
    <data><![CDATA[<section id=s1>
    <h2>Test</h2>
    <p style="font-size: 120%">This is some text.</p>
</section>
<section>
  <h2>Another test</h2>
  <p>This is some text.
  <p>This is some other text.
  </section>]]></data>
</root>
</code>```

into

```<code><?xml version="1.0" encoding="UTF-8"?><root>
    <data>
    Test
    This is some text.

  Another test
  This is some text.
  This is some other text.
  </data>
</root>
</code>```

Of course as the HTML parser is written in XSLT 2 you can use it with any XSLT 2 processor as well, you simply need to replace <xsl:mode name="strip" on-no-match="text-only-copy"/> by

```<code><xsl:template match="*" mode="strip">
  <xsl:apply-templates/>
</xsl:template>
</code>```

Body:
I am doing xslt transformation and I have a problem. The text that I have to transform have some html tags, but instead of < and > I have < and >. I want to change content from all tags from

ici-import/issue/article/languageVersion/abstract

and transform it into a new element: abstract, deleting the html tags

That is my code I was trying to implement:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="ici-import/issue/article/languageVersion/">
        <xsl:variable name="StripHTML">
            <![CDATA[<\s*\w.*?>|<\s*/\s*\w\s*.*?>]]>
        </xsl:variable>
        <xsl:analyze-string select="abstract" regex="{$StripHTML}">
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>

My current xslt:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <ici-import>
            <journal issn="2299-3711" />
            <issue>
                <xsl:for-each select="issue/section">
                    <xsl:for-each select="article">

                            <languageVersion>
                                <xsl:if test="abstract != ''">
                                    <abstract>
                                        <xsl:value-of select="abstract"/>
                                    </abstract>
                                </xsl:if>
                            </languageVersion>

                    </xsl:for-each>
                </xsl:for-each>
            </issue>
        </ici-import>
    </xsl:template>
</xsl:stylesheet>

Body:
If the contents you have escaped is an XML fragment then in XSLT 3 (as supported by Saxon 9.8 HE or Altova 2017 and 2018) you could simply parse the contents and push it through a mode that only copies text through.

Here is an example:

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <data><![CDATA[<section id="s1">
    <h2>Test</h2>
    <p style="font-size: 120%">This is some text.</p>
</section>
<section>
  <h2>Another test</h2>
  <p>This is some text.</p>
  </section>]]></data>
</root>

is transformed by Saxon 9.8 HE and the XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    exclude-result-prefixes="xs math map array"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:mode name="strip" on-no-match="text-only-copy"/>

  <xsl:template match="data">
      <xsl:copy>
          <xsl:apply-templates select="parse-xml-fragment(.)" mode="strip"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

into

<?xml version="1.0" encoding="UTF-8"?><root>
    <data>
    Test
    This is some text.

  Another test
  This is some text.
  </data>
</root>

If the contents is not XML but HTML then you could import a local copy of David Carlisle's HTML parser written in XSLT 2 and use that to parse the contents and push it through a mode that only copies text through:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    xmlns:htmlparser="data:,dpc"
    exclude-result-prefixes="xs math map array htmlparser"
    version="3.0">

  <!-- adjust to local copy of file -->
  <xsl:import href="https://github.com/davidcarlisle/web-xslt/raw/master/htmlparse/htmlparse.xsl"/>

  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:mode name="strip" on-no-match="text-only-copy"/>

  <xsl:template match="data">
      <xsl:copy>
          <xsl:apply-templates select="htmlparser:htmlparse(.)/node()" mode="strip"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Using Saxon 9.8 HE that transforms

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <data><![CDATA[<section id=s1>
    <h2>Test</h2>
    <p style="font-size: 120%">This is some text.</p>
</section>
<section>
  <h2>Another test</h2>
  <p>This is some text.
  <p>This is some other text.
  </section>]]></data>
</root>

into

<?xml version="1.0" encoding="UTF-8"?><root>
    <data>
    Test
    This is some text.

  Another test
  This is some text.
  This is some other text.
  </data>
</root>

Of course as the HTML parser is written in XSLT 2 you can use it with any XSLT 2 processor as well, you simply need to replace <xsl:mode name="strip" on-no-match="text-only-copy"/> by

<xsl:template match="*" mode="strip">
  <xsl:apply-templates/>
</xsl:template>


问:
Do While with Multiple Conditions
Simple Question, I must just be missing something obvious.

I am trying to create a subroutine that polls for a window to be open and I am aiming to accomplish this by a loop that will run while two conditions are met. I keep getting an error:

Run time error 13: Type Mismatch

On the Do while loop, and after searching through the similar issues on SO I still am not quite sure what I am doing wrong.

Here is the line that keeps erroring out:

```<code>Sub FindHWND()
    Dim HWNDOut as string
    Dim Timer as Date
    Timer = Now()
    'This following line is the one erroring out.
    Do While ((Now() < Timer + TimeValue("00:00:10")) And (HWNDOut = 0))
        HWNDOut = CStr(Hex(FindWindowEx(0&, 0, "SunAwtFrame", "Graph.graphml - yEd")))
        Debug.Print HWNDOut
        Sleep (100)
    Loop
    'Other, following sub and code that is not relevant
End Sub
</code>```

Where Timer is the Now() at moment before the loop starts, and HWNDOut is the handle for the window I am looking for, which will be found in the loop.

All this loop does is look every 100 MS to see if the window to a third party program has opened, in order to prevent the loss of commands in the next subroutines.

Post Script: If anyone has any suggestions how to do this better, I'm all ears. This is my first time using UI Automation so I'm still learning.
Edit: Added more code to the block for context.

答:
Try changing variable name Timer to something else e.g. StartTime (think there is a Timer function in VBA which returns a value of a different type; so best not to use words which are reserved or semantically significant).

Might help, might not, good luck.

Title: Do While with Multiple Conditions

Body:
Simple Question, I must just be missing something obvious.

I am trying to create a subroutine that polls for a window to be open and I am aiming to accomplish this by a loop that will run while two conditions are met. I keep getting an error:

Run time error 13: Type Mismatch

On the Do while loop, and after searching through the similar issues on SO I still am not quite sure what I am doing wrong.

Here is the line that keeps erroring out:

Sub FindHWND()
    Dim HWNDOut as string
    Dim Timer as Date
    Timer = Now()
    'This following line is the one erroring out.
    Do While ((Now() < Timer + TimeValue("00:00:10")) And (HWNDOut = 0))
        HWNDOut = CStr(Hex(FindWindowEx(0&, 0, "SunAwtFrame", "Graph.graphml - yEd")))
        Debug.Print HWNDOut
        Sleep (100)
    Loop
    'Other, following sub and code that is not relevant
End Sub

Where Timer is the Now() at moment before the loop starts, and HWNDOut is the handle for the window I am looking for, which will be found in the loop.

All this loop does is look every 100 MS to see if the window to a third party program has opened, in order to prevent the loss of commands in the next subroutines.

Post Script: If anyone has any suggestions how to do this better, I'm all ears. This is my first time using UI Automation so I'm still learning.
Edit: Added more code to the block for context.


问:
No errors and always zero for result
I am trying to write a function that gets the average of a users number guesses. The table has the userID and tieBreakerPoints.

```<code>function getUserTBA($userID) {
    global $mysqli;

    // loop through user totals & calculate average for each user
    $sql = "SELECT u.userID, p.userID, AVG(p.tieBreakerPoints) AS 'avarage' ";
    $sql .= "FROM " . DB_PREFIX . "picksummary p";
    $sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
    $sql .= "WHERE p.userID = " . $user->userID . " ";
    $sql .= "GROUP BY p.userID";
    $query = $mysqli->query($sql);

    if ($query->num_rows > 0) {
        $row = $query->fetch_array();
        return (int)$row['average'];
    }

    return 0;
}
</code>```

When I call the function, I only seem to get zero values, but if I run the SQL query directly in SQL, I get the results. Am I missing something with this function?

答:
There may be other problems, but $user (and by extension, $user->userID) is undefined in your function scope. Consequently, you're concatenating a null value there, so the SQL you're generating is

```<code>WHERE p.userID =  GROUP BY p.userID
</code>```

which is causing the error you mentioned in the comments. It's a syntax error because you have a keyword where it's expecting a value.

I see you have $userID as a parameter to the function, but it isn't used. Should it just be $user?

Title: No errors and always zero for result

Body:
I am trying to write a function that gets the average of a users number guesses. The table has the userID and tieBreakerPoints.

function getUserTBA($userID) {
    global $mysqli;

    // loop through user totals & calculate average for each user
    $sql = "SELECT u.userID, p.userID, AVG(p.tieBreakerPoints) AS 'avarage' ";
    $sql .= "FROM " . DB_PREFIX . "picksummary p";
    $sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
    $sql .= "WHERE p.userID = " . $user->userID . " ";
    $sql .= "GROUP BY p.userID";
    $query = $mysqli->query($sql);

    if ($query->num_rows > 0) {
        $row = $query->fetch_array();
        return (int)$row['average'];
    }

    return 0;
}

When I call the function, I only seem to get zero values, but if I run the SQL query directly in SQL, I get the results. Am I missing something with this function?

Body:
There may be other problems, but $user (and by extension, $user->userID) is undefined in your function scope. Consequently, you're concatenating a null value there, so the SQL you're generating is

WHERE p.userID =  GROUP BY p.userID

which is causing the error you mentioned in the comments. It's a syntax error because you have a keyword where it's expecting a value.

I see you have $userID as a parameter to the function, but it isn't used. Should it just be $user?


问:
How to Fix Permissions on Home-brew on MacOS High Sierra
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

```<code>$ brew link python
</code>```

After entering that the same error message appears:

```permission denied @ dir_s_mkdir - /usr/local/lib```

I have tried to do:

```<code>$ sudo chown -R $(whoami) /usr/local
</code>```

And I get an error message that reads:

chown: /usr/local: Operation not permitted

答:
I tried and had this same ( I think ) output:

```<code>Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
</code>```

So I created a directory /usr/local/Frameworks as root, and than change the ownership:

```<code>sudo mkdir /usr/local/Frameworks && chown $USER:admin /usr/local/Frameworks
</code>```

I tried again brew install python:

```<code>Warning: python 2.7.14 is already installed, it's just not linked.
You can use `brew link python` to link this version.
</code>```

And then brew link python:

```<code>Linking /usr/local/Cellar/python/2.7.14... 26 symlinks created
</code>```

Now in directory /usr/local/Frameworks/Python.framework/ I can see links, for example:

```<code>lrwxr-xr-x 1 niquit admin  62 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Headers -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Headers/
lrwxr-xr-x 1 niquit admin  61 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Python -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Python*
lrwxr-xr-x 1 niquit admin  64 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Resources -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Resources/
</code>```

In your case, I suggest create manually /usr/local/lib:

```<code>sudo mkdir /usr/local/lib && chown $USER:admin /usr/local/lib
</code>```

A made a test by mv /usr/local/lib{,.orig}, and I got:

```<code>Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/lib
Error: Permission denied @ dir_s_mkdir - /usr/local/lib
</code>```

Like before I created manually directory sudo mkdir /usr/local/lib && chown $USER:admin /usr/local/lib, and successful did brew link python:

```<code>Linking /usr/local/Cellar/python/2.7.14... 324 symlinks created
</code>```

Now I can find some links:

```<code>lrwxr-xr-x 1 niquit admin  54 Dec  8 22:01 python-2.7.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python-2.7.pc
lrwxr-xr-x 1 niquit admin  50 Dec  8 22:01 python.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python.pc
lrwxr-xr-x 1 niquit admin  51 Dec  8 22:01 python2.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python2.pc
</code>```

I think that Apple after latest update increased security, so its not possible to create now directory in /usr/ without root permission.

Body:
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

$ brew link python

After entering that the same error message appears:

permission denied @ dir_s_mkdir - /usr/local/lib

I have tried to do:

$ sudo chown -R $(whoami) /usr/local

And I get an error message that reads:

chown: /usr/local: Operation not permitted

Body:
I tried and had this same ( I think ) output:

Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

So I created a directory /usr/local/Frameworks as root, and than change the ownership:

sudo mkdir /usr/local/Frameworks && chown $USER:admin /usr/local/Frameworks

I tried again brew install python:

Warning: python 2.7.14 is already installed, it's just not linked.
You can use `brew link python` to link this version.

And then brew link python:

Linking /usr/local/Cellar/python/2.7.14... 26 symlinks created

Now in directory /usr/local/Frameworks/Python.framework/ I can see links, for example:

lrwxr-xr-x 1 niquit admin  62 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Headers -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Headers/
lrwxr-xr-x 1 niquit admin  61 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Python -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Python*
lrwxr-xr-x 1 niquit admin  64 Dec  8 21:41 /usr/local/Frameworks/Python.framework/Resources -> ../../Cellar/python/2.7.14/Frameworks/Python.framework/Resources/

In your case, I suggest create manually /usr/local/lib:

sudo mkdir /usr/local/lib && chown $USER:admin /usr/local/lib

A made a test by mv /usr/local/lib{,.orig}, and I got:

Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/lib
Error: Permission denied @ dir_s_mkdir - /usr/local/lib

Like before I created manually directory sudo mkdir /usr/local/lib && chown $USER:admin /usr/local/lib, and successful did brew link python:

Linking /usr/local/Cellar/python/2.7.14... 324 symlinks created

Now I can find some links:

lrwxr-xr-x 1 niquit admin  54 Dec  8 22:01 python-2.7.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python-2.7.pc
lrwxr-xr-x 1 niquit admin  50 Dec  8 22:01 python.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python.pc
lrwxr-xr-x 1 niquit admin  51 Dec  8 22:01 python2.pc -> ../../Cellar/python/2.7.14/lib/pkgconfig/python2.pc

I think that Apple after latest update increased security, so its not possible to create now directory in /usr/ without root permission.


问:
How to insert data into MS Access table without entering data into the AutoNumber column?
I am working with Microsoft Access 2016 and developing a ASP.NET WebForm where I want to enter data into the tbl_users table. I have the following server side code:

```<code>connectionString = GetConnString();
string insertQuery = "insert into tbl_users (fullName, emailID, password) values(?, ?, ?)";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    using (OleDbCommand insertCommand = new OleDbCommand(insertQuery, con))
    {
        insertCommand.CommandType = CommandType.Text;
        insertCommand.Parameters.AddWithValue("fullName", TextBoxFullName.Text);
        insertCommand.Parameters.AddWithValue("emailID", TextBoxEmailID.Text);
        insertCommand.Parameters.AddWithValue("password", TextBoxPassword.Text);
        insertCommand.ExecuteNonQuery();
        con.Close();
    }
}
</code>```

The table schemas is as follows:

tbl_users(userID(AutoNumber), fullName(LongText), emailID(LongText), password(LongText))

When I run the code, I get the following error:

System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement

Where am I going wrong?

答:
password is a keyword in Access SQL, thus needs to be bracketed. Add brackets ([password]) and your query will run fine.

End result:

```<code>string insertQuery = "insert into tbl_users (fullName, emailID, [password]) values(?, ?, ?)";
</code>```

Body:
I am working with Microsoft Access 2016 and developing a ASP.NET WebForm where I want to enter data into the tbl_users table. I have the following server side code:

connectionString = GetConnString();
string insertQuery = "insert into tbl_users (fullName, emailID, password) values(?, ?, ?)";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    using (OleDbCommand insertCommand = new OleDbCommand(insertQuery, con))
    {
        insertCommand.CommandType = CommandType.Text;
        insertCommand.Parameters.AddWithValue("fullName", TextBoxFullName.Text);
        insertCommand.Parameters.AddWithValue("emailID", TextBoxEmailID.Text);
        insertCommand.Parameters.AddWithValue("password", TextBoxPassword.Text);
        insertCommand.ExecuteNonQuery();
        con.Close();
    }
}

The table schemas is as follows:

tbl_users(userID(AutoNumber), fullName(LongText), emailID(LongText), password(LongText))

When I run the code, I get the following error:

System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement

Where am I going wrong?

Body:
password is a keyword in Access SQL, thus needs to be bracketed. Add brackets ([password]) and your query will run fine.

End result:

string insertQuery = "insert into tbl_users (fullName, emailID, [password]) values(?, ?, ?)";


问:
Why do these two methods of loading images from SQL CE into a WPF Image produce different results?
In a ValueConverter, I was trying to convert a System.Data.Linq.Binary (SQL CE image) to a BitmapImage. This method works (image is show correctly on the form):

```<code>public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(binary.ToArray());
        bitmap.EndInit();
        return bitmap;
    }
    return null;
}
</code>```

This method does NOT work (but no exception is thrown, strangely):

```<code>public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
    }
    return null;
}
</code>```

Good programming practice states that you should dispose of any streams you create... so I'm confused why the second method doesn't work, but the first does. Any insights?

答:
Try this instead:

```<code>public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze();
            return bitmap;
        }
    }
    return null;
}
</code>```

In your non-working version, your using block means the stream is closed before the image is actually decoded.

ContentLicense: CC BY-SA 2.5

Body:
In a ValueConverter, I was trying to convert a System.Data.Linq.Binary (SQL CE image) to a BitmapImage. This method works (image is show correctly on the form):

public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(binary.ToArray());
        bitmap.EndInit();
        return bitmap;
    }
    return null;
}

This method does NOT work (but no exception is thrown, strangely):

public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
    }
    return null;
}

Good programming practice states that you should dispose of any streams you create... so I'm confused why the second method doesn't work, but the first does. Any insights?

Body:
Try this instead:

public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze();
            return bitmap;
        }
    }
    return null;
}

In your non-working version, your using block means the stream is closed before the image is actually decoded.


问:
Why doesn't android studio show type of object or variables
If I use Xcode or visual studio all I have to do is hover my mouse (Or alt + hover) to get more information about what the variable is returning or expecting. How can I do the same thing in android studio? </p>

<p>Do I have something toggled off or does android studio not support something like that? </p>

答: It's ctrl + shift + p. You can customize it in File -> Settings -> Keymap -> View -> Expression Type.</p>

Body:
If I use Xcode or visual studio all I have to do is hover my mouse (Or alt + hover) to get more information about what the variable is returning or expecting. How can I do the same thing in android studio?

Do I have something toggled off or does android studio not support something like that?


问:
Why would removeAllObservers() not work in deinit?
As everyone knows when using the awesomeness that is Firebase in iOS,

whenever you have observations in a view controller,,

```<code>var o: DatabaseReference?
var o2: DatabaseReference?
var o3: DatabaseReference?
</code>```

it's essential that when that screen goes away, you must terminate all the observations...

```<code>private func clearObservations() {

    print("\n\n clearing observations! \n\n")

    if o != nil {

        o?.removeAllObservers()
        o = nil
    }

    if o2 != nil {
    etc...
}
</code>```

However!

After considerable testing, you cannot call clearObservations() in deinit - you must call it in viewDidDisappear (or some other logical place).

Again - it explicitly does not work in deinit.

My question, why would it be that actually this does not work in deinit?

BTW, you fire up a Firebase observor like this:

```<code>say, viewWillAppear#

    o = Database.database().reference(withPath: "string")
    o!.observe(.value, with: { (snapshot) in

        self.blah(snapshot)
    })
</code>```

答:
I believe your issue is likely that deinit is not being called at all and usually this kind of thing is because your observer closure is strongly retaining self and the closure is itself retained by the firebase service.  That means your object can never die.  You can break this kind of cycle with an unowned or weak capture.

To check if this is the case, put a print in your deinit.  If the print does not get called when you expect then the object is not being released and you should run the memory debugger to see who else is pointing at it.

I've had the same issue before when forgetting to put unowned on a realm observe method.

Body:
As everyone knows when using the awesomeness that is Firebase in iOS,

whenever you have observations in a view controller,,

var o: DatabaseReference?
var o2: DatabaseReference?
var o3: DatabaseReference?

it's essential that when that screen goes away, you must terminate all the observations...

private func clearObservations() {

    print("\n\n clearing observations! \n\n")

    if o != nil {

        o?.removeAllObservers()
        o = nil
    }

    if o2 != nil {
    etc...
}

However!

After considerable testing, you cannot call clearObservations() in deinit - you must call it in viewDidDisappear (or some other logical place).

Again - it explicitly does not work in deinit.

My question, why would it be that actually this does not work in deinit?

BTW, you fire up a Firebase observor like this:

say, viewWillAppear#

    o = Database.database().reference(withPath: "string")
    o!.observe(.value, with: { (snapshot) in

        self.blah(snapshot)
    })


问:
How to follow the cursor with Angular?
I created a simple application (StackBlitz here) in Angular with animations.
It uses states that we can toggle to make an eye look wherever we want.

Now I would like to be able to follow the mouse cursor using pure Angular/TypeScript (not jQuery...), so the eye would look to the cursor's direction whenever the mouse is moving.

Any suggestion would be appreciated.

答:
You could use @HostListener decorator.
Here is live example</p>

Title: How to follow the cursor with Angular?


问:
Parallelizing through Multi-threading and Multi-processing taking significantly more time than serial
I'm trying to learn how to do parallel programming in python. I wrote a simple int square function and then ran it in serial, multi-thread, and multi-process:

```<code>import time
import multiprocessing, threading
import random

def calc_square(numbers):
    sq = 0
    for n in numbers:
        sq = n*n

def splita(list, n):
    a = [[] for i in range(n)]
    counter = 0
    for i in range(0,len(list)):
        a[counter].append(list[i])
        if len(a[counter]) == len(list)/n:
            counter = counter +1
            continue
    return a

if __name__ == "__main__":

    random.seed(1)
    arr = [random.randint(1, 11) for i in xrange(1000000)]
    print "init completed"

    start_time2 = time.time()
    calc_square(arr)
    end_time2 = time.time()

    print "serial: " + str(end_time2 - start_time2)

    newarr = splita(arr,8)
    print 'split complete'

    start_time = time.time()

    for i in range(8):
        t1 = threading.Thread(target=calc_square, args=(newarr[i],))

        t1.start()
        t1.join()

    end_time = time.time()

    print "mt: " + str(end_time - start_time)

    start_time = time.time()

    for i in range(8):
        p1 = multiprocessing.Process(target=calc_square, args=(newarr[i],))
        p1.start()
        p1.join()

    end_time = time.time()

    print "mp: " + str(end_time - start_time)
</code>```

Output:

```<code>init completed
serial: 0.0640001296997
split complete
mt: 0.0599999427795
mp: 2.97099995613
</code>```

However, as you can see, something weird happened and mt is taking the same time as serial and mp is actually taking significantly longer (almost 50 times longer).

What am I doing wrong? Could someone push me in the right direction to learn parallel programming in python?

Edit 01

Looking at the comments, I see that perhaps the function not returning anything seems pointless. The reason I'm even trying this is because previously I tried the following add function:

```<code>def addi(numbers):
    sq = 0
    for n in numbers:
        sq = sq + n
    return sq
</code>```

I tried returning the addition of each part to a serial number adder, so at least I could see some performance improvement over a pure serial implementation. However, I couldn't figure out how to store and use the returned value, and that's the reason I'm trying to figure out something even simpler than that, which is just dividing up the array and running a simple function on it.

Thanks!

答:
I think that multiprocessing takes quite a long time to create and start each process. I have changed the program to make 10 times the size of arr and changed the way that the processes are started and there is a slight speed-up:

(Also note python 3)

```<code>import time
import multiprocessing, threading
from multiprocessing import Queue
import random

def calc_square_q(numbers,q):
    while q.empty():
        pass
    return calc_square(numbers)

if __name__ == "__main__":

    random.seed(1)   # note how big arr is now vvvvvvv
    arr = [random.randint(1, 11) for i in range(10000000)]
    print("init completed")

    # ...
    # other stuff as before
    # ...

    processes=[]
    q=Queue()
    for arrs in newarr:
        processes.append(multiprocessing.Process(target=calc_square_q, args=(arrs,q)))

    print('start processes')
    for p in processes:
        p.start()  # even tho' each process is started it waits...

    print('join processes')
    q.put(None)   # ... for q to become not empty.
    start_time = time.time()
    for p in processes:
        p.join()

    end_time = time.time()

    print("mp: " + str(end_time - start_time))
</code>```

Also notice above how I create and start the processes in two different loops, and then finally join with the processes in a third loop.

Output:

```<code>init completed
serial: 0.53214430809021
split complete
start threads
mt: 0.5551605224609375
start processes
join processes
mp: 0.2800724506378174
</code>```

Another factor of 10 increase in size of arr:

```<code>init completed
serial: 5.8455305099487305
split complete
start threads
mt: 5.411392450332642
start processes
join processes
mp: 1.9705185890197754
</code>```

And yes, I've also tried this in python 2.7, although Threads seemed slower.

Body:
I'm trying to learn how to do parallel programming in python. I wrote a simple int square function and then ran it in serial, multi-thread, and multi-process:

import time
import multiprocessing, threading
import random

def calc_square(numbers):
    sq = 0
    for n in numbers:
        sq = n*n

def splita(list, n):
    a = [[] for i in range(n)]
    counter = 0
    for i in range(0,len(list)):
        a[counter].append(list[i])
        if len(a[counter]) == len(list)/n:
            counter = counter +1
            continue
    return a

if __name__ == "__main__":

    random.seed(1)
    arr = [random.randint(1, 11) for i in xrange(1000000)]
    print "init completed"

    start_time2 = time.time()
    calc_square(arr)
    end_time2 = time.time()

    print "serial: " + str(end_time2 - start_time2)

    newarr = splita(arr,8)
    print 'split complete'

    start_time = time.time()

    for i in range(8):
        t1 = threading.Thread(target=calc_square, args=(newarr[i],))

        t1.start()
        t1.join()

    end_time = time.time()

    print "mt: " + str(end_time - start_time)

    start_time = time.time()

    for i in range(8):
        p1 = multiprocessing.Process(target=calc_square, args=(newarr[i],))
        p1.start()
        p1.join()

    end_time = time.time()

    print "mp: " + str(end_time - start_time)

Output:

init completed
serial: 0.0640001296997
split complete
mt: 0.0599999427795
mp: 2.97099995613

However, as you can see, something weird happened and mt is taking the same time as serial and mp is actually taking significantly longer (almost 50 times longer).

What am I doing wrong? Could someone push me in the right direction to learn parallel programming in python?

Edit 01

Looking at the comments, I see that perhaps the function not returning anything seems pointless. The reason I'm even trying this is because previously I tried the following add function:

def addi(numbers):
    sq = 0
    for n in numbers:
        sq = sq + n
    return sq

I tried returning the addition of each part to a serial number adder, so at least I could see some performance improvement over a pure serial implementation. However, I couldn't figure out how to store and use the returned value, and that's the reason I'm trying to figure out something even simpler than that, which is just dividing up the array and running a simple function on it.

Thanks!

Body:
I think that multiprocessing takes quite a long time to create and start each process. I have changed the program to make 10 times the size of arr and changed the way that the processes are started and there is a slight speed-up:

(Also note python 3)

import time
import multiprocessing, threading
from multiprocessing import Queue
import random

def calc_square_q(numbers,q):
    while q.empty():
        pass
    return calc_square(numbers)

if __name__ == "__main__":

    random.seed(1)   # note how big arr is now vvvvvvv
    arr = [random.randint(1, 11) for i in range(10000000)]
    print("init completed")

    # ...
    # other stuff as before
    # ...

    processes=[]
    q=Queue()
    for arrs in newarr:
        processes.append(multiprocessing.Process(target=calc_square_q, args=(arrs,q)))

    print('start processes')
    for p in processes:
        p.start()  # even tho' each process is started it waits...

    print('join processes')
    q.put(None)   # ... for q to become not empty.
    start_time = time.time()
    for p in processes:
        p.join()

    end_time = time.time()

    print("mp: " + str(end_time - start_time))

Also notice above how I create and start the processes in two different loops, and then finally join with the processes in a third loop.

Output:

init completed
serial: 0.53214430809021
split complete
start threads
mt: 0.5551605224609375
start processes
join processes
mp: 0.2800724506378174

Another factor of 10 increase in size of arr:

init completed
serial: 5.8455305099487305
split complete
start threads
mt: 5.411392450332642
start processes
join processes
mp: 1.9705185890197754

And yes, I've also tried this in python 2.7, although Threads seemed slower.


问:
Can't install cordova with npm 5.6.0
I can't install cordova in my Linux (deepin 15.5), please help me :)

$ sudo npm install -g ionic

```<code>/usr/local/bin/ionic -> /usr/local/lib/node_modules/ionic/bin/ionic
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/ionic/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

\+ ionic@3.19.0
updated 1 package in 8.52s
</code>```

$sudo npm install -g cordova

```<code>npm WARN deprecated node-uuid@1.4.8: Use uuid module instead
npm ERR! path /usr/local/lib/node_modules/cordova/node_modules  /npm/node_modules/ansistyles
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename '/usr/local/lib/node_modules/cordova/node_modules/npm/node_modules/ansistyles' -> '/usr/local/lib/node_modules/cordova/node_modules/npm/node_modules/.ansistyles.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-08T19_53_31_209Z-debug.log
</code>```

答:
You could try downgrading your NPM version. Personally, I had some issues with 5.6.0 and had to downgrade to 5.3.0, haven't had a problem with any packages since then.

If you want to, this is how you'd downgrade your version to 5.3.0:

```<code>npm install -g npm@5.3.0
</code>```

Cheers!

EDIT: Also, make sure there have not been any previous installations of the package you are trying to install. Leftovers or older versions may cause conflict which might not let you install/update to newer versions.

Try this, if the previous solution doesn't work:

```<code>npm uninstall -g cordova
npm install -g cordova
</code>```

Title: Can't install cordova with npm 5.6.0

Body:
I can't install cordova in my Linux (deepin 15.5), please help me :)

$ sudo npm install -g ionic

/usr/local/bin/ionic -> /usr/local/lib/node_modules/ionic/bin/ionic
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/ionic/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

\+ ionic@3.19.0
updated 1 package in 8.52s

$sudo npm install -g cordova

npm WARN deprecated node-uuid@1.4.8: Use uuid module instead
npm ERR! path /usr/local/lib/node_modules/cordova/node_modules  /npm/node_modules/ansistyles
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename '/usr/local/lib/node_modules/cordova/node_modules/npm/node_modules/ansistyles' -> '/usr/local/lib/node_modules/cordova/node_modules/npm/node_modules/.ansistyles.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-08T19_53_31_209Z-debug.log

Body:
You could try downgrading your NPM version. Personally, I had some issues with 5.6.0 and had to downgrade to 5.3.0, haven't had a problem with any packages since then.

If you want to, this is how you'd downgrade your version to 5.3.0:

npm install -g npm@5.3.0

Cheers!

EDIT: Also, make sure there have not been any previous installations of the package you are trying to install. Leftovers or older versions may cause conflict which might not let you install/update to newer versions.

Try this, if the previous solution doesn't work:

npm uninstall -g cordova
npm install -g cordova


问:
How to store elements in javascript array?
I am trying to build a card game in which two players gets random cards and the one who gets the highest sum of cards wins.

I tried pushing the generated random number into array .The trouble here is the new number should add to array but instead its going off leaving array empty. Could someone please help me.

 var varCounter = 1;
    var refVar = setInterval(function() {

      if (varCounter <= 4) {

        var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player1 = [];
        player1.push(randomnumber);

        for (var i = 0; i < player1.length; i++) {
          document.write("
");
          document.write("player1 " + i + "card");
          document.write("
");
          document.write(player1[i]);

        }
        varCounter++;
      } else if (varCounter >= 5 && varCounter <= 8) {
        var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player2 = [];
        player2.push(randomnumber2);
        for (var i = 0; i < player2.length; i++) {
          document.write("
");
          document.write("player2 " + i + "card");
          document.write("
");
          document.write(player2[i]);
        }
        varCounter++;
      } else {
        clearInterval(refVar);
      }
    }, 100);```
</div>
</div>
</p>

<p>EXPECTED OUTPUT:</p>

```player1 1card
9
player1 2card
12
player1 3card
4
player1 4card
12
player2 1card
5
player2 2card
7
player2 3card
9
player2 4card
2
```

<p>CURRENT OUTPUT:</p>

```player1 0card
9
player1 0card
12
player1 0card
4
player1 0card
12
player2 0card
5
player2 0card
7
player2 0card
9
player2 0card
2
```

答:
As the comments on your question pointed out, your arrays player1 and player2 get overwritten each time you iterate through your counter as it's contained within the iteration, if you like to write something with every iteration, I suggest taking out your for loop like this:

```<code>if (varCounter <= 4) {
  var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
  var player1 = [];
  player1.push(randomnumber);

  document.write("<br>");
  document.write("player1 " + varCounter + "card"); // varCounter becomes your 1 2 3 4card
  document.write("<br>");
  document.write(player1);

  varCounter++;
}
</code>```

Or exploring a while loop like this: https://codepen.io/corviday/pen/pdMyEw?editors=1010

Hope this helps!

Body:
I am trying to build a card game in which two players gets random cards and the one who gets the highest sum of cards wins.

I tried pushing the generated random number into array .The trouble here is the new number should add to array but instead its going off leaving array empty. Could someone please help me.

 var varCounter = 1;
    var refVar = setInterval(function() {

      if (varCounter <= 4) {

        var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player1 = [];
        player1.push(randomnumber);

        for (var i = 0; i < player1.length; i++) {
          document.write("
");
          document.write("player1 " + i + "card");
          document.write("
");
          document.write(player1[i]);

        }
        varCounter++;
      } else if (varCounter >= 5 && varCounter <= 8) {
        var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player2 = [];
        player2.push(randomnumber2);
        for (var i = 0; i < player2.length; i++) {
          document.write("
");
          document.write("player2 " + i + "card");
          document.write("
");
          document.write(player2[i]);
        }
        varCounter++;
      } else {
        clearInterval(refVar);
      }
    }, 100);

EXPECTED OUTPUT:

player1 1card
9
player1 2card
12
player1 3card
4
player1 4card
12
player2 1card
5
player2 2card
7
player2 3card
9
player2 4card
2

CURRENT OUTPUT:

player1 0card
9
player1 0card
12
player1 0card
4
player1 0card
12
player2 0card
5
player2 0card
7
player2 0card
9
player2 0card
2

Body:
As the comments on your question pointed out, your arrays player1 and player2 get overwritten each time you iterate through your counter as it's contained within the iteration, if you like to write something with every iteration, I suggest taking out your for loop like this:

if (varCounter <= 4) {
  var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
  var player1 = [];
  player1.push(randomnumber);

  document.write("<br>");
  document.write("player1 " + varCounter + "card"); // varCounter becomes your 1 2 3 4card
  document.write("<br>");
  document.write(player1);

  varCounter++;
}

Or exploring a while loop like this: https://codepen.io/corviday/pen/pdMyEw?editors=1010

Hope this helps!


问:
can't cast wrapper to object
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.</p>

```<code>private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}
</code>```

答:
In order to get text, a string, to a long, or other numeric data type, you would have to convert it with the data types parse method. </p>

<p>What Aomine mentioned about relationship is correct.
Short -> Integer -> Long </p>

Title: can't cast wrapper to object

Body:
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.

private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}

Body:
In order to get text, a string, to a long, or other numeric data type, you would have to convert it with the data types parse method.

What Aomine mentioned about relationship is correct.
Short -> Integer -> Long


问:
Print elements of a linked list recursively
I am trying to print out the elements of a Linked List in Java in reverse using recursion, but I don't know exactly how to go about that. I've tried looking at several examples but it doesn't look like there is anything that tries to accomplish what I need to do. I did it with a for loop but I know that completely defeats the purpose of this assignment. This is what I have so far:

```<code>public class Recursion <E>{

public void add (E list, Object element) {
    ((LinkedList) list).add(element);
}// end add

public void reverse (LinkedList<E> a) {
    for (int i = a.size() - 1; i >= 0; i--) {
        System.out.println(a.get(i));
    }
}//end reverse

public static void main(String[] args) {
    Recursion test = new Recursion();
    LinkedList<Object> list = new LinkedList<>();

    test.add(list, 1);
    test.add(list, 2);
    test.add(list, 3);
    test.add(list, 4);

    System.out.println(list);

    test.reverse(list);

}//end main
}
</code>```

I apologize if it's kinda sloppy, It's obviously not finalized in any way, but I am unsure of how to go about turning the reverse method into something that does the same thing but with recursion. Please help!

EDIT: If i need to have a seperate node class for this (not sure if I do or not), I do have this SLNode class that was provided a few weeks ago that I'm assuming would work:

```<code>public class SLNode <E>
{
public E element;
public SLNode next;

public SLNode()
{
    this.element = null;
    this.next = null;
}

public SLNode(E element, SLNode<E> node)
{
    this.element = element;
    this.next = node;
}

public E getElement()
{
    return this.element;
}

public void setElement(E element)
{
    this.element = element;
}

public SLNode<E> getSuccessor()
{
    return this.next;
}

public void setSuccessor(SLNode next)
{
    this.next = next;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return "Element: " + element;
}
}
</code>```

But once again...I'm not sure how to go about implementing it all..

答:
This is my solution</p>

```<code>// 1. recursiveDisplayElements --> Displays all elements of a MyDynamicList

/**
 * Given a concrete MyDynamicList, this recursive algorithm displays its
 * elements by screen (if any).
 *
 * @param m:
 *            The MyDynamicList we want to display its elements.
 */
public void recursiveDisplayElements(MyDynamicList m) {
    // -----------------------------
    // SET OF OPS
    // -----------------------------

    // -----------------------------
    // I. SCENARIO IDENTIFICATION
    // -----------------------------
    int scenario = 0;

    // Rule 1. MyDynamicList is empty
    if (m.length() == 0)
        scenario = 1;
    // Rule 2. MyDynamicList is non-empty
    else
        scenario = 2;
    // We create size- holds index of last element of MyDanamicList
    int size = m.length();

    // -----------------------------
    // II. SCENARIO IMPLEMENTATION
    // -----------------------------
    switch (scenario) {

    // Rule 1. MyDynamicList is empty
    case 1:
        System.out.println();
        break;
    case 2:
        // 1. We get the last element of MyDynamicList

        int e = m.getElement(size - 1);
        // 2. We print the last element from MyDanamic list
        System.out.println(e);
        // 3. We remove the last element from MyDynamicList we just checked

        m.removeElement(size - 1);
        // 4. We recursively solve the smaller problem
        recursiveDisplayElements(m);
        // 5. We also add the element back to m, so as to not to modify its original
        // state
        m.addElement(size - 1, e);

    }

}
</code>```

Body:
I am trying to print out the elements of a Linked List in Java in reverse using recursion, but I don't know exactly how to go about that. I've tried looking at several examples but it doesn't look like there is anything that tries to accomplish what I need to do. I did it with a for loop but I know that completely defeats the purpose of this assignment. This is what I have so far:

public class Recursion <E>{

public void add (E list, Object element) {
    ((LinkedList) list).add(element);
}// end add

public void reverse (LinkedList<E> a) {
    for (int i = a.size() - 1; i >= 0; i--) {
        System.out.println(a.get(i));
    }
}//end reverse

public static void main(String[] args) {
    Recursion test = new Recursion();
    LinkedList<Object> list = new LinkedList<>();

    test.add(list, 1);
    test.add(list, 2);
    test.add(list, 3);
    test.add(list, 4);

    System.out.println(list);

    test.reverse(list);

}//end main
}

I apologize if it's kinda sloppy, It's obviously not finalized in any way, but I am unsure of how to go about turning the reverse method into something that does the same thing but with recursion. Please help!

EDIT: If i need to have a seperate node class for this (not sure if I do or not), I do have this SLNode class that was provided a few weeks ago that I'm assuming would work:

public class SLNode <E>
{
public E element;
public SLNode next;

public SLNode()
{
    this.element = null;
    this.next = null;
}

public SLNode(E element, SLNode<E> node)
{
    this.element = element;
    this.next = node;
}

public E getElement()
{
    return this.element;
}

public void setElement(E element)
{
    this.element = element;
}

public SLNode<E> getSuccessor()
{
    return this.next;
}

public void setSuccessor(SLNode next)
{
    this.next = next;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return "Element: " + element;
}
}

But once again...I'm not sure how to go about implementing it all..

Body:
This is my solution

// 1. recursiveDisplayElements --> Displays all elements of a MyDynamicList

/**
 * Given a concrete MyDynamicList, this recursive algorithm displays its
 * elements by screen (if any).
 *
 * @param m:
 *            The MyDynamicList we want to display its elements.
 */
public void recursiveDisplayElements(MyDynamicList m) {
    // -----------------------------
    // SET OF OPS
    // -----------------------------

    // -----------------------------
    // I. SCENARIO IDENTIFICATION
    // -----------------------------
    int scenario = 0;

    // Rule 1. MyDynamicList is empty
    if (m.length() == 0)
        scenario = 1;
    // Rule 2. MyDynamicList is non-empty
    else
        scenario = 2;
    // We create size- holds index of last element of MyDanamicList
    int size = m.length();

    // -----------------------------
    // II. SCENARIO IMPLEMENTATION
    // -----------------------------
    switch (scenario) {

    // Rule 1. MyDynamicList is empty
    case 1:
        System.out.println();
        break;
    case 2:
        // 1. We get the last element of MyDynamicList

        int e = m.getElement(size - 1);
        // 2. We print the last element from MyDanamic list
        System.out.println(e);
        // 3. We remove the last element from MyDynamicList we just checked

        m.removeElement(size - 1);
        // 4. We recursively solve the smaller problem
        recursiveDisplayElements(m);
        // 5. We also add the element back to m, so as to not to modify its original
        // state
        m.addElement(size - 1, e);

    }

}


问:
Save a file interactively?
Using tk_choose.files or file.choose I am able to select a file interactively. Is there an analogous function wherein I can allow a user to interactively decide where to save the output of a write.table?

答:
Try </p>

```<code>val <- tkgetSaveFile(initialfile="", title="Save a file...")
f <- tclvalue(val)
if(f != "") ...
</code>```

Title: Save a file interactively?

Body:
Try

val <- tkgetSaveFile(initialfile="", title="Save a file...")
f <- tclvalue(val)
if(f != "") ...


问:
Move positions in a table - R
In R, considering a generic matrix A, how can I move the triangle NA to the position in matrix B? What about if the matrix is m x n?

```<code>> A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
> A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

> B <- matrix(c(3, 2, 3, 4, 5, NA, 1, NA, NA), nrow = 3)
> B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
</code>```

Thanks!

答:
A possible way is to rotate 180 over columns. I assumed that the NA triangle from A is used to set NA in matrix B after rotation. One can use the same technique to rotate in A matrix itself.</p>

```<code>A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

B <- matrix(c(3, 2, 3, 4, 5, 4, 1, 6, 8), nrow = 3)
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5    6
[3,]    3    4    8

#Find NA in A
NA_Val <- is.na(A)

#Rotate NA matrix on column
NA_VAL_180 <- NA_Val[1:nrow(NA_Val),ncol(NA_Val):1]

#Set corresponding values NA in B.
B[NA_VAL_180] <- NA
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
</code>```

Title: Move positions in a table - R

Body:
In R, considering a generic matrix A, how can I move the triangle NA to the position in matrix B? What about if the matrix is m x n?

> A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
> A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

> B <- matrix(c(3, 2, 3, 4, 5, NA, 1, NA, NA), nrow = 3)
> B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA

Thanks!

Body:
A possible way is to rotate 180 over columns. I assumed that the NA triangle from A is used to set NA in matrix B after rotation. One can use the same technique to rotate in A matrix itself.

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

B <- matrix(c(3, 2, 3, 4, 5, 4, 1, 6, 8), nrow = 3)
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5    6
[3,]    3    4    8

#Find NA in A
NA_Val <- is.na(A)

#Rotate NA matrix on column
NA_VAL_180 <- NA_Val[1:nrow(NA_Val),ncol(NA_Val):1]

#Set corresponding values NA in B.
B[NA_VAL_180] <- NA
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA