qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | ```
$dom = new DOMDocument;
$dom->loadXML($xml);
$elements = $dom->getElementsByTagName('*');
foreach($elements as $element) {
if ( ! $element->hasChildNodes() OR $element->nodeValue == '') {
$element->parentNode->removeChild($element);
}
}
echo $dom->saveXML();
```
[CodePad](http://codepad.viper-7.com/hDtzrS). | If you're going to be a lot of this, just do something like:
```
$value[] = "2";
$value[] = "4";
$value[] = "";
$xml = '<parentnode>';
for($i=1,$m=count($value); $i<$m+1; $i++)
$xml .= !empty($value[$i-1]) ? "<tag{$i}>{$value[$i-1]}</tag{$i}>" : null;
$xml .= '</parentnode>';
echo $xml;
```
Ideally though, you should probably use [domdocument](http://php.net/manual/en/domdocument.createelement.php). |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | You can use [XPath](http://docs.php.net/DOMXPath) with the [predicate](http://www.w3.org/TR/xpath/#predicates) `not(node())` to select all elements that do not have child nodes.
```
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml('<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
</parentnode>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//*[not(node())]') as $node ) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();
```
prints
```
<?xml version="1.0"?>
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag2>4</tag2>
<tag2>4</tag2>
</parentnode>
``` | ```
$dom = new DOMDocument;
$dom->loadXML($xml);
$elements = $dom->getElementsByTagName('*');
foreach($elements as $element) {
if ( ! $element->hasChildNodes() OR $element->nodeValue == '') {
$element->parentNode->removeChild($element);
}
}
echo $dom->saveXML();
```
[CodePad](http://codepad.viper-7.com/hDtzrS). |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | ```
$dom = new DOMDocument;
$dom->loadXML($xml);
$elements = $dom->getElementsByTagName('*');
foreach($elements as $element) {
if ( ! $element->hasChildNodes() OR $element->nodeValue == '') {
$element->parentNode->removeChild($element);
}
}
echo $dom->saveXML();
```
[CodePad](http://codepad.viper-7.com/hDtzrS). | The solution that worked with my production PHP SimpleXMLElement object code, by using Xpath, was:
```
/*
* Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
* This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
*/
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
}
```
Note that it is not required to use PHP DOM, DOMDocument, DOMXPath, or dom\_import\_simplexml().
```
//this is a recursively option
do {
$removed = false;
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
$removed = true;
}
} while ($removed) ;
``` |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | You can use [XPath](http://docs.php.net/DOMXPath) with the [predicate](http://www.w3.org/TR/xpath/#predicates) `not(node())` to select all elements that do not have child nodes.
```
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml('<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
</parentnode>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//*[not(node())]') as $node ) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();
```
prints
```
<?xml version="1.0"?>
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag2>4</tag2>
<tag2>4</tag2>
</parentnode>
``` | If you're going to be a lot of this, just do something like:
```
$value[] = "2";
$value[] = "4";
$value[] = "";
$xml = '<parentnode>';
for($i=1,$m=count($value); $i<$m+1; $i++)
$xml .= !empty($value[$i-1]) ? "<tag{$i}>{$value[$i-1]}</tag{$i}>" : null;
$xml .= '</parentnode>';
echo $xml;
```
Ideally though, you should probably use [domdocument](http://php.net/manual/en/domdocument.createelement.php). |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | The solution that worked with my production PHP SimpleXMLElement object code, by using Xpath, was:
```
/*
* Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
* This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
*/
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
}
```
Note that it is not required to use PHP DOM, DOMDocument, DOMXPath, or dom\_import\_simplexml().
```
//this is a recursively option
do {
$removed = false;
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
$removed = true;
}
} while ($removed) ;
``` | If you're going to be a lot of this, just do something like:
```
$value[] = "2";
$value[] = "4";
$value[] = "";
$xml = '<parentnode>';
for($i=1,$m=count($value); $i<$m+1; $i++)
$xml .= !empty($value[$i-1]) ? "<tag{$i}>{$value[$i-1]}</tag{$i}>" : null;
$xml .= '</parentnode>';
echo $xml;
```
Ideally though, you should probably use [domdocument](http://php.net/manual/en/domdocument.createelement.php). |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | This works recursively and removes nodes that:
* contain only spaces
* do not have attributes
* do not have child notes
```
// not(*) does not have children elements
// not(@*) does not have attributes
// text()[normalize-space()] nodes that include whitespace text
while (($node_list = $xpath->query('//*[not(*) and not(@*) and not(text()[normalize-space()])]')) && $node_list->length) {
foreach ($node_list as $node) {
$node->parentNode->removeChild($node);
}
}
``` | If you're going to be a lot of this, just do something like:
```
$value[] = "2";
$value[] = "4";
$value[] = "";
$xml = '<parentnode>';
for($i=1,$m=count($value); $i<$m+1; $i++)
$xml .= !empty($value[$i-1]) ? "<tag{$i}>{$value[$i-1]}</tag{$i}>" : null;
$xml .= '</parentnode>';
echo $xml;
```
Ideally though, you should probably use [domdocument](http://php.net/manual/en/domdocument.createelement.php). |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | You can use [XPath](http://docs.php.net/DOMXPath) with the [predicate](http://www.w3.org/TR/xpath/#predicates) `not(node())` to select all elements that do not have child nodes.
```
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml('<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
</parentnode>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//*[not(node())]') as $node ) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();
```
prints
```
<?xml version="1.0"?>
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag2>4</tag2>
<tag2>4</tag2>
</parentnode>
``` | The solution that worked with my production PHP SimpleXMLElement object code, by using Xpath, was:
```
/*
* Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
* This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
*/
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
}
```
Note that it is not required to use PHP DOM, DOMDocument, DOMXPath, or dom\_import\_simplexml().
```
//this is a recursively option
do {
$removed = false;
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
$removed = true;
}
} while ($removed) ;
``` |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | You can use [XPath](http://docs.php.net/DOMXPath) with the [predicate](http://www.w3.org/TR/xpath/#predicates) `not(node())` to select all elements that do not have child nodes.
```
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml('<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
<tag2>4</tag2>
<tag3></tag3>
</parentnode>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//*[not(node())]') as $node ) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();
```
prints
```
<?xml version="1.0"?>
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag2>4</tag2>
<tag2>4</tag2>
</parentnode>
``` | This works recursively and removes nodes that:
* contain only spaces
* do not have attributes
* do not have child notes
```
// not(*) does not have children elements
// not(@*) does not have attributes
// text()[normalize-space()] nodes that include whitespace text
while (($node_list = $xpath->query('//*[not(*) and not(@*) and not(text()[normalize-space()])]')) && $node_list->length) {
foreach ($node_list as $node) {
$node->parentNode->removeChild($node);
}
}
``` |
8,603,259 | I've got a question about the facebook graph api.
I have a example facebook page: <https://www.facebook.com/pages/TheBestCompany/250721784993387>
And i want to get the images from all the people that liked that page.
I've found on this site that it is **not** possible to find the people that liked a external page. but thats not the case?
I hope to hear from you people:) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111460/"
] | This works recursively and removes nodes that:
* contain only spaces
* do not have attributes
* do not have child notes
```
// not(*) does not have children elements
// not(@*) does not have attributes
// text()[normalize-space()] nodes that include whitespace text
while (($node_list = $xpath->query('//*[not(*) and not(@*) and not(text()[normalize-space()])]')) && $node_list->length) {
foreach ($node_list as $node) {
$node->parentNode->removeChild($node);
}
}
``` | The solution that worked with my production PHP SimpleXMLElement object code, by using Xpath, was:
```
/*
* Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
* This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
*/
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
}
```
Note that it is not required to use PHP DOM, DOMDocument, DOMXPath, or dom\_import\_simplexml().
```
//this is a recursively option
do {
$removed = false;
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
$removed = true;
}
} while ($removed) ;
``` |
63,860,763 | In case the customer pays online (using for example PayPal) the WooCommerce creates order and then wait for the payment. This "waiting" is order status `pending`. No stock is being reduced during this period which is very bad. The stock is reduced after the succesfull payment by changing the order status to `on-hold`. But sometimes the payment can take up 30minutes and during these 30minutes the order keeps in `pending` status and the stock is not reduced, therefore if its a last piece of a product on stock, it is still available during this period. Therefore if I have only 1-3 pieces of each product on stock, there is a big possibility, that if I will have only one last piece of a product on stock, someone else will come and buy it during these 30 minutes, which leads to situation, where the last piece can be sold twice, which is inacceptible. Therefore I need to reduce the stock immediately after creating any order with any type of payment and any type of shipping. Therefore I tried to create a snippet, which will use a hook `woocommerce_order_status_changed` and it should reduce the stock always when the order status changed to `pending`, because `pending` status does not reduces the stock. I do not know if this is the right attitude how to solve it. Could anyone help pls? I tried these two snippets, but without any changes of behaviour:
```
add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );
function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
if ( $order->has_status( 'pending' )) {
$reduce_stock = true;
}
return $reduce_stock;
}
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
```
```
add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
if ( $new_status == 'pending'){
$stock_reduced = get_post_meta( $order_id, '_order_stock_reduced', true );
if( empty($stock_reduced) && $order->get_payment_method() == 'barion' ){
wc_reduce_stock_levels($order_id);
}
}
}
``` | 2020/09/12 | [
"https://Stackoverflow.com/questions/63860763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13681589/"
] | You can simply add the following code line to allow stock to be reduced on pending order status *(WooCommerce will do the job triggering [the function `wc_maybe_reduce_stock_levels()`](https://github.com/woocommerce/woocommerce/blob/4.5.1/includes/wc-stock-functions.php#L79-L108) on pending orders*):
```
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
```
Code goes in functions.php file of your active child theme (or active theme). It should works. | Well this is the only working solution I found now:
```
add_action( 'woocommerce_checkout_create_order', 'force_new_order_status', 20, 1 );
function force_new_order_status( $order )
{
if( ! $order->has_status('on-hold') )
$order->set_status( 'on-hold', 'Forced status by a custom script (this note is not neccessary and can be deleted)' );
}
```
There is only one problem: in case of failed payment the stock is not getting back. Therefore there must be another action made like automatic cancelling of non-paid orders after (for example) 60mins, or use specific hook(s) from the payment gateway.
Anyway what I have learned today, that there is a massive difference between `set_status` and `update_status`. Beginners like me, beware! :-)
So this way I switch every new order made by WooCommerce automatically in `pending` state (which is not reducing the ordered stock) to `on-hold` state (which does reducing the ordered stock) which is working solution to my problem. Maybe too easy for advanced programmers but because I did not find correct working solution of my question for two days of searching, I am posting it even it is so trivial to save another beginner's time, because as I found during searching: I am not the only one who needs to reduce the stock immediately when the order is made. So this is the way! :-) |
63,860,763 | In case the customer pays online (using for example PayPal) the WooCommerce creates order and then wait for the payment. This "waiting" is order status `pending`. No stock is being reduced during this period which is very bad. The stock is reduced after the succesfull payment by changing the order status to `on-hold`. But sometimes the payment can take up 30minutes and during these 30minutes the order keeps in `pending` status and the stock is not reduced, therefore if its a last piece of a product on stock, it is still available during this period. Therefore if I have only 1-3 pieces of each product on stock, there is a big possibility, that if I will have only one last piece of a product on stock, someone else will come and buy it during these 30 minutes, which leads to situation, where the last piece can be sold twice, which is inacceptible. Therefore I need to reduce the stock immediately after creating any order with any type of payment and any type of shipping. Therefore I tried to create a snippet, which will use a hook `woocommerce_order_status_changed` and it should reduce the stock always when the order status changed to `pending`, because `pending` status does not reduces the stock. I do not know if this is the right attitude how to solve it. Could anyone help pls? I tried these two snippets, but without any changes of behaviour:
```
add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );
function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
if ( $order->has_status( 'pending' )) {
$reduce_stock = true;
}
return $reduce_stock;
}
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
```
```
add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
if ( $new_status == 'pending'){
$stock_reduced = get_post_meta( $order_id, '_order_stock_reduced', true );
if( empty($stock_reduced) && $order->get_payment_method() == 'barion' ){
wc_reduce_stock_levels($order_id);
}
}
}
``` | 2020/09/12 | [
"https://Stackoverflow.com/questions/63860763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13681589/"
] | You can simply add the following code line to allow stock to be reduced on pending order status *(WooCommerce will do the job triggering [the function `wc_maybe_reduce_stock_levels()`](https://github.com/woocommerce/woocommerce/blob/4.5.1/includes/wc-stock-functions.php#L79-L108) on pending orders*):
```
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
```
Code goes in functions.php file of your active child theme (or active theme). It should works. | You need to add stock reducing hook (as LoicTheAztec already answered), but you need to also remove the opposite wc\_maybe\_increase\_stock\_levels hook too. To remove it correctly, you need to run it when it is already hooked, so you need to wrap it into init hook.
**Following works for me (Woocommerce 5.4.1) - ensure the Pending status reduce stock levels:**
```
add_action( 'init', function() {
add_action('woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels');
remove_action('woocommerce_order_status_pending', 'wc_maybe_increase_stock_levels');
});
``` |
63,860,763 | In case the customer pays online (using for example PayPal) the WooCommerce creates order and then wait for the payment. This "waiting" is order status `pending`. No stock is being reduced during this period which is very bad. The stock is reduced after the succesfull payment by changing the order status to `on-hold`. But sometimes the payment can take up 30minutes and during these 30minutes the order keeps in `pending` status and the stock is not reduced, therefore if its a last piece of a product on stock, it is still available during this period. Therefore if I have only 1-3 pieces of each product on stock, there is a big possibility, that if I will have only one last piece of a product on stock, someone else will come and buy it during these 30 minutes, which leads to situation, where the last piece can be sold twice, which is inacceptible. Therefore I need to reduce the stock immediately after creating any order with any type of payment and any type of shipping. Therefore I tried to create a snippet, which will use a hook `woocommerce_order_status_changed` and it should reduce the stock always when the order status changed to `pending`, because `pending` status does not reduces the stock. I do not know if this is the right attitude how to solve it. Could anyone help pls? I tried these two snippets, but without any changes of behaviour:
```
add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );
function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
if ( $order->has_status( 'pending' )) {
$reduce_stock = true;
}
return $reduce_stock;
}
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
```
```
add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
if ( $new_status == 'pending'){
$stock_reduced = get_post_meta( $order_id, '_order_stock_reduced', true );
if( empty($stock_reduced) && $order->get_payment_method() == 'barion' ){
wc_reduce_stock_levels($order_id);
}
}
}
``` | 2020/09/12 | [
"https://Stackoverflow.com/questions/63860763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13681589/"
] | Well this is the only working solution I found now:
```
add_action( 'woocommerce_checkout_create_order', 'force_new_order_status', 20, 1 );
function force_new_order_status( $order )
{
if( ! $order->has_status('on-hold') )
$order->set_status( 'on-hold', 'Forced status by a custom script (this note is not neccessary and can be deleted)' );
}
```
There is only one problem: in case of failed payment the stock is not getting back. Therefore there must be another action made like automatic cancelling of non-paid orders after (for example) 60mins, or use specific hook(s) from the payment gateway.
Anyway what I have learned today, that there is a massive difference between `set_status` and `update_status`. Beginners like me, beware! :-)
So this way I switch every new order made by WooCommerce automatically in `pending` state (which is not reducing the ordered stock) to `on-hold` state (which does reducing the ordered stock) which is working solution to my problem. Maybe too easy for advanced programmers but because I did not find correct working solution of my question for two days of searching, I am posting it even it is so trivial to save another beginner's time, because as I found during searching: I am not the only one who needs to reduce the stock immediately when the order is made. So this is the way! :-) | You need to add stock reducing hook (as LoicTheAztec already answered), but you need to also remove the opposite wc\_maybe\_increase\_stock\_levels hook too. To remove it correctly, you need to run it when it is already hooked, so you need to wrap it into init hook.
**Following works for me (Woocommerce 5.4.1) - ensure the Pending status reduce stock levels:**
```
add_action( 'init', function() {
add_action('woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels');
remove_action('woocommerce_order_status_pending', 'wc_maybe_increase_stock_levels');
});
``` |
7,896 | I have a problem with a sentence "A list of items grouped by category".
There are two possible ways to understand this sentence:
1. (A list of items) that is grouped by category
2. A list of (items that are grouped by category)
How to write it correctly? | 2011/01/03 | [
"https://english.stackexchange.com/questions/7896",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/2312/"
] | This is indeed a classic. The question has been asked many times around the web, and there appear to be two schools: one that agrees with you, and one that thinks both constructions are acceptable and interprets both as 15 sweets. I think those people are nuts, but, hey, they might be the majority. I say, why use a construction that is either illogical or ambiguous when you have a perfectly good alternative? But language isn't logical, especially not idiom, so I suppose I cannot call my argument objective. I think "3 times more" as 15 sweets total is acceptable to most people, though I'd never use it. You will even see it in newspapers. The exact same problem exists in Dutch, with the same sides to choose between. | A recent article from the OpenSecrets.org website bears the headline “[Dark Money Spending Three Times More Than at Same Time in 2012 Cycle, CRP Testifies](https://www.opensecrets.org/news/2014/04/dark-money-spending-three-times-more-than-at-same-time-in-2012-cycle-crp-testifies/)” (April 30, 2014). A graph in the [actual CRP document](https://www.documentcloud.org/documents/1150286-kingtestimonymerged1.html) (“Exhibit 2,” on page 9 of the submitted testimony) identifies the relevant figures as being slightly more than $4 million in 2012 (“to date”) and slightly more than $12 million in 2014 (“to date”). Clearly the headline writer considers “three times more than” to be synonymous with “three times as much as.” The main text of the testimony (on page 3) evinces a similar understanding in describing the difference between the two figures:
>
> As of April 29 in the current cycle, despite this being a midterm election, spending by nondisclosing groups is nearly **three times higher than** it was at the same point in 2012, totaling $12.3 million compared to $4.4 million in the same point in 2012.
>
>
>
It seems to me that many writers and speakers of English are inclined to use "X times more than" and "X times as much as" interchangeably and to interpret them as being equivalent. But in a paper titled “[Common Errors in Forming Arithmetic Comparisons](http://web.augsburg.edu/~schield/MiloPapers/984OfSigCompare3.pdf),” Professor Milo Schield of Augsburg College in Minneapolis, Minnesota, treats this understanding as a common error:
>
> *Confusing ‘times as much’ with ‘times more than’.* If B is three times as much as A, then B is two times more than A — not three times more than A. The essential feature is the difference is between ‘as much as’ and ‘more than’. ‘As much as’ indicates a ratio; ‘more than’ indicates a difference. ‘More than’ means ‘added to the base’. This essential difference is ignored by those who say that ‘times’ is dominant so that ‘three times as much’ is really the same as ‘three times more than’.
>
>
>
Of course, the fact that “more than” indicates a difference doesn’t alter the fact that “times more than” indicates a ratio of a certain kind. The real question is whether people understand the ratio implied by “times more than” to compare the entire amount of the larger quantity to the smaller quantity or whether they understand it to compare only the difference between the larger and smaller quantities to the smaller quantity.
Historically, at least one fairly early text supports Professor Schield’s distinction. From a 1657 translation of Voltaire’s [*The General History and State of Europe*](http://books.google.com/books?id=YpBJAAAAYAAJ&pg=PA155&dq=%22times+more+than%22&hl=en&sa=X&ei=GfjXU-j7JO3BiwLbg4Fw&ved=0CDQQ6AEwBDgK#v=onepage&q=%22times%20more%20than%22&f=false), Part V:
>
> The farmers of those alienated duties plundered the people of **four times more than** their demand amounted to ; and when at length the general depredation obliged Henry IV, to give the intire administration of the finances to the duke de Sully, this able and upright minister found that in the year 1596, they raised about a hundred and fifty millions of livres on the people, to bring about thirty into the Exchequer.
>
>
>
In this example, Voltaire observes that 150 million is four times more than 30 million, though it is also clearly five times as much as 30 million.
In my view, if substantial numbers of English speakers and readers have conflicting understandings of the two terms—some taking the position that “X times as much as” and “X times more than” refer to equivalent ratios, and others adopting Professor Schield's view that the two ratios involved differ fundamentally—a writer who doesn’t want to be misunderstood by some significant portion of readers might do well to avoid ever using the potentially ambiguous phrase “X times more than,” especially since any such ratio is easy to recast (and recalculate, if necessary) as an unambiguous “X times as much as” ratio. |
25,843,418 | I have a file input with multiple attribute
I want when user select multiple file in this control split those files
and create multiple file input with each one having only one of those files selected.
This allow a user to select multiple files at once but delete them individually if he wants.
Beside i want to ajax upload those files one by one while allowing user to cancel any of
those file being uploaded.
any idea. | 2014/09/15 | [
"https://Stackoverflow.com/questions/25843418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4022919/"
] | You can use one of the free jQuery plugins available.
[jQuery File Upload Demo](http://blueimp.github.io/jQuery-File-Upload/index.html)
[Uplodify](http://www.uploadify.com/) | You cannot set the "files" or "value" attribute on a file input - therefore you can't just create new file inputs and fill them with one file each. But you can use the new HTML5 FormData object to upload each file separately. So you just display the original file input's "files" attribute as a list. The user can de-select the indices. When he submits you can iterate the files attribute and skip the de-selected indices.
See <https://stackoverflow.com/a/24089581/4809444> |
40,654,046 | I want to ask about for each
here's my HTML
```
<select class="namaKota" id="fromCity"></select>
```
my data in js
```
var listCity =
{
"Popular":
[
{"cityname":"London","code":"LDN"},
{"cityname":"Rome","code":"ROM"},
{"cityname":"Madrid","code":"MDR"}
],
"Germany":
[
{"cityname":"Hamburg", "code":"HMB"},
{"cityname":"Frankfurt", "code":"FRN"}
]
}
```
and here's my JS
```
var a = $("select#fromCity").val();
listKota.forEach(function(e){
a.append('<option value="'+ listCity.code +'">'+ listCity.cityname +'</option>');});
```
I want be like this image. How can I create using for each?
[](https://i.stack.imgur.com/Usp4c.png)
Here's my jsfiddle. <https://jsfiddle.net/dedi_wibisono17/9u9uec8d/1/> Anybody help? Thankyou | 2016/11/17 | [
"https://Stackoverflow.com/questions/40654046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5361782/"
] | The layout you have in your image uses `<optgroup>` elements to group the `<option>`. Therefore you need two loops; one to create the `optgroups` from the keys of the object, and another to populate the actual `option` within those groups. Try this:
```js
var listCity = {
"Popular": [
{ "cityname": "London", "code": "LDN" },
{ "cityname": "Rome", "code": "ROM" },
{ "cityname": "Madrid", "code": "MDR" }
],
"Germany": [
{ "cityname": "Hamburg", "code": "HMB" },
{ "cityname": "Frankfurt", "code": "FRN" }
]
}
Object.keys(listCity).forEach(function(key) {
var $group = $('<optgroup label="' + key + '"></optgroup>');
listCity[key].forEach(function(obj) {
$group.append('<option value="' + obj.code + '">' + obj.cityname + '</option>')
})
$('#fromCity').append($group);
})
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="fromCity"></select>
``` | You need to create `optGroup` element with `option` element which needs to be added `select` element.
```
var select = $("select#fromCity");
//Iterate list City
for (var key in listCity) {
var cities = listCity[key];
//Create optGroup
var optGroup = $('<optgroup/>', {
label: key
})
for (var i = 0; i < cities.length; i++) {
//Create option and append to optGroup created above
$('<option>', {
value: cities[i].code,
text: cities[i].cityname,
}).appendTo(optGroup);
}
optGroup.appendTo(select);
}
```
```js
var listCity = {
"Popular": [
{ "cityname": "London", "code": "LDN" },
{ "cityname": "Rome", "code": "ROM" },
{ "cityname": "Madrid", "code": "MDR" }
],
"Germany": [
{ "cityname": "Hamburg", "code": "HMB" },
{ "cityname": "Frankfurt", "code": "FRN" }
]
}
var select = $("select#fromCity");
//Iterate list City
for (var key in listCity) {
var cities = listCity[key];
//Create optGroup
var optGroup = $('<optgroup/>', {
label: key
})
for (var i = 0; i < cities.length; i++) {
//Create option and append to optGroup created above
$('<option>', {
value: cities[i].code,
text: cities[i].cityname,
}).appendTo(optGroup);
}
optGroup.appendTo(select);
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="fromCity"></select>
```
[**Updated Fiddle**](https://jsfiddle.net/4urrxzzp/1/) |
22,061,417 | Getting these errors when attempting to post stuff to a database from a form:
```
Notice: Undefined index: formUser in /Applications/MAMP/htdocs/Crewniverse/index.php on line 49
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /Applications/MAMP/htdocs/Crewniverse/index.php on line 49
Notice: Undefined index: formPass in /Applications/MAMP/htdocs/Crewniverse/index.php on line 50
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /Applications/MAMP/htdocs/Crewniverse/index.php on line 50
```
Code is:
```
<?php
$dbServer = "localhost";
$db = "Crewniverse";
$dbUser = "url_acc";
$dbPassword = "url_pass";
$db_connect = mysqli_connect("localhost", "url_acc", "url_pass", "Crewniverse");
//evaluate the connection
if (mysqli_connect_error()) {
echo mysqli_connect_error();
die("<br>Couldn't connect!");
}
$formUser=mysqli_real_escape_string($_POST['formUser']);
$formPass=mysqli_real_escape_string($_POST['formPass']);
if(isset($_POST['submit']))
{
$sql="INSERT INTO username_pass (formUser, formPass)VALUES('$formUser', '$formPass')";
$result=mysql_query($sql) or die ('error Updating database');
}
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='index.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
``` | 2014/02/27 | [
"https://Stackoverflow.com/questions/22061417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2766253/"
] | Obviously it will create only 2 tow when size is 4,
when size is 6 it will create 3 row. remove it statement from loop if you want to
create rows equal to number if size | remove if statements from loop and create rows normally.
change your loop with this
for (int arrayCounter = 0; arrayCounter < (documentList.size()/2); arrayCounter++)
and for last row you can have if statement which will compare
if (documentList.size()/2)-1 == arrayCounter).. then
you will get what you are looking for
else
for (int arrayCounter = 0; arrayCounter < documentList.size(); arrayCounter++) {
```
if (documentList.size()/2)-1 == arrayCounter){ create 1 row}else{
create 1st row and then arraycounter ++
create 2nd row and then arraycounter ++
```
}
} |
22,061,417 | Getting these errors when attempting to post stuff to a database from a form:
```
Notice: Undefined index: formUser in /Applications/MAMP/htdocs/Crewniverse/index.php on line 49
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /Applications/MAMP/htdocs/Crewniverse/index.php on line 49
Notice: Undefined index: formPass in /Applications/MAMP/htdocs/Crewniverse/index.php on line 50
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /Applications/MAMP/htdocs/Crewniverse/index.php on line 50
```
Code is:
```
<?php
$dbServer = "localhost";
$db = "Crewniverse";
$dbUser = "url_acc";
$dbPassword = "url_pass";
$db_connect = mysqli_connect("localhost", "url_acc", "url_pass", "Crewniverse");
//evaluate the connection
if (mysqli_connect_error()) {
echo mysqli_connect_error();
die("<br>Couldn't connect!");
}
$formUser=mysqli_real_escape_string($_POST['formUser']);
$formPass=mysqli_real_escape_string($_POST['formPass']);
if(isset($_POST['submit']))
{
$sql="INSERT INTO username_pass (formUser, formPass)VALUES('$formUser', '$formPass')";
$result=mysql_query($sql) or die ('error Updating database');
}
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='index.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
``` | 2014/02/27 | [
"https://Stackoverflow.com/questions/22061417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2766253/"
] | Obviously it will create only 2 tow when size is 4,
when size is 6 it will create 3 row. remove it statement from loop if you want to
create rows equal to number if size | Don't use scriptlets in jsp, Jsp is is view layer, use as a view. there is servlet/java-beans to put your all java code.
There is jstl taglib, which has many inbuild functions, use it. you can get it from [here](http://mvnrepository.com/artifact/jstl/jstl/1.2)
In your case to loop over a list do like this:
* Add jstl library to your classpath
* First import jstl taglib in top of your jsp.
* Then you have jstl tags to use in your jsp.
To import jstl in jsp do like:
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
```
for looping a `List` in jstl, there is `c:forEach` tag, you can use it like:
```
<c:forEach items="${documentList}" var="doc">
//here you can access one element by doc like: ${doc}
</c:forEach>
```
If you want to generate table rows, for each documentList element, then do like:
```
<table width="89%" style="margin-left:30px;">
<c:forEach items="${documentList}" var="doc" varStatus="loop">
<tr>
<td style="width:2%">
//here if you want loop index you can get like: ${loop.index}
</td>
<td style="width:20%;align:left;">
//if you want to display some property of doc then do like: ${doc.someProperty},
jstl will call getter method of someProperty to get the value.
</td>
<td style="width:30%;align:left;">
</td>
</tr>
</c:forEach>
</table>
```
read more [here](https://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files?rq=1) for how to avoid java code in jsp. |
33,130,554 | I can easily write a little parse program to do this task, but I just know that some linux command line tool guru can teach me something new here. I've pulled apart a bunch of files to gather some data within such that I can create a table with it. The data is presently in the format:
```
.serviceNum=6360,
.transportId=1518,
.suid=6360,
.serviceNum=6361,
.transportId=1518,
.suid=6361,
.serviceNum=6362,
.transportId=1518,
.suid=6362,
.serviceNum=6359,
.transportId=1518,
.suid=6359,
.serviceNum=203,
.transportId=117,
.suid=20203,
.serviceNum=9436,
.transportId=919,
.suid=16294,
.serviceNum=9524,
.transportId=906,
.suid=17613,
.serviceNum=9439,
.transportId=917,
.suid=9439,
```
What I would like is this:
```
.serviceNum=6360,.transportId=1518,.suid=6360,
.serviceNum=6361,.transportId=1518,.suid=6361,
.serviceNum=6362,.transportId=1518,.suid=6362,
.serviceNum=6359,.transportId=1518,.suid=6359,
.serviceNum=203,.transportId=117,.suid=20203,
.serviceNum=9436,.transportId=919,.suid=16294,
.serviceNum=9524,.transportId=906,.suid=17613,
.serviceNum=9439,.transportId=917,.suid=9439,
```
So, the question is, is there a linux command line tool that will somehow read through the file and auto remove the EOL/CR on the end of every 2nd and 3rd line? I've seen old school linux gurus do incredible things on the command line and this is one of those instances where I think it's worth my time to inquire. :)
TIA
O | 2015/10/14 | [
"https://Stackoverflow.com/questions/33130554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5445938/"
] | Perl to the rescue:
```
perl -pe 'chomp if $. % 3' < input
```
* `-p` processes the input line by line printing each line;
* [chomp](http://p3rl.org/chomp) removes the final newline;
* [$.](http://p3rl.org/perlvar#%24NR) contains the input line number;
* `%` is the modulo operator. | ```
perl -alne '$a.=$_; if($.%3==0){print $a; $a=""}' filename
``` |
33,130,554 | I can easily write a little parse program to do this task, but I just know that some linux command line tool guru can teach me something new here. I've pulled apart a bunch of files to gather some data within such that I can create a table with it. The data is presently in the format:
```
.serviceNum=6360,
.transportId=1518,
.suid=6360,
.serviceNum=6361,
.transportId=1518,
.suid=6361,
.serviceNum=6362,
.transportId=1518,
.suid=6362,
.serviceNum=6359,
.transportId=1518,
.suid=6359,
.serviceNum=203,
.transportId=117,
.suid=20203,
.serviceNum=9436,
.transportId=919,
.suid=16294,
.serviceNum=9524,
.transportId=906,
.suid=17613,
.serviceNum=9439,
.transportId=917,
.suid=9439,
```
What I would like is this:
```
.serviceNum=6360,.transportId=1518,.suid=6360,
.serviceNum=6361,.transportId=1518,.suid=6361,
.serviceNum=6362,.transportId=1518,.suid=6362,
.serviceNum=6359,.transportId=1518,.suid=6359,
.serviceNum=203,.transportId=117,.suid=20203,
.serviceNum=9436,.transportId=919,.suid=16294,
.serviceNum=9524,.transportId=906,.suid=17613,
.serviceNum=9439,.transportId=917,.suid=9439,
```
So, the question is, is there a linux command line tool that will somehow read through the file and auto remove the EOL/CR on the end of every 2nd and 3rd line? I've seen old school linux gurus do incredible things on the command line and this is one of those instances where I think it's worth my time to inquire. :)
TIA
O | 2015/10/14 | [
"https://Stackoverflow.com/questions/33130554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5445938/"
] | Use cat and paste and see the magic
```
cat inputfile.txt | paste - - -
``` | Perl to the rescue:
```
perl -pe 'chomp if $. % 3' < input
```
* `-p` processes the input line by line printing each line;
* [chomp](http://p3rl.org/chomp) removes the final newline;
* [$.](http://p3rl.org/perlvar#%24NR) contains the input line number;
* `%` is the modulo operator. |
33,130,554 | I can easily write a little parse program to do this task, but I just know that some linux command line tool guru can teach me something new here. I've pulled apart a bunch of files to gather some data within such that I can create a table with it. The data is presently in the format:
```
.serviceNum=6360,
.transportId=1518,
.suid=6360,
.serviceNum=6361,
.transportId=1518,
.suid=6361,
.serviceNum=6362,
.transportId=1518,
.suid=6362,
.serviceNum=6359,
.transportId=1518,
.suid=6359,
.serviceNum=203,
.transportId=117,
.suid=20203,
.serviceNum=9436,
.transportId=919,
.suid=16294,
.serviceNum=9524,
.transportId=906,
.suid=17613,
.serviceNum=9439,
.transportId=917,
.suid=9439,
```
What I would like is this:
```
.serviceNum=6360,.transportId=1518,.suid=6360,
.serviceNum=6361,.transportId=1518,.suid=6361,
.serviceNum=6362,.transportId=1518,.suid=6362,
.serviceNum=6359,.transportId=1518,.suid=6359,
.serviceNum=203,.transportId=117,.suid=20203,
.serviceNum=9436,.transportId=919,.suid=16294,
.serviceNum=9524,.transportId=906,.suid=17613,
.serviceNum=9439,.transportId=917,.suid=9439,
```
So, the question is, is there a linux command line tool that will somehow read through the file and auto remove the EOL/CR on the end of every 2nd and 3rd line? I've seen old school linux gurus do incredible things on the command line and this is one of those instances where I think it's worth my time to inquire. :)
TIA
O | 2015/10/14 | [
"https://Stackoverflow.com/questions/33130554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5445938/"
] | Use cat and paste and see the magic
```
cat inputfile.txt | paste - - -
``` | ```
perl -alne '$a.=$_; if($.%3==0){print $a; $a=""}' filename
``` |
10,755,197 | I have this script which fires scrolling to next/prev when "N" and "P" keys on keyboard are pressed. My question is how to stop this from firing when the user type these letters normally in any form (such as search field, login field, and so on.) because when I press n e.g. John in a form it does not write N instead it fires the scroll function. How to fix that behaviour?
My code is below:
```
$(document).keydown(function (evt) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
});
```
Thank you. | 2012/05/25 | [
"https://Stackoverflow.com/questions/10755197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385112/"
] | The event object has a `target` property which tells you where the event actually occurred (after which it bubbled up to your document-level handler). So you can test `evt.target` against form field elements and, if it's a match, don't do your special logic.
Probably the easiest way to do that is to use [`closest`](http://api.jquery.com/closest), e.g.:
```
$(document).keydown(function (evt) {
if (!$(evt.target).closest('input, select, textarea')[0]) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
}
});
```
There I'm asking what the closest form field is starting with the element (since `closest` starts with the element you give it) and working up through ancestors. If there are non, then the returned jQuery object will be empty, and `[0]` will return `undefined`. So since `!undefined` is `true`, we'll process your logic when *not* in a form field. | I think something like
```
$('form').on('keydown', function(event) {event.stopPropagation();});
```
should do the trick if you don't need keyboard controls from inside of a form. |
10,755,197 | I have this script which fires scrolling to next/prev when "N" and "P" keys on keyboard are pressed. My question is how to stop this from firing when the user type these letters normally in any form (such as search field, login field, and so on.) because when I press n e.g. John in a form it does not write N instead it fires the scroll function. How to fix that behaviour?
My code is below:
```
$(document).keydown(function (evt) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
});
```
Thank you. | 2012/05/25 | [
"https://Stackoverflow.com/questions/10755197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385112/"
] | The event object has a `target` property which tells you where the event actually occurred (after which it bubbled up to your document-level handler). So you can test `evt.target` against form field elements and, if it's a match, don't do your special logic.
Probably the easiest way to do that is to use [`closest`](http://api.jquery.com/closest), e.g.:
```
$(document).keydown(function (evt) {
if (!$(evt.target).closest('input, select, textarea')[0]) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
}
});
```
There I'm asking what the closest form field is starting with the element (since `closest` starts with the element you give it) and working up through ancestors. If there are non, then the returned jQuery object will be empty, and `[0]` will return `undefined`. So since `!undefined` is `true`, we'll process your logic when *not* in a form field. | Use the `target` property of the [`Event` object](https://developer.mozilla.org/en/DOM/event), which points to the source DOM node. So, you could easily use
```
var nn = evt.target.nodeName.toLowerCase();
if (nn != "input" && nn != "textarea")
// do your special handling
```
but it might be easier to check for existance of the [`form` property](http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#dom-fae-form), which points to elements owner form:
```
if (! "form" in evt.target)
// do your special handling
``` |
15,684,402 | So I have this simple if loop
```
chick<-lapply(1:length(t),function(i){
if(t[[i]]<0.01){
chick=1
}else 0
})
```
So basically when t<0.01 it print outs 1 if not it prints 0 but there are times when I have data that has NA values like the one below....how can I assign the NA values 0 as well coz I'll get an error similar to this if I dont:
```
Error in if (t[[i]] < 0.01) { : missing value where TRUE/FALSE needed
```
Here is a sample output from data called 't'
```
[[1]]
[1] NA
[[2]]
[1] NA
[[3]]
[1] 0.01
```
thanks again | 2013/03/28 | [
"https://Stackoverflow.com/questions/15684402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214558/"
] | use `is.na`
```
if(t[!is.na(t)][[i]]<0.01) ...
```
---
More importatnly though, since you are assigning to `chick`, do not try to also assign inside your `lapply` (or similar) statement. It will give you results different from what you are expecting. Instead try
```
chick <- lapply(1:length(t),function(i)
if(t[!is.na(t)][[i]]<0.01) 1 else 0
)
```
Or better yet, use ifelse.
```
chick <- ifelse(t[!is.na(t)] < 0.01, 1, 0)
```
If you want `chick` to be the same length as `t`, then use the '|' operator in ifelse. as suggested by NPE (but use single `|` not `||` in `ifelse`) | The following with check whether `t[[i]]` is either `NA` or less than `0.01`:
```
if (is.na(t[[i]]) || t[[i]] < 0.01) {
....
``` |
15,684,402 | So I have this simple if loop
```
chick<-lapply(1:length(t),function(i){
if(t[[i]]<0.01){
chick=1
}else 0
})
```
So basically when t<0.01 it print outs 1 if not it prints 0 but there are times when I have data that has NA values like the one below....how can I assign the NA values 0 as well coz I'll get an error similar to this if I dont:
```
Error in if (t[[i]] < 0.01) { : missing value where TRUE/FALSE needed
```
Here is a sample output from data called 't'
```
[[1]]
[1] NA
[[2]]
[1] NA
[[3]]
[1] 0.01
```
thanks again | 2013/03/28 | [
"https://Stackoverflow.com/questions/15684402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214558/"
] | use `is.na`
```
if(t[!is.na(t)][[i]]<0.01) ...
```
---
More importatnly though, since you are assigning to `chick`, do not try to also assign inside your `lapply` (or similar) statement. It will give you results different from what you are expecting. Instead try
```
chick <- lapply(1:length(t),function(i)
if(t[!is.na(t)][[i]]<0.01) 1 else 0
)
```
Or better yet, use ifelse.
```
chick <- ifelse(t[!is.na(t)] < 0.01, 1, 0)
```
If you want `chick` to be the same length as `t`, then use the '|' operator in ifelse. as suggested by NPE (but use single `|` not `||` in `ifelse`) | Or you could just use...
```
chick <- numeric( length(t) )
chick[ t < 0.01 ] <- 1
```
... and avoid loops and checking for NA altogether. |
15,684,402 | So I have this simple if loop
```
chick<-lapply(1:length(t),function(i){
if(t[[i]]<0.01){
chick=1
}else 0
})
```
So basically when t<0.01 it print outs 1 if not it prints 0 but there are times when I have data that has NA values like the one below....how can I assign the NA values 0 as well coz I'll get an error similar to this if I dont:
```
Error in if (t[[i]] < 0.01) { : missing value where TRUE/FALSE needed
```
Here is a sample output from data called 't'
```
[[1]]
[1] NA
[[2]]
[1] NA
[[3]]
[1] 0.01
```
thanks again | 2013/03/28 | [
"https://Stackoverflow.com/questions/15684402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214558/"
] | use `is.na`
```
if(t[!is.na(t)][[i]]<0.01) ...
```
---
More importatnly though, since you are assigning to `chick`, do not try to also assign inside your `lapply` (or similar) statement. It will give you results different from what you are expecting. Instead try
```
chick <- lapply(1:length(t),function(i)
if(t[!is.na(t)][[i]]<0.01) 1 else 0
)
```
Or better yet, use ifelse.
```
chick <- ifelse(t[!is.na(t)] < 0.01, 1, 0)
```
If you want `chick` to be the same length as `t`, then use the '|' operator in ifelse. as suggested by NPE (but use single `|` not `||` in `ifelse`) | Why not just this (invert the test and return 0 for the complementary test as well as for NA):
```
chick <- ifelse(is.na(t)|t>=0.01, 0, 1)
```
This should work because FALSE|NA will return FALSE. See the ?Logic page. It's also more efficient that looping with `lapply`. I suppose if you need the results in list format you could eitehr do as.list to the results or use:
```
if( is.na(t) || t>=0.01 ) { 0 }else{ 1 }
``` |
80,604 | I create a software in order to solve a step of an specific problem. The results obtained (aided by the software) are going to be published in some journal. The focus of the publication is far away from that step.
The software may be very useful for other people because that step is involved in many common problems. It is not a huge code, but neither me or my collaborators known about other similar software for the matter. We know many researchers that solve it manually in long time.
I want to make the software available online. I wish to do it in some way that it can be cited (and the cites counted).
I can include the code in the supporting information, but I think that it has some downsides:
* Hard to find compared to a site like github.
* Impossible to polish and improve it.
If I don't attach it to a paper, then I don't know how it can be cited.
In short I want to: Make the code widely avaliable in some way that let me collect cites, and make me free to modify/improove the code after publication.
Is there any way? Which are my best options? | 2016/11/28 | [
"https://academia.stackexchange.com/questions/80604",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/44674/"
] | What do you mean by "and the cites counted"? Do you mean something like Google Scholar will index it?
If so, then the common route in CS is to publish *something* that introduces the program (although the code often lives on github). Then people will often cite that paper and or the repo whenever they use your program.
That isn't necessarily a ton of work either. Many conferences have workshops or industry tracks (in case you are an engineer and not a researcher). Also, see dgraziotin's [answer](https://academia.stackexchange.com/a/14041/746) on publishing a paper in an open access journal so that others could cite his work. | You're already publishing something, and this would be the ideal object to cite for people that will use your software in the future.
I would suggest putting the software on a repository, or even on your own website. Then just ask that people cite your paper if they use your software for a publication.
Some examples from my field:
* <http://www.gromacs.org/Gromacs_papers>
* <http://autodock.scripps.edu/resources/references>
* <https://swissmodel.expasy.org/docs/references>
Many of the articles listed there got 100s or 1000s of citations. |
80,604 | I create a software in order to solve a step of an specific problem. The results obtained (aided by the software) are going to be published in some journal. The focus of the publication is far away from that step.
The software may be very useful for other people because that step is involved in many common problems. It is not a huge code, but neither me or my collaborators known about other similar software for the matter. We know many researchers that solve it manually in long time.
I want to make the software available online. I wish to do it in some way that it can be cited (and the cites counted).
I can include the code in the supporting information, but I think that it has some downsides:
* Hard to find compared to a site like github.
* Impossible to polish and improve it.
If I don't attach it to a paper, then I don't know how it can be cited.
In short I want to: Make the code widely avaliable in some way that let me collect cites, and make me free to modify/improove the code after publication.
Is there any way? Which are my best options? | 2016/11/28 | [
"https://academia.stackexchange.com/questions/80604",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/44674/"
] | What do you mean by "and the cites counted"? Do you mean something like Google Scholar will index it?
If so, then the common route in CS is to publish *something* that introduces the program (although the code often lives on github). Then people will often cite that paper and or the repo whenever they use your program.
That isn't necessarily a ton of work either. Many conferences have workshops or industry tracks (in case you are an engineer and not a researcher). Also, see dgraziotin's [answer](https://academia.stackexchange.com/a/14041/746) on publishing a paper in an open access journal so that others could cite his work. | One option is to put it onto Github, which allows you to mint a DOI so that it can be easily cited by others, which in turn allows you to quantify its impact.
If you are a member of an academic institution you should check with your library services. Increasingly they regard themselves as custodians of data, and so may have a standard process for archiving and sharing code and datasets. Often this takes the form of a landing page with a stable URL and including a description of the code, with links to the source (perhaps tagged versions mapping to what you used in your publications) and compiled executables, if appropriate. |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | (I'm assuming throughout that the concentration of wine at the end needs to be 50%.)
Unless I'm missing something:
There are $n$ pints of wine to begin with. After the first 3 pints are taken, you have an $(n-3)/n$ fraction of wine after the water is put back. After the second 3 pints are taken and replaced, you just multiply by the same fraction again, so you have $(n-3)^2/n^2$, and after the last 3 pints you end up with an $(n-3)^3/n^3$ fraction. This leads to $(n-3)^3/n^3=0.5$.
This equation can be rewritten into the linear equation
$(n-3)/n=1/\sqrt[3]{2}$, which then implies
$n=3\sqrt[3]{2}/(\sqrt[3]{2}-1) \approx 14.54$ pints.
Another way is to rewrite the equation into the cubic equation $~~n^3/2 -9n^2 +27n -27=0$, which can be solved by numerical methods to give $n\approx14.54$ pints. | The answer is
>
> $14.542$ pints if he replaces wine with water after taking 3 pints of wine.
>
>
>
Let say you have 300 units of wine and you take off 3 pints of wine and add 3 pints of wine 3 times.
**I. Theft**
After you take off 3 pints of wine (3p) and add 3 pints of wine and add water the new concentration of wine would be;
$\frac{300-3p}{300}$ or $\frac{100-p}{100}$ or $(100-p) \%$
As a result, you would have taken off;
$3p$ of wine.
**II. Theft**
You know that the concentration of wine is $\frac{100-p}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p)\%$ wine and $p\%$ water.
As a result, you would take off
$3p \frac{(100-p)}{100}=3p-\frac{3p^2}{100}$ of wine from the barrel as a wine! So previously it was $3p$ of wine and now the difference between I. Theft and II. Theft is $\frac{3p^2}{100}$ less than first.
$\frac{p}{100}$.
As a result, you would have taken off;
$3p-\frac{3p^2}{100}$ of wine
**III. Theft**
You know that the new concentration of wine is $\frac{100-p-(p-\frac{p^2}{100})}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p-(p-\frac{p^2}{100}))\%$ wine.
As a result you would taken off;
$3p \frac{(100-p-(p-\frac{p^2}{100})}{100}=3p-\frac{6p^2}{100}+\frac{3p^3}{100^2}$ of wine!
**RESULT**
So the sum of wine taken from the barrel would be equal to 50% of wine, or 150 units;
$50\% \ of \ barrel=3p+(3p-\frac{3p^2}{100})+(3p-\frac{6p^2}{100}+\frac{3p^3}{100^2})=150$
As a result;
$p(3-\frac{3p}{100}+\frac{p^2}{100^2})=50$
so $p=20.630$ and since total amount of barrel is assumed to be 300;
>
> The capacity of barrel in terms of pints is $\frac{300}{20.630}=14.542$
>
>
> |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | (I'm assuming throughout that the concentration of wine at the end needs to be 50%.)
Unless I'm missing something:
There are $n$ pints of wine to begin with. After the first 3 pints are taken, you have an $(n-3)/n$ fraction of wine after the water is put back. After the second 3 pints are taken and replaced, you just multiply by the same fraction again, so you have $(n-3)^2/n^2$, and after the last 3 pints you end up with an $(n-3)^3/n^3$ fraction. This leads to $(n-3)^3/n^3=0.5$.
This equation can be rewritten into the linear equation
$(n-3)/n=1/\sqrt[3]{2}$, which then implies
$n=3\sqrt[3]{2}/(\sqrt[3]{2}-1) \approx 14.54$ pints.
Another way is to rewrite the equation into the cubic equation $~~n^3/2 -9n^2 +27n -27=0$, which can be solved by numerical methods to give $n\approx14.54$ pints. | Let $x$ be the starting amount of pints of wine.
Now just focus on the amount of water in the barrel.
After the first step there is 3 pints of water in the barrel. Because the content of the barrel is still $x$ pints the amount of water per pint is therefore $3/x$
So in the second step we take $3$ times $3/x$ water so we take away $9/x$ water and we add $3$ pints of water so we end up with $6 - 9/x$ water in the barrel. This means there is $\frac{6 - 9/x}{x}$ water per pint in the barrel.
So in the final step we take $3$ times $\frac{6 - 9/x}{x}$ water so we take away $3 \cdot \frac{6 - 9/x}{x}$ water and we add $3$ pints of water so we end up with $9 - 9/x - 3 \cdot \frac{6 - 9/x}{x}$ water in the barrel.
We know this is half the amount of the total barrel, so half of $x$, so we just need to solve the following equation:
$$9 - 9/x - 3 \cdot \frac{6 - 9/x}{x} = \frac x 2$$
Solving this gives $x = 3 (2+ \sqrt[3]{2} +\sqrt[3]{4})$ |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | (I'm assuming throughout that the concentration of wine at the end needs to be 50%.)
Unless I'm missing something:
There are $n$ pints of wine to begin with. After the first 3 pints are taken, you have an $(n-3)/n$ fraction of wine after the water is put back. After the second 3 pints are taken and replaced, you just multiply by the same fraction again, so you have $(n-3)^2/n^2$, and after the last 3 pints you end up with an $(n-3)^3/n^3$ fraction. This leads to $(n-3)^3/n^3=0.5$.
This equation can be rewritten into the linear equation
$(n-3)/n=1/\sqrt[3]{2}$, which then implies
$n=3\sqrt[3]{2}/(\sqrt[3]{2}-1) \approx 14.54$ pints.
Another way is to rewrite the equation into the cubic equation $~~n^3/2 -9n^2 +27n -27=0$, which can be solved by numerical methods to give $n\approx14.54$ pints. | Here is an alternate line of reasoning based on *astralfenix*'s very helpful answer to solving the puzzle:
```
p = Capacity of barrel in pints
((p - 3) / p) ** 3 = 0.5
(p - 3) / p = 0.5 ** (1 / 3)
C = 0.5 ** (1 / 3)
(p - 3) / p = C
p - 3 = C * p
p - 3 - C * p = 0
p - C * p = 3
1 * p - C * p = 3
(1 - C) * p = 3
p = 3 / (1 - C)
p = 3 / (1 - 0.5 ** (1 / 3))
p = 14.541966305589222
``` |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | (I'm assuming throughout that the concentration of wine at the end needs to be 50%.)
Unless I'm missing something:
There are $n$ pints of wine to begin with. After the first 3 pints are taken, you have an $(n-3)/n$ fraction of wine after the water is put back. After the second 3 pints are taken and replaced, you just multiply by the same fraction again, so you have $(n-3)^2/n^2$, and after the last 3 pints you end up with an $(n-3)^3/n^3$ fraction. This leads to $(n-3)^3/n^3=0.5$.
This equation can be rewritten into the linear equation
$(n-3)/n=1/\sqrt[3]{2}$, which then implies
$n=3\sqrt[3]{2}/(\sqrt[3]{2}-1) \approx 14.54$ pints.
Another way is to rewrite the equation into the cubic equation $~~n^3/2 -9n^2 +27n -27=0$, which can be solved by numerical methods to give $n\approx14.54$ pints. | Each time wine is replaced the wine remaining is $\frac{n-3}{n}$.
$\frac{(n-3)^3}{n^3} = \frac{1}{2}$
$\frac{2(n-3)^3}{n^3} = 1$
$2(n-3)^3 = n^3$
$\sqrt[3]{2(n-3)^3} = \sqrt[3]{n^3}$
$(n-3)\sqrt[3]{2} = n$
$n\sqrt[3]{2} - n - 3\sqrt[3]{2} = 0$
$n\sqrt[3]{2} - n = 3\sqrt[3]{2}$
$n(\sqrt[3]{2} - 1) = 3\sqrt[3]{2}$
$n = \frac{3\sqrt[3]{2}}{\sqrt[3]{2} - 1}$ |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | The answer is
>
> $14.542$ pints if he replaces wine with water after taking 3 pints of wine.
>
>
>
Let say you have 300 units of wine and you take off 3 pints of wine and add 3 pints of wine 3 times.
**I. Theft**
After you take off 3 pints of wine (3p) and add 3 pints of wine and add water the new concentration of wine would be;
$\frac{300-3p}{300}$ or $\frac{100-p}{100}$ or $(100-p) \%$
As a result, you would have taken off;
$3p$ of wine.
**II. Theft**
You know that the concentration of wine is $\frac{100-p}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p)\%$ wine and $p\%$ water.
As a result, you would take off
$3p \frac{(100-p)}{100}=3p-\frac{3p^2}{100}$ of wine from the barrel as a wine! So previously it was $3p$ of wine and now the difference between I. Theft and II. Theft is $\frac{3p^2}{100}$ less than first.
$\frac{p}{100}$.
As a result, you would have taken off;
$3p-\frac{3p^2}{100}$ of wine
**III. Theft**
You know that the new concentration of wine is $\frac{100-p-(p-\frac{p^2}{100})}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p-(p-\frac{p^2}{100}))\%$ wine.
As a result you would taken off;
$3p \frac{(100-p-(p-\frac{p^2}{100})}{100}=3p-\frac{6p^2}{100}+\frac{3p^3}{100^2}$ of wine!
**RESULT**
So the sum of wine taken from the barrel would be equal to 50% of wine, or 150 units;
$50\% \ of \ barrel=3p+(3p-\frac{3p^2}{100})+(3p-\frac{6p^2}{100}+\frac{3p^3}{100^2})=150$
As a result;
$p(3-\frac{3p}{100}+\frac{p^2}{100^2})=50$
so $p=20.630$ and since total amount of barrel is assumed to be 300;
>
> The capacity of barrel in terms of pints is $\frac{300}{20.630}=14.542$
>
>
> | Here is an alternate line of reasoning based on *astralfenix*'s very helpful answer to solving the puzzle:
```
p = Capacity of barrel in pints
((p - 3) / p) ** 3 = 0.5
(p - 3) / p = 0.5 ** (1 / 3)
C = 0.5 ** (1 / 3)
(p - 3) / p = C
p - 3 = C * p
p - 3 - C * p = 0
p - C * p = 3
1 * p - C * p = 3
(1 - C) * p = 3
p = 3 / (1 - C)
p = 3 / (1 - 0.5 ** (1 / 3))
p = 14.541966305589222
``` |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | The answer is
>
> $14.542$ pints if he replaces wine with water after taking 3 pints of wine.
>
>
>
Let say you have 300 units of wine and you take off 3 pints of wine and add 3 pints of wine 3 times.
**I. Theft**
After you take off 3 pints of wine (3p) and add 3 pints of wine and add water the new concentration of wine would be;
$\frac{300-3p}{300}$ or $\frac{100-p}{100}$ or $(100-p) \%$
As a result, you would have taken off;
$3p$ of wine.
**II. Theft**
You know that the concentration of wine is $\frac{100-p}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p)\%$ wine and $p\%$ water.
As a result, you would take off
$3p \frac{(100-p)}{100}=3p-\frac{3p^2}{100}$ of wine from the barrel as a wine! So previously it was $3p$ of wine and now the difference between I. Theft and II. Theft is $\frac{3p^2}{100}$ less than first.
$\frac{p}{100}$.
As a result, you would have taken off;
$3p-\frac{3p^2}{100}$ of wine
**III. Theft**
You know that the new concentration of wine is $\frac{100-p-(p-\frac{p^2}{100})}{100}$. So If you take off 3 pints of wine (3p) again, you would actually take off $(100-p-(p-\frac{p^2}{100}))\%$ wine.
As a result you would taken off;
$3p \frac{(100-p-(p-\frac{p^2}{100})}{100}=3p-\frac{6p^2}{100}+\frac{3p^3}{100^2}$ of wine!
**RESULT**
So the sum of wine taken from the barrel would be equal to 50% of wine, or 150 units;
$50\% \ of \ barrel=3p+(3p-\frac{3p^2}{100})+(3p-\frac{6p^2}{100}+\frac{3p^3}{100^2})=150$
As a result;
$p(3-\frac{3p}{100}+\frac{p^2}{100^2})=50$
so $p=20.630$ and since total amount of barrel is assumed to be 300;
>
> The capacity of barrel in terms of pints is $\frac{300}{20.630}=14.542$
>
>
> | Each time wine is replaced the wine remaining is $\frac{n-3}{n}$.
$\frac{(n-3)^3}{n^3} = \frac{1}{2}$
$\frac{2(n-3)^3}{n^3} = 1$
$2(n-3)^3 = n^3$
$\sqrt[3]{2(n-3)^3} = \sqrt[3]{n^3}$
$(n-3)\sqrt[3]{2} = n$
$n\sqrt[3]{2} - n - 3\sqrt[3]{2} = 0$
$n\sqrt[3]{2} - n = 3\sqrt[3]{2}$
$n(\sqrt[3]{2} - 1) = 3\sqrt[3]{2}$
$n = \frac{3\sqrt[3]{2}}{\sqrt[3]{2} - 1}$ |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | Let $x$ be the starting amount of pints of wine.
Now just focus on the amount of water in the barrel.
After the first step there is 3 pints of water in the barrel. Because the content of the barrel is still $x$ pints the amount of water per pint is therefore $3/x$
So in the second step we take $3$ times $3/x$ water so we take away $9/x$ water and we add $3$ pints of water so we end up with $6 - 9/x$ water in the barrel. This means there is $\frac{6 - 9/x}{x}$ water per pint in the barrel.
So in the final step we take $3$ times $\frac{6 - 9/x}{x}$ water so we take away $3 \cdot \frac{6 - 9/x}{x}$ water and we add $3$ pints of water so we end up with $9 - 9/x - 3 \cdot \frac{6 - 9/x}{x}$ water in the barrel.
We know this is half the amount of the total barrel, so half of $x$, so we just need to solve the following equation:
$$9 - 9/x - 3 \cdot \frac{6 - 9/x}{x} = \frac x 2$$
Solving this gives $x = 3 (2+ \sqrt[3]{2} +\sqrt[3]{4})$ | Here is an alternate line of reasoning based on *astralfenix*'s very helpful answer to solving the puzzle:
```
p = Capacity of barrel in pints
((p - 3) / p) ** 3 = 0.5
(p - 3) / p = 0.5 ** (1 / 3)
C = 0.5 ** (1 / 3)
(p - 3) / p = C
p - 3 = C * p
p - 3 - C * p = 0
p - C * p = 3
1 * p - C * p = 3
(1 - C) * p = 3
p = 3 / (1 - C)
p = 3 / (1 - 0.5 ** (1 / 3))
p = 14.541966305589222
``` |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | Let $x$ be the starting amount of pints of wine.
Now just focus on the amount of water in the barrel.
After the first step there is 3 pints of water in the barrel. Because the content of the barrel is still $x$ pints the amount of water per pint is therefore $3/x$
So in the second step we take $3$ times $3/x$ water so we take away $9/x$ water and we add $3$ pints of water so we end up with $6 - 9/x$ water in the barrel. This means there is $\frac{6 - 9/x}{x}$ water per pint in the barrel.
So in the final step we take $3$ times $\frac{6 - 9/x}{x}$ water so we take away $3 \cdot \frac{6 - 9/x}{x}$ water and we add $3$ pints of water so we end up with $9 - 9/x - 3 \cdot \frac{6 - 9/x}{x}$ water in the barrel.
We know this is half the amount of the total barrel, so half of $x$, so we just need to solve the following equation:
$$9 - 9/x - 3 \cdot \frac{6 - 9/x}{x} = \frac x 2$$
Solving this gives $x = 3 (2+ \sqrt[3]{2} +\sqrt[3]{4})$ | Each time wine is replaced the wine remaining is $\frac{n-3}{n}$.
$\frac{(n-3)^3}{n^3} = \frac{1}{2}$
$\frac{2(n-3)^3}{n^3} = 1$
$2(n-3)^3 = n^3$
$\sqrt[3]{2(n-3)^3} = \sqrt[3]{n^3}$
$(n-3)\sqrt[3]{2} = n$
$n\sqrt[3]{2} - n - 3\sqrt[3]{2} = 0$
$n\sqrt[3]{2} - n = 3\sqrt[3]{2}$
$n(\sqrt[3]{2} - 1) = 3\sqrt[3]{2}$
$n = \frac{3\sqrt[3]{2}}{\sqrt[3]{2} - 1}$ |
28,776 | [Niccolò Tartaglia](https://en.wikipedia.org/wiki/Niccol%C3%B2_Fontana_Tartaglia) was an Italian mathematician, engineer and bookkeeper, living in the 16th century in the Republic of Venice.
Tartaglia published many books, including his "General Trattato di Numeri", an acclaimed compilation of the mathematics known at his time.
Among many other problems, the Trattato contained the following mathematical puzzle:
>
> A dishonest servant takes out three pints of wine from a barrel and replaces them with the same amount of water. He repeats this theft another two times, removing altogether nine pints and replacing them with water. As a result of this swindle, the diluted wine remaining in the barrel lost half of its former strength.
>
>
> How much wine was in the barrel before the thievery began?
>
>
>
(Note: Tartaglia is also famous for his solution of the cubic equation. The cubic equation that is implicit in this puzzle, however, is of a simple form that could be solved already before Tartaglia's work.) | 2016/03/11 | [
"https://puzzling.stackexchange.com/questions/28776",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/8874/"
] | Each time wine is replaced the wine remaining is $\frac{n-3}{n}$.
$\frac{(n-3)^3}{n^3} = \frac{1}{2}$
$\frac{2(n-3)^3}{n^3} = 1$
$2(n-3)^3 = n^3$
$\sqrt[3]{2(n-3)^3} = \sqrt[3]{n^3}$
$(n-3)\sqrt[3]{2} = n$
$n\sqrt[3]{2} - n - 3\sqrt[3]{2} = 0$
$n\sqrt[3]{2} - n = 3\sqrt[3]{2}$
$n(\sqrt[3]{2} - 1) = 3\sqrt[3]{2}$
$n = \frac{3\sqrt[3]{2}}{\sqrt[3]{2} - 1}$ | Here is an alternate line of reasoning based on *astralfenix*'s very helpful answer to solving the puzzle:
```
p = Capacity of barrel in pints
((p - 3) / p) ** 3 = 0.5
(p - 3) / p = 0.5 ** (1 / 3)
C = 0.5 ** (1 / 3)
(p - 3) / p = C
p - 3 = C * p
p - 3 - C * p = 0
p - C * p = 3
1 * p - C * p = 3
(1 - C) * p = 3
p = 3 / (1 - C)
p = 3 / (1 - 0.5 ** (1 / 3))
p = 14.541966305589222
``` |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | This CFX Tag - [CFX\_HTTP5](http://www.cftagstore.com/tags/cfxhttp5.cfm) - should do what you need. It does cost $50, but perhaps it's worth the cost? Seems like a small price to pay. | Here is some code I found in:
<http://www.bpurcell.org/downloads/presentations/securing_cfapps_examples.zip>
There are also examples for ldap, webservices, and more.. I'll paste 2 files here so you can have an idea, code looks like it should still work.
```
<cfapplication name="example2" sessionmanagement="Yes" loginStorage="Session">
<!-- Application.cfm -->
<!-- CFMX will check for authentication with each page request. -->
<cfset Request.myDomain="allaire">
<cfif isdefined("url.logout")>
<CFLOGOUT>
</cfif>
<cflogin>
<cfif not IsDefined("cflogin")>
<cfinclude template="loginform.cfm">
<cfabort>
<cfelse>
<!--Invoke NTSecurity CFC -->
<cfinvoke component = "NTSecurity" method = "authenticateAndGetGroups"
returnVariable = "userRoles" domain = "#Request.myDomain#"
userid = "#cflogin.name#" passwd = "#cflogin.password#">
<cfif userRoles NEQ "">
<cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles="#stripSpacesfromList(userRoles)#">
<cfset session.displayroles=stripSpacesfromList(userRoles)><!--- for displaying roles only --->
<cfelse>
<cfset loginmessage="Invalid Login">
<cfinclude template="loginform.cfm">
<cfabort>
</cfif>
</cfif>
</cflogin>
<!-- strips leading & trailing spaces from the list of roles that was returned -->
<cffunction name="stripSpacesfromList">
<cfargument name="myList">
<cfset myArray=listtoarray(arguments.myList)>
<cfloop index="i" from="1" to="#arraylen(myArray)#" step="1">
<!--- <cfset myArray[i]=replace(trim(myArray[i]), " ", "_")>
out<br>--->
<cfset myArray[i]=trim(myArray[i])>
</cfloop>
<cfset newList=arrayToList(myArray)>
<cfreturn newList>
</cffunction>
```
This is the cfc that might be of interest to you:
```
<!---
This component implements methods for use for NT Authentication and Authorization.
$Log: NTSecurity.cfc,v $
Revision 1.1 2002/03/08 22:40:41 jking
Revision 1.2 2002/06/26 22:46 Brandon Purcell
component for authentication and authorization
--->
<cfcomponent name="NTSecurity" >
<!--- Authenticates the user and outputs true on success and false on failure. --->
<cffunction name="authenticateUser" access="REMOTE" output="no" static="yes" hint="Authenticates the user." returntype="boolean">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
ntauth.authenticateUser(arguments.userid, arguments.passwd);
</cfscript>
<cfreturn true>
<cfcatch>
<cfreturn false>
</cfcatch>
</cftry>
</cffunction>
<!---
Authenticates the user and outputs true on success and false on failure.
--->
<cffunction access="remote" name="getUserGroups" output="false" returntype="string" hint="Gets user groups." static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now???
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cflog text="Error in ntsecurity.cfc method getUserGroups - Error: #cfcatch.message#" type="Error" log="authentication" file="authentication" thread="yes" date="yes" time="yes" application="no">
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
<!---
This method combines the functionality of authenticateUser and getUserGroups.
--->
<cffunction access="remote" name="authenticateAndGetGroups" output="false" returntype="string" hint="Authenticates the user and gets user groups if it returns nothing the user is not authticated" static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
// so we don't have anything specific here
ntauth.authenticateUser(arguments.userid, arguments.passwd);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
</cfcomponent>
``` |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | This CFX Tag - [CFX\_HTTP5](http://www.cftagstore.com/tags/cfxhttp5.cfm) - should do what you need. It does cost $50, but perhaps it's worth the cost? Seems like a small price to pay. | You could try following the guidance here: [<http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating>](http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating)
Here is what it boils down to you doing:
```
edit the client-config.wsdd
```
Change
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.HTTPSender">
</transport>
```
to
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.CommonsHTTPSender">
</transport>
``` |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | This CFX Tag - [CFX\_HTTP5](http://www.cftagstore.com/tags/cfxhttp5.cfm) - should do what you need. It does cost $50, but perhaps it's worth the cost? Seems like a small price to pay. | If the code from Brandon Purcell that uses the `jrun.security.NTauth` class doesn't work for you in `cf9` (it didn't for me) the fix is to use the `coldfusion.security.NTAuthentication` class instead. Everything worked fine for me. |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | This CFX Tag - [CFX\_HTTP5](http://www.cftagstore.com/tags/cfxhttp5.cfm) - should do what you need. It does cost $50, but perhaps it's worth the cost? Seems like a small price to pay. | In my case I fixed this problem using 'NTLM Authorization Proxy Server'
<http://www.tldp.org/HOWTO/Web-Browsing-Behind-ISA-Server-HOWTO-4.html>
work fine for me :) |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | Here is some code I found in:
<http://www.bpurcell.org/downloads/presentations/securing_cfapps_examples.zip>
There are also examples for ldap, webservices, and more.. I'll paste 2 files here so you can have an idea, code looks like it should still work.
```
<cfapplication name="example2" sessionmanagement="Yes" loginStorage="Session">
<!-- Application.cfm -->
<!-- CFMX will check for authentication with each page request. -->
<cfset Request.myDomain="allaire">
<cfif isdefined("url.logout")>
<CFLOGOUT>
</cfif>
<cflogin>
<cfif not IsDefined("cflogin")>
<cfinclude template="loginform.cfm">
<cfabort>
<cfelse>
<!--Invoke NTSecurity CFC -->
<cfinvoke component = "NTSecurity" method = "authenticateAndGetGroups"
returnVariable = "userRoles" domain = "#Request.myDomain#"
userid = "#cflogin.name#" passwd = "#cflogin.password#">
<cfif userRoles NEQ "">
<cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles="#stripSpacesfromList(userRoles)#">
<cfset session.displayroles=stripSpacesfromList(userRoles)><!--- for displaying roles only --->
<cfelse>
<cfset loginmessage="Invalid Login">
<cfinclude template="loginform.cfm">
<cfabort>
</cfif>
</cfif>
</cflogin>
<!-- strips leading & trailing spaces from the list of roles that was returned -->
<cffunction name="stripSpacesfromList">
<cfargument name="myList">
<cfset myArray=listtoarray(arguments.myList)>
<cfloop index="i" from="1" to="#arraylen(myArray)#" step="1">
<!--- <cfset myArray[i]=replace(trim(myArray[i]), " ", "_")>
out<br>--->
<cfset myArray[i]=trim(myArray[i])>
</cfloop>
<cfset newList=arrayToList(myArray)>
<cfreturn newList>
</cffunction>
```
This is the cfc that might be of interest to you:
```
<!---
This component implements methods for use for NT Authentication and Authorization.
$Log: NTSecurity.cfc,v $
Revision 1.1 2002/03/08 22:40:41 jking
Revision 1.2 2002/06/26 22:46 Brandon Purcell
component for authentication and authorization
--->
<cfcomponent name="NTSecurity" >
<!--- Authenticates the user and outputs true on success and false on failure. --->
<cffunction name="authenticateUser" access="REMOTE" output="no" static="yes" hint="Authenticates the user." returntype="boolean">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
ntauth.authenticateUser(arguments.userid, arguments.passwd);
</cfscript>
<cfreturn true>
<cfcatch>
<cfreturn false>
</cfcatch>
</cftry>
</cffunction>
<!---
Authenticates the user and outputs true on success and false on failure.
--->
<cffunction access="remote" name="getUserGroups" output="false" returntype="string" hint="Gets user groups." static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now???
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cflog text="Error in ntsecurity.cfc method getUserGroups - Error: #cfcatch.message#" type="Error" log="authentication" file="authentication" thread="yes" date="yes" time="yes" application="no">
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
<!---
This method combines the functionality of authenticateUser and getUserGroups.
--->
<cffunction access="remote" name="authenticateAndGetGroups" output="false" returntype="string" hint="Authenticates the user and gets user groups if it returns nothing the user is not authticated" static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
// so we don't have anything specific here
ntauth.authenticateUser(arguments.userid, arguments.passwd);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
</cfcomponent>
``` | You could try following the guidance here: [<http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating>](http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating)
Here is what it boils down to you doing:
```
edit the client-config.wsdd
```
Change
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.HTTPSender">
</transport>
```
to
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.CommonsHTTPSender">
</transport>
``` |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | Here is some code I found in:
<http://www.bpurcell.org/downloads/presentations/securing_cfapps_examples.zip>
There are also examples for ldap, webservices, and more.. I'll paste 2 files here so you can have an idea, code looks like it should still work.
```
<cfapplication name="example2" sessionmanagement="Yes" loginStorage="Session">
<!-- Application.cfm -->
<!-- CFMX will check for authentication with each page request. -->
<cfset Request.myDomain="allaire">
<cfif isdefined("url.logout")>
<CFLOGOUT>
</cfif>
<cflogin>
<cfif not IsDefined("cflogin")>
<cfinclude template="loginform.cfm">
<cfabort>
<cfelse>
<!--Invoke NTSecurity CFC -->
<cfinvoke component = "NTSecurity" method = "authenticateAndGetGroups"
returnVariable = "userRoles" domain = "#Request.myDomain#"
userid = "#cflogin.name#" passwd = "#cflogin.password#">
<cfif userRoles NEQ "">
<cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles="#stripSpacesfromList(userRoles)#">
<cfset session.displayroles=stripSpacesfromList(userRoles)><!--- for displaying roles only --->
<cfelse>
<cfset loginmessage="Invalid Login">
<cfinclude template="loginform.cfm">
<cfabort>
</cfif>
</cfif>
</cflogin>
<!-- strips leading & trailing spaces from the list of roles that was returned -->
<cffunction name="stripSpacesfromList">
<cfargument name="myList">
<cfset myArray=listtoarray(arguments.myList)>
<cfloop index="i" from="1" to="#arraylen(myArray)#" step="1">
<!--- <cfset myArray[i]=replace(trim(myArray[i]), " ", "_")>
out<br>--->
<cfset myArray[i]=trim(myArray[i])>
</cfloop>
<cfset newList=arrayToList(myArray)>
<cfreturn newList>
</cffunction>
```
This is the cfc that might be of interest to you:
```
<!---
This component implements methods for use for NT Authentication and Authorization.
$Log: NTSecurity.cfc,v $
Revision 1.1 2002/03/08 22:40:41 jking
Revision 1.2 2002/06/26 22:46 Brandon Purcell
component for authentication and authorization
--->
<cfcomponent name="NTSecurity" >
<!--- Authenticates the user and outputs true on success and false on failure. --->
<cffunction name="authenticateUser" access="REMOTE" output="no" static="yes" hint="Authenticates the user." returntype="boolean">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
ntauth.authenticateUser(arguments.userid, arguments.passwd);
</cfscript>
<cfreturn true>
<cfcatch>
<cfreturn false>
</cfcatch>
</cftry>
</cffunction>
<!---
Authenticates the user and outputs true on success and false on failure.
--->
<cffunction access="remote" name="getUserGroups" output="false" returntype="string" hint="Gets user groups." static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now???
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cflog text="Error in ntsecurity.cfc method getUserGroups - Error: #cfcatch.message#" type="Error" log="authentication" file="authentication" thread="yes" date="yes" time="yes" application="no">
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
<!---
This method combines the functionality of authenticateUser and getUserGroups.
--->
<cffunction access="remote" name="authenticateAndGetGroups" output="false" returntype="string" hint="Authenticates the user and gets user groups if it returns nothing the user is not authticated" static="yes">
<cfargument name="userid" type="string" required="true" />
<cfargument name="passwd" type="string" required="true" />
<cfargument name="domain" type="string" required="true" />
<cftry>
<cfscript>
ntauth = createObject("java", "jrun.security.NTAuth");
ntauth.init(arguments.domain);
// authenticateUser throws an exception if it fails,
// so we don't have anything specific here
ntauth.authenticateUser(arguments.userid, arguments.passwd);
groups = ntauth.GetUserGroups(arguments.userid);
// note that groups is a java.util.list, which should be
// equiv to a CF array, but it's not right now
groups = trim(groups.toString());
groups = mid(groups,2,len(groups)-2);
</cfscript>
<cfreturn groups>
<cfcatch>
<cfreturn "">
</cfcatch>
</cftry>
</cffunction>
</cfcomponent>
``` | In my case I fixed this problem using 'NTLM Authorization Proxy Server'
<http://www.tldp.org/HOWTO/Web-Browsing-Behind-ISA-Server-HOWTO-4.html>
work fine for me :) |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | If the code from Brandon Purcell that uses the `jrun.security.NTauth` class doesn't work for you in `cf9` (it didn't for me) the fix is to use the `coldfusion.security.NTAuthentication` class instead. Everything worked fine for me. | You could try following the guidance here: [<http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating>](http://cfsilence.com/blog/client/index.cfm/2008/3/17/ColdFusionSharepoint-Integration--Part-1--Authenticating)
Here is what it boils down to you doing:
```
edit the client-config.wsdd
```
Change
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.HTTPSender">
</transport>
```
to
```
<transport
name="http"
pivot="java:org.apache.axis.transport.http.CommonsHTTPSender">
</transport>
``` |
895,361 | Is there a recommended (and preferably free) way in ColdFusion to access a remote file that is protected by NTLM authentication? The cfhttp tag appears to only support Basic authentication. | 2009/05/21 | [
"https://Stackoverflow.com/questions/895361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | If the code from Brandon Purcell that uses the `jrun.security.NTauth` class doesn't work for you in `cf9` (it didn't for me) the fix is to use the `coldfusion.security.NTAuthentication` class instead. Everything worked fine for me. | In my case I fixed this problem using 'NTLM Authorization Proxy Server'
<http://www.tldp.org/HOWTO/Web-Browsing-Behind-ISA-Server-HOWTO-4.html>
work fine for me :) |
26,946,975 | I work with android, I want to draw design like this

There are two LinearLayuots ( blue and white ), I want add picture their borders, I have tryied to use minus margin but not work
Can Anybody help me? | 2014/11/15 | [
"https://Stackoverflow.com/questions/26946975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2834421/"
] | I finally managed to access logs of the appengine VM using [volumes](https://docs.docker.com/userguide/dockervolumes/) of docker. And hacking a file of the google-cloud-sdk after browsing the python code.
However, since I am working on Mac OS X, some extra things where needed because of the VirtualBox layer in between the OS and docker, as described here: <http://viget.com/extend/how-to-use-docker-on-os-x-the-missing-guide>
So, below are the commands I ran.
1 - stop all docker containers if necessary:
```
➜ ~ docker stop $(docker ps -a -q)
```
2 - remove all docker containers if necessary:
```
➜ ~ docker rm $(docker ps -a -q)
```
3 - stop the boot2docker VirtualBox VM:
```
➜ ~ boot2docker down
```
4 - create the directory where you want it mapped on your local machine (make sure it is one where you have read/write permissions without needing to `sudo`):
```
➜ ~ mkdir -p ~/var/log/app_engine
```
5 - mount the directory into the boot2docker VirtualBox VM:
```
➜ ~ VBoxManage sharedfolder add boot2docker-vm -name var -hostpath ~/var/log/app_engine
```
6 - start the boot2docker VirtualBox VM:
```
➜ ~ boot2docker up
```
7 - edit line 266 of file google-cloud-sdk/platform/google\_appengine/google/appengine/tools/devappserver2/vm\_runtime\_proxy.py
```
265 external_logs_path = os.path.join(
266 '/var/log/app_engine',
267 self._escape_domain(
```
with the path to the sharedfolder, in my case:
```
265 external_logs_path = os.path.join(
266 '/Users/nicolas/var/log/app_engine',
267 self._escape_domain(
```
8 - run the app:
```
➜ ~ mvn appengine:gcloud_app_run
```
9 - check the logs are there:
```
➜ ~ ls ~/var/log/app_engine/heimdall-dev/default/1/0/
STDERR.2014_11_16.log STDOUT.2014_11_16.log app.0.log.json app.0.log.json.1 app.0.log.json.1.lck app.0.log.json.2 app.0.log.json.2.lck app.0.log.json.lck request.2014_11_16.log
```
Not exactly straightforward and easy...
It must be possible to make the default `/var/mog/app_engine` local folder available to the VirtualBox VM by changing the permissions and thus there would be no need to hack into google-cloud-sdk python files. However, I haven't had the time to test that yet. I'll update the answer when I get to test that. | Just as a completion to your initial answer @Nicolas, I've created a small shell script that will
1. Builds the project
2. Launch docker
3. Launch a console that will show the latest logs
4. Launch the `gcloud preview app` command
I'm sharing the .sh file with you now:
```
#!/bin/sh
mvn clean install #build via MAVEN
boot2dockerstatus=$( boot2docker status )
echo $boot2dockerstatus
if [ $boot2dockerstatus != 'running' ]
then
boot2docker start
boot2docker status
fi
open http://localhost:8080
#ADD logs debugging on a separate window (MacOSx only) !!
osascript -e 'tell app "Terminal"
do script "cd /var/log/app_engine/; tail -F *.log"
end tell'
gcloud --verbosity debug preview app run --enable-mvm-logs "./target/<your-project-build-name-here>"
``` |
379,345 | I was wondering what the state machine for a video player would be like.
I can think of two states : playing and paused.
* When the video is playing and the user clicks on a point in the progress bar the video is paused (the video player transitions from the playing state to paused state) until the user stops pressing the mouse button.
When the mouse is released the video begins to play again from the selected point (the video player transitions from the paused state to the playing state).
* However if the video was paused before the user clicked on the progress bar the video jumps to the specified point but does not start playing (the video player remains in the paused state).
The state transitions would be :
playing (begin click on progress bar)--> paused (end click on progress bar)--> playing paused (begin click on progress bar)--> paused (end click on progress bar)--> paused
If there was a method to change the position of the video in the paused state, then calling that method would result in a different state depending on the previous state. I was wondering if there is an alternate state machine design for a video player where the transitions from each state do not depend on any previous state. | 2018/10/02 | [
"https://softwareengineering.stackexchange.com/questions/379345",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/316628/"
] | If you want to hold onto "classical" state machines whose transition functions only depend on the current state and incoming inputs you have to rethink how you want to model the application's state.
Formally, you can simulate transitions depending on the previous state (in terms of your current application) by building a new state machine which has pair states with each pair containing combinations of two of the original state machine's states.
Conceptually one of the pair's components stands for your current main state while the other one describes the previous state.
For each original transition `t` from state `x` to state `y` you'll get transitions `t'` from any state of the form `(*, x)` to state `(x, y)` (here the first component encodes the previous main state).
Then modify the resulting state machine to your needs such that you're actually using the previous main state (first component).
You may reduce this "product state machine" by eliminating states/combinations which are impossible to reach or by collapsing state-sets `(*,s)` which are equivalent regarding the ingoing and outgoing transitions to single states.
Perhaps in your case you can directly introduce SOME pair states instead of going through the whole formal ceremony.
Just be careful to consider all important combinations.
In your example the resulting state machine is not much different from the original one. Some of the states and transitions you might get from such a construction are (now with `(x,y)` written as `x_y`):
```
playing --(mousedown)--> playing_paused --(mouseup)--> playing
paused --(mousedown)--> paused_paused --(mouseup)--> paused
```
Notice how the target state on `mouseup` events at the middle `paused` state differs, depending on the encoded previous state. | Usually, next state *s**i*+1 in a finite state machine is fully defined by a current state *si* and an incoming signal *m*. In other words:
*s**i*+1 = *f*(*si*, *m*)
>
> Can a state machine transition depend on [both the current and] the previous state?
>
>
>
Yes, it can. The resulting construct still qualifies as a state machine. A state machine transition can depend on a finite number of previous states. In other words,
*s**i*+1 = *f*(*si*, *s**i*-1, *m*)
is valid for a state machine.
*p.s.* History pseudostate also has an effect the the transition is guided by some older history in addition to the current state and incoming message. |
340,192 | I have a problem with a oneway web method that open a moss site (probably because in a oneway webmethod the context is null)
Is possible to rewrite this code to remove the null reference exception? (without the oneway attribute i don't have the exception)
```
[SoapDocumentMethod(OneWay = true)]
[WebMethod(Description = "TestOneWay")]
public voidTestOneWay(string webUrl)
{
using (SPSite site = new SPSite(webUrl))
{
....
}
}
```
the exception is:
```
[2304] Error:Object reference not set to an instance of an object.
[2304] w3wp.exe Error: 0 :
[2304StackTrace: at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
[2304] at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
[2304] at System.Web.HttpRequest.AddServerVariableToCollection(String name)
[2304] at System.Web.HttpRequest.FillInServerVariablesCollection()
[2304] at System.Web.HttpServerVarsCollection.Populate()
[2304] at System.Web.HttpServerVarsCollection.Get(String name)
[2304] at System.Collections.Specialized.NameValueCollection.get_Item(String name)
[2304] at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)
[2304] at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)
[2304] at Microsoft.SharePoint.Administration.SPFarm.get_RequestNoAuth()
[2304] at Microsoft.SharePoint.SPSite.CopyUserToken(SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite.SPSiteConstructor(SPFarm farm, Guid applicationId, Guid contentDatabaseId, Guid siteId, SPUrlZone zone, Uri requestUri, String serverRelativeUrl, Boolean hostHeaderIsSiteName, Uri redirectUri, Pairing pairing, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
[2304] at Reply.Moss2EAI.SPHandler.GetAllFlowConfiguration(String webUrl, String flowConList)
[2304] at Reply.Moss2EAI.EaiMossIntegration.GetMessagesFromEai(String webUrl, String listName, String applicationName)
``` | 2008/12/04 | [
"https://Stackoverflow.com/questions/340192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43162/"
] | i have found a workaround to solve my problem.Create new HttpContext. The question now is:
is it the right solution or there are implications that i don't consider?
the method that i use to change the context is this:
```
//Call this before call new SPSite()
private static void ChangeContext(string webUrl)
{
Trace.TraceInformation("ChangeContext");
HttpContext current = HttpContext.Current;
HttpRequest request = new HttpRequest("", webUrl, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
HttpContext.Current.User = current.User;
}
``` | The only implication that I see is that you are actually using a new HttpContext.
Well..duh :)
Anyway, this will have implications if you also have input- and outputfilters set up. For example if you are using WebServiceExtensions (WSE) with your own input and outputfilters. In that case, you should store the data in the HttpContext (that is there in your input- and outputfilters) and use that one. Just so that you use only one httpContext, instead of creating a second one, and to prevent any future errors when extending your software. |
340,192 | I have a problem with a oneway web method that open a moss site (probably because in a oneway webmethod the context is null)
Is possible to rewrite this code to remove the null reference exception? (without the oneway attribute i don't have the exception)
```
[SoapDocumentMethod(OneWay = true)]
[WebMethod(Description = "TestOneWay")]
public voidTestOneWay(string webUrl)
{
using (SPSite site = new SPSite(webUrl))
{
....
}
}
```
the exception is:
```
[2304] Error:Object reference not set to an instance of an object.
[2304] w3wp.exe Error: 0 :
[2304StackTrace: at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
[2304] at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
[2304] at System.Web.HttpRequest.AddServerVariableToCollection(String name)
[2304] at System.Web.HttpRequest.FillInServerVariablesCollection()
[2304] at System.Web.HttpServerVarsCollection.Populate()
[2304] at System.Web.HttpServerVarsCollection.Get(String name)
[2304] at System.Collections.Specialized.NameValueCollection.get_Item(String name)
[2304] at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)
[2304] at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)
[2304] at Microsoft.SharePoint.Administration.SPFarm.get_RequestNoAuth()
[2304] at Microsoft.SharePoint.SPSite.CopyUserToken(SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite.SPSiteConstructor(SPFarm farm, Guid applicationId, Guid contentDatabaseId, Guid siteId, SPUrlZone zone, Uri requestUri, String serverRelativeUrl, Boolean hostHeaderIsSiteName, Uri redirectUri, Pairing pairing, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
[2304] at Reply.Moss2EAI.SPHandler.GetAllFlowConfiguration(String webUrl, String flowConList)
[2304] at Reply.Moss2EAI.EaiMossIntegration.GetMessagesFromEai(String webUrl, String listName, String applicationName)
``` | 2008/12/04 | [
"https://Stackoverflow.com/questions/340192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43162/"
] | i have found a workaround to solve my problem.Create new HttpContext. The question now is:
is it the right solution or there are implications that i don't consider?
the method that i use to change the context is this:
```
//Call this before call new SPSite()
private static void ChangeContext(string webUrl)
{
Trace.TraceInformation("ChangeContext");
HttpContext current = HttpContext.Current;
HttpRequest request = new HttpRequest("", webUrl, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
HttpContext.Current.User = current.User;
}
``` | Use this will work for you:
```
SPWeb web = SPContext.Current.Web
``` |
19,458,150 | I have a form where I must choose a file, then I want to get the $\_FILES['image'] array to be able to pass it as an argument to a Jquery function. How can I do it ?
Thank you | 2013/10/18 | [
"https://Stackoverflow.com/questions/19458150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/891623/"
] | You can use hex code directly in `RewriteRule`:
```
RewriteEngine On
RewriteRule ^\xE2\x80\xA6/(myfile\.htm)$ mydirectory/$1 [L,NE,NC,R]
``` | I needed to redirect <http://www.bentonswcd.org/resources/rural-living/%20%E2%80%8E> to <http://www.bentonswcd.org/resources/rural-living/>. I tried the suggestion here and in these other posts and none worked:
[Trying to Redirect 301 %E2%80%A6 in htaccess file](https://stackoverflow.com/questions/16183230/trying-to-redirect-301-e280a6-in-htaccess-file)
[Redirect %20%E2%80%8E](https://stackoverflow.com/questions/18739473/redirect-20e2808e)
[How to redirect %E2%80%8E and other weird links to right place?](https://stackoverflow.com/questions/19024846/how-to-redirect-e2808e-and-other-weird-links-to-right-place)
Then a friend of mine suggested this fix, and it worked great. Hope it can work for you:
```
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)\%20%E2%80%8E(.*)\ HTTP/ [NC]
RewriteRule ^.*$ /%1 [R=301,L]
``` |
752,691 | When resetting IPTables, the apt-get and wget command functions correctly and also downloads what I want. But once I activate this firewall, it isn't functional. Pings still work.
I want to allow all outgoing connections. That's why I added "iptables -P OUTPUT ACCEPT" at the end.
IPTables Firewall:
<http://pastebin.com/pTGyiz7c>
iptables -L -n -v: <http://pastebin.com/6Q8Mbgfh> | 2016/01/29 | [
"https://serverfault.com/questions/752691",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | This is what your are looking for. It will pause the sequence and put an icon on the desktop. When you are finished doing what ever you need to install, you complete the image by clicking on the desktop icon.
[How to setup LTI-Pause](http://deploymentbunny.com/2011/05/10/ltipause-vbs-take-a-break-in-deployment/ "LTI-Pause") | If the drivers are in exe form then use the `install application` task sequence task. If they are in `inf`/`ini` form then add them to the MDT driver database and use the install driver task.
If you can use a `command prompt` or `powershell` to install them then use the command prompt command or powershell command task.[](https://i.stack.imgur.com/m4yGG.png)
Another idea is to include the files for your drivers in your install image and execute the files with the `unattend.xml` after the install is complete so that the network drivers are available for MDT to finish up with. |
121,974 | I have a diskless host 'A', that has a directory NFS mounted on server 'B'. A process on A writes to two files F1 and F2 in that directory, and a process on B monitors these files for changes. Assume that B polls for changes faster than A is expected to make them. Process A seeks the head of the files, writes data, and flushes. Process B seeks the head of the files and does reads.
Are there *any* guarantees about how the order of the changes performed by A will be detected at B?
Specifically, if A alternately writes to one file, and then the other, is it reasonable to expect that B will notice alternating changes to F1 and F2? Or could B conceivably detect a series of changes on F1 and then a series on F2?
I know there are a lot of assumptions embedded in the question. For instance, I am virtually certain that, even operating on just one file, if A performs 100 operations on the file, B may see a smaller number of changes that give the same result, due to NFS caching some of the actions on A before they are communicated to B. And of course there would be issues with concurrent file access even if NFS weren't involved and both the reading and the writing process were running on the same *real* file system.
The reason I'm even putting the question up here is that it seems like most of the time, the setup described above *does* detect the changes at B in the same order they are made at A, but that occasionally some events come through in transposed order. So, is it worth trying to make this work? Is there some way to tune NFS to make it work, perhaps cache settings or something? Or is fine-grained behavior like this just too much expect from NFS? | 2010/03/11 | [
"https://serverfault.com/questions/121974",
"https://serverfault.com",
"https://serverfault.com/users/15222/"
] | I wouldn't rely on consistent ordering across the network. NFS itself generally only guarantees that *after* one client *closes* a file, another client *opening* it should see those changes. (And this says nothing about the observed behavior on the server's filesystem.)
What are your NFS client, server, and protocol versions, though? The Linux kernel NFS client, for example, changed (default) attribute caching behaviors around 2.6.18, and you can mount with `-o sync` for no write caching at all (data or attribute). NFSv4 also allows more control over caching behavior than NFSv3. | You might like to see [the answer to another question](https://stackoverflow.com/questions/2422500/safely-lock-a-file-then-move-windows/2422535#2422535), which links to a description of Transactional NTFS. It's really cool, and might help your situation. |
121,974 | I have a diskless host 'A', that has a directory NFS mounted on server 'B'. A process on A writes to two files F1 and F2 in that directory, and a process on B monitors these files for changes. Assume that B polls for changes faster than A is expected to make them. Process A seeks the head of the files, writes data, and flushes. Process B seeks the head of the files and does reads.
Are there *any* guarantees about how the order of the changes performed by A will be detected at B?
Specifically, if A alternately writes to one file, and then the other, is it reasonable to expect that B will notice alternating changes to F1 and F2? Or could B conceivably detect a series of changes on F1 and then a series on F2?
I know there are a lot of assumptions embedded in the question. For instance, I am virtually certain that, even operating on just one file, if A performs 100 operations on the file, B may see a smaller number of changes that give the same result, due to NFS caching some of the actions on A before they are communicated to B. And of course there would be issues with concurrent file access even if NFS weren't involved and both the reading and the writing process were running on the same *real* file system.
The reason I'm even putting the question up here is that it seems like most of the time, the setup described above *does* detect the changes at B in the same order they are made at A, but that occasionally some events come through in transposed order. So, is it worth trying to make this work? Is there some way to tune NFS to make it work, perhaps cache settings or something? Or is fine-grained behavior like this just too much expect from NFS? | 2010/03/11 | [
"https://serverfault.com/questions/121974",
"https://serverfault.com",
"https://serverfault.com/users/15222/"
] | This
>
> Assume that B polls for changes
>
>
>
and
>
> Specifically, if A alternately writes to one file, and then the other, is it reasonable to expect that B will notice alternating changes to F1 and F2? Or could B conceivably detect a series of changes on F1 and then a series on F2?
>
>
>
mean that no matter *what* guarantees the filesystem makes there is a race condition here.
That is: you can't count count on the order in which process B detects the changes.
Consider what happens if
1. B polls Foo
2. A writes to Foo
3. A writes to Bar
4. B polls Bar | You might like to see [the answer to another question](https://stackoverflow.com/questions/2422500/safely-lock-a-file-then-move-windows/2422535#2422535), which links to a description of Transactional NTFS. It's really cool, and might help your situation. |
18,049 | Please suggest the word which means "understandable by specific group". I just forgot that. | 2011/03/26 | [
"https://english.stackexchange.com/questions/18049",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/530/"
] | There are lots of words covering the general concept, but they're usually used by people who are *not* members of the "specific group", so they tend to be pejorative.
**Esoteric** strikes me as somewhat less value-laden than most. | While not a direct answer to your question, the term **jargon** refers to language (words and phrases) that are common in one specific group but not used that way outside the group.
For example, in medical jargon, a heart attack is called a myocardial infarction. |
18,049 | Please suggest the word which means "understandable by specific group". I just forgot that. | 2011/03/26 | [
"https://english.stackexchange.com/questions/18049",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/530/"
] | There are lots of words covering the general concept, but they're usually used by people who are *not* members of the "specific group", so they tend to be pejorative.
**Esoteric** strikes me as somewhat less value-laden than most. | An "in-joke" is a term used describe an event that is humourous only to a small group of insiders to whom the full history leading up to the event is known, thereby allowing them to find humour in the situation that would otherwise to an outsider not appear to be humourous. |
18,049 | Please suggest the word which means "understandable by specific group". I just forgot that. | 2011/03/26 | [
"https://english.stackexchange.com/questions/18049",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/530/"
] | There are lots of words covering the general concept, but they're usually used by people who are *not* members of the "specific group", so they tend to be pejorative.
**Esoteric** strikes me as somewhat less value-laden than most. | You *may* be looking for the word **shibboleth**. From [Wikipedia](http://en.wikipedia.org/wiki/Shibboleth):
>
> A shibboleth ( /ˈʃɪbəlɛθ/ or /ˈʃɪbələθ/) is any distinguishing practice that is indicative of one's social or regional origin.
>
>
>
It is also used to mean words used by a members of a group to distinguish themselves as members of that group. When used this way, it is being used metaphorically. |
18,049 | Please suggest the word which means "understandable by specific group". I just forgot that. | 2011/03/26 | [
"https://english.stackexchange.com/questions/18049",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/530/"
] | While not a direct answer to your question, the term **jargon** refers to language (words and phrases) that are common in one specific group but not used that way outside the group.
For example, in medical jargon, a heart attack is called a myocardial infarction. | An "in-joke" is a term used describe an event that is humourous only to a small group of insiders to whom the full history leading up to the event is known, thereby allowing them to find humour in the situation that would otherwise to an outsider not appear to be humourous. |
18,049 | Please suggest the word which means "understandable by specific group". I just forgot that. | 2011/03/26 | [
"https://english.stackexchange.com/questions/18049",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/530/"
] | While not a direct answer to your question, the term **jargon** refers to language (words and phrases) that are common in one specific group but not used that way outside the group.
For example, in medical jargon, a heart attack is called a myocardial infarction. | You *may* be looking for the word **shibboleth**. From [Wikipedia](http://en.wikipedia.org/wiki/Shibboleth):
>
> A shibboleth ( /ˈʃɪbəlɛθ/ or /ˈʃɪbələθ/) is any distinguishing practice that is indicative of one's social or regional origin.
>
>
>
It is also used to mean words used by a members of a group to distinguish themselves as members of that group. When used this way, it is being used metaphorically. |
69,884,335 | I am following this tutorial:
<https://www.baeldung.com/spring-boot-react-crud>
When I start the React server and try to fetch the json object(s) from REST API and display them in the map, the player data is not displayed despite following the tutorial.
The only thing displayed is the word 'Players' but no player data is shown.
In the console I am getting:
```
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
```
The API works correctly and when I visit http://localhost:8080/players I am displayed a json object of all the players data.
```
[{"id":1,"firstName":"Fabiano","lastName":"Caruana","email":"fabcar@gmail.com","bio":"Not quite WC.","password":"BigFab72","rating":2750"},
{"id":2,"firstName":"Biggie","lastName":"Ta","email":"bigt@gmail.com", "bio":"Not quite a WC.","password":"BigT72","rating":2750}]
```
app.js:
```
import React, {Component} from 'react';
class App extends Component {
state = {
players: []
};
async componentDidMount() {
const response = await fetch('/players');
const body = await response.json();
this.setState({players: body});
}
render() {
const {players} = this.state;
return (
<div className="App">
<header className="App-header">
<div className="App-intro">
<h2>Players</h2>
{players.map(player =>
<div key={player.id}>
{player.firstName} ({player.email})
</div>
)}
</div>
</header>
</div>
);
}
}
export default App;
```
In my package.json file I have:
```
"proxy": "http://localhost:8080"
```
And my SpringBoot REST application runs on 8080.
When I did console.log(response.text()):
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json" />
<!--
Notice the use of in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="/static/js/bundle.js"></script><script src="/static/js/vendors~main.chunk.js"></script><script src="/static/js/main.chunk.js"></script></body>
</html>
```
Controller:
```
@RestController
@RequestMapping("/players")
public class PlayersController {
private final PlayerRepository playerRepository;
public PlayersController(PlayerRepository playerRepository) {
this.playerRepository = playerRepository;
}
@GetMapping
public List<Player> getPlayers() {
return playerRepository.findAll();
}
@GetMapping("/{id}")
public Player getPlayer(@PathVariable Long id) {
return playerRepository.findById(id).orElseThrow(RuntimeException::new);
}
@PostMapping()
public ResponseEntity createPlayer(@RequestBody Player player) throws URISyntaxException {
Player savedPlayer = playerRepository.save(player);
return ResponseEntity.created(new URI("/players/" + savedPlayer.getId())).body(savedPlayer);
}
@PutMapping("/{id}")
public ResponseEntity updatePlayer(@PathVariable Long id, @RequestBody Player player) {
Player currentPlayer = playerRepository.findById(id).orElseThrow(RuntimeException::new);
currentPlayer.setFirstName(player.getFirstName());
currentPlayer.setEmail(player.getEmail());
currentPlayer = playerRepository.save(player);
return ResponseEntity.ok(currentPlayer);
}
@DeleteMapping("/{id}")
public ResponseEntity deletePlayer(@PathVariable Long id) {
playerRepository.deleteById(id);
return ResponseEntity.ok().build();
}
}
```
Thanks for help! | 2021/11/08 | [
"https://Stackoverflow.com/questions/69884335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17320369/"
] | if you bind the element to property using wire:model, you can hook the lifecycle as mentioned above
```
public function updatedCourseId($value)
{
dd($value);
}
```
in a different approach, you can listen for the event using wire:change, and for that, you must define the event in listener property like
```
<x-select label="{!! __('Ders') !!}" wire:change="$emit('courseSelected', $event.target.value)" id="course_id" :options="$this->courses"/>
// in component
protected $listeners = [
'courseSelected'
];
public function courseSelected($value)
{
dd($value);
}
``` | you should hook to the updated method in the lifecycle.
<https://laravel-livewire.com/docs/2.x/lifecycle-hooks>
```
public function updatedCourseId(){
dd("here");
}
```
Also remove wire:change |
85,247 | I am managing an e-store site created by another colleague, that was badly created from the start.
Because of the structure, pagination and user browser capabilities combined with lack of meta robots directives to "noindex" certain pages it ended up with over 20k pages indexed in Google.
I am working on a website restructure, to follow all the seo meta robots directives correctly as well as eliminate a lot of browsing capabilities to eliminate tons of duplicated and useless pages.
However, doing bulk 301 redirects of the eliminated urls might(most probably will) cause 404 errors according to google's webmaster's guidelines.
Also, if I remove the pages from the website's internal linking, I will have to manually deindex pages one by one in webmaster's tools as the crawler will not have access to it so that it can read the noindex directives and update it in time.
As an example :
* `www.example.com/products` - this contains a list of products, paginated until page 2000+
* `www.example.com/products/a` - this contains a list of products starting with the letter A, paginated to about 30+ pages
* `www.example.com/products/b` - you get the point.
also:
* `www.example.com/products/most-viewed` - a list of most viewed products ( the same products - paginated to 2000+
* `www.example.com/products/top-rated` - the same products, paginated to 2000+
As you can see there lots and lots of duplicated content.
I am trying to fix it. So I am implementing rel=next and prev for the pagination, but I also want to remove some useless pages for example the browse product alphabetically. In order to deindex the `example.com/products/A`, `B`, etc.
Should I:
**a.** Eliminate it from internal linking completely and then manually request an url removal for each link from webmasters tools ?
**b.** Keep it on the website and use meta robots to noindex these pages? I will have to leave it here untill the crawler gets around and updates all the pages accordingly.
**c.** Remove it from website's internal linking but add the meta robots noindex/follow, but instead of manually de-indexing them I should add them to the url sitemap and submit it to google so that the crawler still knows them and crawls them to read the noindex directive... even though they are no longer linked from the website.
**d.** 301 redirect to either the products page or home page. But some many bulk directs to a single page or homepage will cause problems and Google can treat them as 404 actually. More info here <https://moz.com/blog/save-your-website-with-redirects>
If I were to redirect each one to another page that would be something, but I am trying to remove lots and lots of pages.
What would be the logical approach? | 2015/09/21 | [
"https://webmasters.stackexchange.com/questions/85247",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/37417/"
] | ```
by another colleague, that was badly created from the start
```
my deepest condolences:)
The main point you should consider, is whether pages you want to get rid of have EXTERNAL links. This should be the basis for your decision to 301 or 404 them:
* if they have external link, 301 them to save the link equity
* if they haven't, or have just a few, 404 them.
The procedure should look like:
* create the new, optimized site/url structure
* don't mind about internal linking - you will have some drop of search engine visibility in any case, it is usual, if you make such big structure optimization. But the drop is temporal, till Google gets your new structure.
* 404 all old page, which don't have external links
* create counterparts for all old pages, which have external links and 301 old pages to their new counterparts
* nothing to noindex! - make and upload the new sitemap into search console and Google will get your new site structure like a charm.
* be patient! Google **will** get your new site structure
if you WANT have such sites, like example.com/product category1/, i.e. for users, then let the first page be indexed, and noindex the pagination.
Note: rel prev next go into the head and have nothing to do with indexation. they are only for crawling. | For restructuring of ecommerce websites, perhaps not on a scale as yours, I would do what Evgeniy says above. What I would also do, from an SEO perspective, is if you have any spam/poor/dodgy links pointing to any of the pages you are going to 404, use a 410 response instead - once Google crawls you a couple of times, it'll disregard the poor links to those pages. This has worked or me plenty of times to great effect. Plus, you dont have to 301 every page ( /A or /B etc) that needs 301'd (I got a feeling that's what you are doing, forgive me if I'm wrong), use htacess or the rewrite equivalent of whatever technology you're using to do it by directory. In addition to UX and having a terrific working website, you want to make Google's crawl as easy as possible, so I'd avoid noindexing/URL removal from GWT if possible to keep your xml sitemap as lean as possible. |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | I have also faced this same issue and solved it by changing the port from 465 to 587.
In ColdFusion Administrator check the 'Enable TLS Connection to mail server' check box and remove check from 'Enable SSL connection to mail server'.
Now you can verify the connection.
Thanks | You need to check the 'Enable TLS Connection to mail server' checkbox as well.
I was unable to verify the connection on my test server using the settings you have specified - but using my own credentials.
I was able to verify connection when TLS was enabled. |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | You need to check the 'Enable TLS Connection to mail server' checkbox as well.
I was unable to verify the connection on my test server using the settings you have specified - but using my own credentials.
I was able to verify connection when TLS was enabled. | I've seen this issue a lot recently, due to Google making some changes to the way that you access GMail accounts.
Specifically, you may find a setting in your account that refers to allowing access to 'Less secure apps'.
Essentially, Google are trying to force oAuth style authentication, and denying access via username/password auth.
You can re-enable the 'less secure' method of authentication in your account settings:
<http://www.google.com/settings/security/lesssecureapps> |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | You need to check the 'Enable TLS Connection to mail server' checkbox as well.
I was unable to verify the connection on my test server using the settings you have specified - but using my own credentials.
I was able to verify connection when TLS was enabled. | As others have mentioned, double check your SSL/TLS options and port numbers. Also check for leading/trailing spaces in your SMTP credentials. I spent 20 mins troubleshooting this issue once and it turned out to be caused by a trailing space in the SMTP username field.. :/ |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | I have also faced this same issue and solved it by changing the port from 465 to 587.
In ColdFusion Administrator check the 'Enable TLS Connection to mail server' check box and remove check from 'Enable SSL connection to mail server'.
Now you can verify the connection.
Thanks | Removing username and password worked for me in CF11. |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | I have also faced this same issue and solved it by changing the port from 465 to 587.
In ColdFusion Administrator check the 'Enable TLS Connection to mail server' check box and remove check from 'Enable SSL connection to mail server'.
Now you can verify the connection.
Thanks | I've seen this issue a lot recently, due to Google making some changes to the way that you access GMail accounts.
Specifically, you may find a setting in your account that refers to allowing access to 'Less secure apps'.
Essentially, Google are trying to force oAuth style authentication, and denying access via username/password auth.
You can re-enable the 'less secure' method of authentication in your account settings:
<http://www.google.com/settings/security/lesssecureapps> |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | I have also faced this same issue and solved it by changing the port from 465 to 587.
In ColdFusion Administrator check the 'Enable TLS Connection to mail server' check box and remove check from 'Enable SSL connection to mail server'.
Now you can verify the connection.
Thanks | As others have mentioned, double check your SSL/TLS options and port numbers. Also check for leading/trailing spaces in your SMTP credentials. I spent 20 mins troubleshooting this issue once and it turned out to be caused by a trailing space in the SMTP username field.. :/ |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | Removing username and password worked for me in CF11. | I've seen this issue a lot recently, due to Google making some changes to the way that you access GMail accounts.
Specifically, you may find a setting in your account that refers to allowing access to 'Less secure apps'.
Essentially, Google are trying to force oAuth style authentication, and denying access via username/password auth.
You can re-enable the 'less secure' method of authentication in your account settings:
<http://www.google.com/settings/security/lesssecureapps> |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | Removing username and password worked for me in CF11. | As others have mentioned, double check your SSL/TLS options and port numbers. Also check for leading/trailing spaces in your SMTP credentials. I spent 20 mins troubleshooting this issue once and it turned out to be caused by a trailing space in the SMTP username field.. :/ |
17,997,685 | I am trying to set up a simple maven project that will run a bunch of unit tests written in Python. I believe I need a plugin for this job and I came across one such plugin - [jython-compile-maven-plugin](http://mavenjython.sourceforge.net/compile/plugin-info.html)
However, I believe that this plugin allows the user to make a call to the "nosetests" command which then runs a bunch of Python scripts that call on JUnit test cases (that is test cases written in Java). What I would like to do is have Maven call the command "nosetests" and run just a bunch of test cases written in Python. Can anyone advise if this is doable? Or can anyone point me in the direction to some docs that can help.
Thanks very much | 2013/08/01 | [
"https://Stackoverflow.com/questions/17997685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2630271/"
] | I've seen this issue a lot recently, due to Google making some changes to the way that you access GMail accounts.
Specifically, you may find a setting in your account that refers to allowing access to 'Less secure apps'.
Essentially, Google are trying to force oAuth style authentication, and denying access via username/password auth.
You can re-enable the 'less secure' method of authentication in your account settings:
<http://www.google.com/settings/security/lesssecureapps> | As others have mentioned, double check your SSL/TLS options and port numbers. Also check for leading/trailing spaces in your SMTP credentials. I spent 20 mins troubleshooting this issue once and it turned out to be caused by a trailing space in the SMTP username field.. :/ |
73,357,902 | When I am trying to run my app on my phone it is getting successfully installed in my phone but I am getting white screen instead of my splash page . Attaching my xml code and java code for your reference . Your help is highly appreciated !!
activity\_main.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:fontFamily="sans-serif-black"
android:text="MY APP"
android:textColor="@color/Black"
android:textSize="50sp" />
</Relativelayout>
```
activity\_main.java
```
package com.example.kriova;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
finish();
}
```
} | 2022/08/15 | [
"https://Stackoverflow.com/questions/73357902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14533440/"
] | **`SOLUTION 1`**
You should set the initial state as `{}` empty object to `response` as:
```
let [response, setResponse] = useState({});
```
Because you are accessing it in JSX as:
```
{response.employee_salary}
```
The initial value is `undefined`. So your response is `undefined` and you can't access the property from `undefined`
**`SOLUTION 2`**
You can also use [`optional chaining`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) as:
```
{response?.employee_salary}
```
**`SOLUTION 3`**
You can only render `Text` if `response` is truthy value i.e not undefined (in your case)
```
{
response && (
<Text
onPress={() => navigation.navigate('Home')}
style={{ fontSize: 26, fontWeight: 'bold' }}
>
employee salary: {response.employee_salary}
</Text>
)
}
``` | useEffect is starting working after first render [docs](https://beta.reactjs.org/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events)
so in first render this state is undefined. You can fix it in some ways
1.
```js
{ response?.employee_salary }
```
2.
```js
{response?.employee_salary ?? 'Loading' }
```
or add loading state
```js
export default function App({ navigation }) {
let [response, setResponse] = useState();
const [loading, setLoading] = useState(false);
useEffect(async () => {
const fetchData = async () => {
fetch("https://dummy.restapiexample.com/api/v1/employee/1")
.then((res) => res.json())
.then((jsoon) => {
setResponse(jsoon.data);
});
}
setLoading(true);
await fetchData();
setLoading(false);
}, []);
if (loading) {
return <div>Loading...</div>;
}
return (
<div className="App">employee salary: {response?.employee_salary}</div>
);
}
``` |
40,437,299 | Emulator Image - API 17, armeabi-v7a
`tools$ emulator -avd Nexus_5_API_17
dyld: Library not loaded: /tmp/darwin-x86_64-clang-3.5/lib/libc++.1.dylib
Referenced from: /Users/madhav/Library/Android/sdk/tools/./emulator
Reason: image not found
Trace/BPT trap: 5` | 2016/11/05 | [
"https://Stackoverflow.com/questions/40437299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4708811/"
] | Check your .profile and .bashrc to see if DYLD\_FALLBACK\_LIBRARY\_PATH is set there and if so try commenting out those lines. For me, the Muse SDK had put in a line with this that broke the Android emulator. | As mentioned by Joshua, you need to remove or comment the line added by other applications.
The last line of my `.bash_profile` after fix now is:
```
#export DYLD_FALLBACK_LIBRARY_PATH="$DYLD_FALLBACK_LIBRARY_PATH:/Applications/Muse"
``` |
45,307,541 | ```
function Hello()
{
function HelloAgain(){
}
}
function MyFunction(){
...
}
```
Here I need to call the function HelloAgain() from MyFunction().
Can you suggest any possible solution for this scenario. | 2017/07/25 | [
"https://Stackoverflow.com/questions/45307541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8364649/"
] | You can't, the HelloAgain function is in a closure and is scoped to that closure.
You could return the HelloAgain function and then call it from anywhere you can call Hello.
```
function Hello () {
function HelloAgain () {}
return HelloAgain;
}
function MyFunction () {
Hello().HelloAgain();
}
```
But that slightly weird.
More over you could use the `this` keyword to deal with the matter.
```
function Hello () {
this.helloAgain = function helloAgain () {}
}
var hello = new Hello();
function MyFunction () {
hello.helloAgain();
}
``` | You can't. The scope of `HelloAgain` il limited to the `Hello` function.
This is the only way to make private scope in javascript. |
64,688,864 | I am trying to initialize 2 dynamic arrays which class student will have an array containing all the courses registered and class course will have an array containing all the students registered to the class. I defined class Course and Student like this:
```
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class Course;
class Student {
std::string name; // person’s name
int id; // person’s age
Course* courses;
int course_register; // number of organization registered to
public:
Student();
Student(const Student& s) {
name = s.getName();
id = s.getAge();
course_register = s.getorg_register();
}
Student(std::string n, int i) {
id = i;
name = n;
}
int getAge() const { return id; }
string getName() const { return name; }
int getorg_register() const { return course_register; }
};
class Course {
std::string name; // name of the org
Student* students; // list of members
int size; // actual size of the org
int dim; // max size of the org
public:
Course()
{
dim = 100;
students = new Student[dim];
};
Course(const Course& course)
{
name = course.getName();
dim = course.getDim();
size = course.getSize();
students = new Student[dim];
for (int i = 0; i < size; i++) {
students[i] = course.getStudent(i);
}
}
~Course()
{
delete[] students;
}
Student getStudent(int i) {return students[i];}
Student* getStudents() {return students;}
int getSize(){return size;}
int getDim() {return dim;}
string getName() {return name;}
};
Student::Student() {
courses = new Course[5];
}
```
When I try to compile, I get an exception unhandled at runtime for constructor Student::Student(). Can someone explain to me why I get a runtime error? And how would you change it to make it work? | 2020/11/04 | [
"https://Stackoverflow.com/questions/64688864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Or with Python:
```
import boto3
response = boto3.client("ssm").describe_parameters(
ParameterFilters=[
{
'Key': 'Name',
'Option': 'Contains',
'Values': [
'token',
]
},
]
)
``` | I think this is what you are after:
```
aws ssm describe-parameters --parameter-filters Key=Name,Values=token,Option=Contains
``` |
68,796,367 | I want to do something like this in Notepad++.
Example text:
Text1~Text2 ~Text3 ~Text4 ~
How can I remove the spaces before ~ character and replace ~ with comma instead using Notepad++? The output should be:
Sample Output:
Text1,Text2,Text3,Text4,
Thanks all for your help. | 2021/08/16 | [
"https://Stackoverflow.com/questions/68796367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16674872/"
] | Easiest way is try to replace all on the application.
Use Ctrl + H key | What you are looking for is a simple replacement. Use `Ctrl + H` key combination which will show up find and replace popup. In the first input box write `~` and in the second one write `,` and then click on `replace all` button.
If your text is more complicated than what you've told, give us a piece of text so that I can tell you a better way which is the use of `Regular Expression`. |
1,334,518 | Let $\{a\_0,a\_1,a\_2...\}$ be a sequence of real numbers let $s\_n=\sum a\_{2k}$. If $\lim\_{n\rightarrow \infty} s\_n $ exists then $\sum a\_m$ exists. Is it true?
I don§t find a counter example | 2015/06/22 | [
"https://math.stackexchange.com/questions/1334518",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294365/"
] | This is false. Let
$$
a\_n = \begin{cases}0 \text{, if } n \text{ is even} \\
1 \text{, otherwise} \end{cases}
$$
Then $\lim\_{n \rightarrow \infty} s\_n = 0$, but $\sum\_{m=1}^\infty a\_m = \infty$. | Let:
$$\begin{cases} a\_m = 0 \text{ if m is even} \\
a\_m = 1 \text{ if m is odd }\end{cases}$$
Then $\sum a\_{2k}=0$ and $\sum a\_m =\infty$. |
172 | For a movie I'm working on, I need some small rugby crowd ambiences. So I went to a pub to record some, but the TV was up a bit too present. It's non-distinct, but audible nonetheless.
My question is whether sport on TV (so a presenter, some crowds and some names of players and teams) is okay to record or are there legal implications?
Thanks. | 2010/03/07 | [
"https://sound.stackexchange.com/questions/172",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2/"
] | At least in the US (probably the same everywhere), you can't use it unless you can obtain permission from broadcaster who owns the rights, which you probably will not be able to do without some sort of contract and payment to the rights holder. | I am afraid that it is the same in the UK, you can not include any broadcast content without it being licensed. |
172 | For a movie I'm working on, I need some small rugby crowd ambiences. So I went to a pub to record some, but the TV was up a bit too present. It's non-distinct, but audible nonetheless.
My question is whether sport on TV (so a presenter, some crowds and some names of players and teams) is okay to record or are there legal implications?
Thanks. | 2010/03/07 | [
"https://sound.stackexchange.com/questions/172",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2/"
] | At least in the US (probably the same everywhere), you can't use it unless you can obtain permission from broadcaster who owns the rights, which you probably will not be able to do without some sort of contract and payment to the rights holder. | It's probably illegal, but, then again, so is everything else.
If there's no likelihood of being sued, you should use it illegally to protest against the ever-encroaching tentacles of copyright law. |
172 | For a movie I'm working on, I need some small rugby crowd ambiences. So I went to a pub to record some, but the TV was up a bit too present. It's non-distinct, but audible nonetheless.
My question is whether sport on TV (so a presenter, some crowds and some names of players and teams) is okay to record or are there legal implications?
Thanks. | 2010/03/07 | [
"https://sound.stackexchange.com/questions/172",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2/"
] | Agreed with above, but it sounds like a great reason to ply a bunch of friends with some foamy libations and record rugby walla, probably also doing a separate semi-ADR session with someone doing the play-by-play. I'd volunteer my voice and liver if I lived closer to ya. :-) | I am afraid that it is the same in the UK, you can not include any broadcast content without it being licensed. |
172 | For a movie I'm working on, I need some small rugby crowd ambiences. So I went to a pub to record some, but the TV was up a bit too present. It's non-distinct, but audible nonetheless.
My question is whether sport on TV (so a presenter, some crowds and some names of players and teams) is okay to record or are there legal implications?
Thanks. | 2010/03/07 | [
"https://sound.stackexchange.com/questions/172",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2/"
] | I am afraid that it is the same in the UK, you can not include any broadcast content without it being licensed. | It's probably illegal, but, then again, so is everything else.
If there's no likelihood of being sued, you should use it illegally to protest against the ever-encroaching tentacles of copyright law. |
172 | For a movie I'm working on, I need some small rugby crowd ambiences. So I went to a pub to record some, but the TV was up a bit too present. It's non-distinct, but audible nonetheless.
My question is whether sport on TV (so a presenter, some crowds and some names of players and teams) is okay to record or are there legal implications?
Thanks. | 2010/03/07 | [
"https://sound.stackexchange.com/questions/172",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/2/"
] | Agreed with above, but it sounds like a great reason to ply a bunch of friends with some foamy libations and record rugby walla, probably also doing a separate semi-ADR session with someone doing the play-by-play. I'd volunteer my voice and liver if I lived closer to ya. :-) | It's probably illegal, but, then again, so is everything else.
If there's no likelihood of being sued, you should use it illegally to protest against the ever-encroaching tentacles of copyright law. |
53,112,509 | I'm new to JavaScript and I'm having trouble trying to make my functions work properly.
```js
function myFunction() {
// This part appends a number before a label with the class "enum"
var enumField = document.getElementsByClassName('enum');
for (var z = 0; z <= enumField.length; z++) {
var span = document.createElement('span');
span.innerHTML = z + 1 + '.- ';
enumField[z].parentNode.insertBefore(span, enumField[z]);
}
//This other part changes the background color of an element with the class "fieldsetColor"
var fieldsetStyle = document.getElementsByClassName('fieldsetColor');
for (var i = 0; i <= fieldsetStyle.length; i++) {
fieldsetStyle[i].style.backgroundColor = 'palegoldenrod';
}
}
```
```html
<body onload="myFunction();">
<div>Student</div>
<form id="myForm">
<fieldset class="fieldsetColor">
<legend>Personal Data </legend>
<img src="http://via.placeholder.com/100x100?text=Placeholder"><br>
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
</fieldset>
</form>
</body>
```
The main problem is that only the first part of the function works (the one that enumerates), and the second part does not work.
If I swap the position of the first part and the second one, the same happens (only the background color is changed).
What could be the problem? Is my syntax wrong? Is something wrong with the `<body onload="myFunction()">`?
I'm really afraid that this could be silly question... I'm trying to learn by myself but sometimes I get lost and can't seem to formulate the right question...
Thanks in advance! ☺ | 2018/11/02 | [
"https://Stackoverflow.com/questions/53112509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164555/"
] | You're actually just looping once more than you need to. Since arrays are zero indexed, you don't want `z <= enumField.length` but rather `z < enumField.length`. Since this error was halting the function, nothing continued.
```js
function myFunction() {
// This part appends a number before a label with the class "enum"
var enumField = document.getElementsByClassName('enum');
for (var z = 0; z < enumField.length; z++) {
var span = document.createElement('span');
span.innerHTML = z + 1 + '.- ';
console.log(enumField[z]);
enumField[z].parentNode.insertBefore(span, enumField[z]);
}
//This other part changes the background color of an element with the class "fieldsetColor"
var fieldsetStyle = document.getElementsByClassName('fieldsetColor');
for (var i = 0; i <= fieldsetStyle.length; i++) {
fieldsetStyle[i].style.backgroundColor = 'palegoldenrod';
}
}
```
```html
<body onload="myFunction();">
<div>Student</div>
<form id="myForm">
<fieldset class="fieldsetColor">
<legend>Personal Data </legend>
<img src="http://via.placeholder.com/100x100?text=Placeholder"><br>
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
</fieldset>
</form>
``` | It's caused by your for loop condition. You probably get an Array Index Out of Bounds exception.
you use
```
z <= enumField.length
```
but it should be
```
z < enumField.length
``` |
52,433,394 | *Question below context*
**Context:** For this program to be submitted and work properly I need to be able to input 8.68 for the amount that gets scanned in. The program then needs to be able to calculate how many of each coin type needs to be given as well as the remaining balance after you give ***x*** amount of the coin
[What the output should look like](https://i.stack.imgur.com/9YUW7.jpg)
**Question/Problem:** My program will run until the quarters and get it all correct, once it gets to the dimes, where it has 0 dimes, the program breaks and will exit. *(Even when I use a different amount in the beginning, it will break at a different point if the amount of coin, in this instance the dimes have a value of 0)* What can I do to ensure that it will run and finish the same as the output shown above.
***Code:***
```
#include <stdio.h>
int main()
{
double amount;
double GST = 1.13;
double balance;
int numLoonies;
int numQuarters;
int numDimes;
int numNickels;
int numPennies;
int bal;
printf("Please enter the amount to be paid: $"); //ask how much to be paid
scanf("%lf", &amount); //scans the input
GST = amount * .13 + .005;
printf("GST: 1.13\n");
balance = (amount + GST);
printf("Balance owing: $%.2lf\n", balance);
numLoonies = balance;
bal = ((balance - numLoonies)*100);
printf("Loonies required: %d", numLoonies);
printf(", balance owing $%1.2f\n", (float)bal/100);
numQuarters = bal / 25;
bal = bal % (numQuarters*25);
printf("Quarters required: %d", numQuarters);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numDimes = bal / 10;
bal = bal % (numDimes * 10);
printf("Dimes required: %d", numDimes);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numNickels = bal / 5;
bal = bal % (numNickels * 5);
printf("Nickels required: %d", numNickels);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numPennies = bal / 1;
bal = bal % (numPennies * 1);
printf("Pennies required: %d", numPennies);
printf(", balance owing $%1.2f\n", (float)bal/100);
return 0;
}
```
***Update*** So this is for a school project, should have mentioned that, but I have to use the mod to find the remaining balance, and I had to cast the double into an int as part of the criteria.
*And yes, Canada doesn't have pennies any more but I still have to do it this way* | 2018/09/20 | [
"https://Stackoverflow.com/questions/52433394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393544/"
] | >
> (Even when I use a different amount in the beginning, it will break at a different point if the amount of coin, in this instance the dimes have a value of 0)
>
>
>
That's a big clue. So let's look at the dimes...
```
bal = bal % (numDimes * 10);
```
So, let's say `numDimes` is 0. Then `(numDimes * 10)` is also zero. What do you think happens when you try to calculate `bal % 0`? If you're not sure, you could put that expression into your program and try it.
Another issue is that I don't think you really mean to say `bal % (numDimes * 10)`. Let's say `numDimes` works out to be 3 for some starting balance... in that case you've got `bal % (3 * 10)` or `bal % 30`. Is that really what you want? That'd give some number between 0 and 29, when you probably really want a number that's less than the value of a single dime. If I've got 79 cents and I *take out* 7 dimes, then `79 % 70` does give the `9` that I should have left over, but it's not the most intuitive way to get there. | Step 1 - Convert money into whole numbers of the lowest unit.
Since code is to count to the "penny", take input and round/convert to whole number of cents.
```
#include <math.h>
double amount;
printf("Please enter the amount to be paid: $"); //ask how much to be paid
scanf("%lf", &amount);
long iamount = lround(amount * 100);
```
Same with GST
```
double GST = 1.13;
long itax = lround(iamount * (GST - 1)); // round to the nearest penny
long ibalance = iamount + itax;
printf("Balance owing: $%.2lf\n", ibalance/100.0);
```
2) Proceed to break down into coins
OP's `bal = bal % (numCoins*CoinValue);` is not the right approach.
```
long CoinDenomination = 100; // 100 cents to the Loonie
long iLoonies = ibalance/CoinDenomination;
printf("Loonies required: %ld", iLoonies);
ibalance %= CoinDenomination;
...
CoinDenomination = 10; // 10 cents to the Dime
long iDimes = ibalance/CoinDenomination;
printf("Dimes required: %ld", iDime);
ibalance %= CoinDenomination;
``` |
52,433,394 | *Question below context*
**Context:** For this program to be submitted and work properly I need to be able to input 8.68 for the amount that gets scanned in. The program then needs to be able to calculate how many of each coin type needs to be given as well as the remaining balance after you give ***x*** amount of the coin
[What the output should look like](https://i.stack.imgur.com/9YUW7.jpg)
**Question/Problem:** My program will run until the quarters and get it all correct, once it gets to the dimes, where it has 0 dimes, the program breaks and will exit. *(Even when I use a different amount in the beginning, it will break at a different point if the amount of coin, in this instance the dimes have a value of 0)* What can I do to ensure that it will run and finish the same as the output shown above.
***Code:***
```
#include <stdio.h>
int main()
{
double amount;
double GST = 1.13;
double balance;
int numLoonies;
int numQuarters;
int numDimes;
int numNickels;
int numPennies;
int bal;
printf("Please enter the amount to be paid: $"); //ask how much to be paid
scanf("%lf", &amount); //scans the input
GST = amount * .13 + .005;
printf("GST: 1.13\n");
balance = (amount + GST);
printf("Balance owing: $%.2lf\n", balance);
numLoonies = balance;
bal = ((balance - numLoonies)*100);
printf("Loonies required: %d", numLoonies);
printf(", balance owing $%1.2f\n", (float)bal/100);
numQuarters = bal / 25;
bal = bal % (numQuarters*25);
printf("Quarters required: %d", numQuarters);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numDimes = bal / 10;
bal = bal % (numDimes * 10);
printf("Dimes required: %d", numDimes);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numNickels = bal / 5;
bal = bal % (numNickels * 5);
printf("Nickels required: %d", numNickels);
printf(", balance owing $%1.2f\n", (float)bal / 100);
numPennies = bal / 1;
bal = bal % (numPennies * 1);
printf("Pennies required: %d", numPennies);
printf(", balance owing $%1.2f\n", (float)bal/100);
return 0;
}
```
***Update*** So this is for a school project, should have mentioned that, but I have to use the mod to find the remaining balance, and I had to cast the double into an int as part of the criteria.
*And yes, Canada doesn't have pennies any more but I still have to do it this way* | 2018/09/20 | [
"https://Stackoverflow.com/questions/52433394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393544/"
] | >
> (Even when I use a different amount in the beginning, it will break at a different point if the amount of coin, in this instance the dimes have a value of 0)
>
>
>
That's a big clue. So let's look at the dimes...
```
bal = bal % (numDimes * 10);
```
So, let's say `numDimes` is 0. Then `(numDimes * 10)` is also zero. What do you think happens when you try to calculate `bal % 0`? If you're not sure, you could put that expression into your program and try it.
Another issue is that I don't think you really mean to say `bal % (numDimes * 10)`. Let's say `numDimes` works out to be 3 for some starting balance... in that case you've got `bal % (3 * 10)` or `bal % 30`. Is that really what you want? That'd give some number between 0 and 29, when you probably really want a number that's less than the value of a single dime. If I've got 79 cents and I *take out* 7 dimes, then `79 % 70` does give the `9` that I should have left over, but it's not the most intuitive way to get there. | >
> Because of the way numDimes is calculated, it will always produce the correct answer as long as numDimes > 0. But bal % 10 will produce the same result. – Barmar
>
>
>
So what I ended up doing was easier than I originally thought I was going to have to do, I just used mod *coin value*. Thanks for all the comments :) |
53,656,121 | I am trying to write a simple game, and in that game, there is a class called `Fighter`, and instances of that class can attack other instances.
I want to make an instance of that class that is always defined and has special properties(i know how to do that please don't try to answer that) so that it can be used as a power player of some sort. | 2018/12/06 | [
"https://Stackoverflow.com/questions/53656121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4429205/"
] | What you probably want is:
```
public class Fighter {
public static final Fighter ADMIN_FIGHTER = new Fighter(whatever-args ...);
``` | you can use Singleton pattern like this
```
public final class AdminFighter {
private static final AdminFighter instance = new AdminFighter();
private AdminFighter(){}
public static AdminFighter instance() {
return instance;
}
}
```
so whereever you are in the project you can use like this
```
AdminFighter constant = AdminFighter.instance();
```
and this always return the same instance of AdminFighter like a constant.
**NOTE:** avoid global constants like this example, they will turn in future headaches and they are sign of poor design. [There are tons of blog post discussing about this](http://wiki.c2.com/?GlobalVariablesAreBad). |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | Try:
```
var codeName = document.getElementById(code[i]) || null;
if (codeName) {/* action when codeName != null */}
```
if you want to be sure codeName is an Object:
```
if (codeName && codeName instanceof Object) {
/* action when codeName != null and Object */
}
``` | In ruby `nil` is equivalent to `false`.
So try to check just:
`if codeName` |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | ```
var codeList = document.getElementById('codeList');
if(!codeList && !codeList.value && !codeList.value.length) return;
var code = codeList.value.split(","),
itemCount = code.length;
if(!itemCount) return;
for (var i=0, i<itemCount; i++) {
var codeName = document.getElementById(code[i]);
if(!codename || !codename.length) continue;
//do something here...
}
```
I got a working example here: <http://jsbin.com/uduxe4/15> | I don't do a whole lot of JS coding, but it seems like your [i] is the problem. As far as I know, [] is used for accessing a field of an array, and you don't have an array. Just use "code" + i |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | Try:
```
var codeName = document.getElementById(code[i]) || null;
if (codeName) {/* action when codeName != null */}
```
if you want to be sure codeName is an Object:
```
if (codeName && codeName instanceof Object) {
/* action when codeName != null and Object */
}
``` | ```
<div id='code1'></div>
var itemCount = 10;
var len = 10;
len = itemCount;
for (var i=0;i<len; i++) {
var codeName = document.getElementById('code'+ i);
if(codeName == null)
alert("Nope " + i);
else
alert("Yep " + i);
}
``` |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | After the `getElementById` call, `codeName` is either a DOM Element or null. You can use an alert to see which:
```
alert(codeName);
```
So `if (codename != null)` should work.
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger. | I don't know what `document` is, but you could try something like
```
if(document.getElementById('code'+[i]) == null)
{
//...do Something
}
```
so testing if it exists *before* you using it... |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | After the `getElementById` call, `codeName` is either a DOM Element or null. You can use an alert to see which:
```
alert(codeName);
```
So `if (codename != null)` should work.
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger. | I don't do a whole lot of JS coding, but it seems like your [i] is the problem. As far as I know, [] is used for accessing a field of an array, and you don't have an array. Just use "code" + i |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | ```
var codeList = document.getElementById('codeList');
if(!codeList && !codeList.value && !codeList.value.length) return;
var code = codeList.value.split(","),
itemCount = code.length;
if(!itemCount) return;
for (var i=0, i<itemCount; i++) {
var codeName = document.getElementById(code[i]);
if(!codename || !codename.length) continue;
//do something here...
}
```
I got a working example here: <http://jsbin.com/uduxe4/15> | ```
<div id='code1'></div>
var itemCount = 10;
var len = 10;
len = itemCount;
for (var i=0;i<len; i++) {
var codeName = document.getElementById('code'+ i);
if(codeName == null)
alert("Nope " + i);
else
alert("Yep " + i);
}
``` |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | ```
var codeList = document.getElementById('codeList');
if(!codeList && !codeList.value && !codeList.value.length) return;
var code = codeList.value.split(","),
itemCount = code.length;
if(!itemCount) return;
for (var i=0, i<itemCount; i++) {
var codeName = document.getElementById(code[i]);
if(!codename || !codename.length) continue;
//do something here...
}
```
I got a working example here: <http://jsbin.com/uduxe4/15> | I don't know what `document` is, but you could try something like
```
if(document.getElementById('code'+[i]) == null)
{
//...do Something
}
```
so testing if it exists *before* you using it... |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | Try:
```
var codeName = document.getElementById(code[i]) || null;
if (codeName) {/* action when codeName != null */}
```
if you want to be sure codeName is an Object:
```
if (codeName && codeName instanceof Object) {
/* action when codeName != null and Object */
}
``` | ```
var codeList = document.getElementById('codeList');
if(!codeList && !codeList.value && !codeList.value.length) return;
var code = codeList.value.split(","),
itemCount = code.length;
if(!itemCount) return;
for (var i=0, i<itemCount; i++) {
var codeName = document.getElementById(code[i]);
if(!codename || !codename.length) continue;
//do something here...
}
```
I got a working example here: <http://jsbin.com/uduxe4/15> |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | After the `getElementById` call, `codeName` is either a DOM Element or null. You can use an alert to see which:
```
alert(codeName);
```
So `if (codename != null)` should work.
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger. | Try:
```
var codeName = document.getElementById(code[i]) || null;
if (codeName) {/* action when codeName != null */}
```
if you want to be sure codeName is an Object:
```
if (codeName && codeName instanceof Object) {
/* action when codeName != null and Object */
}
``` |
4,399,304 | Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
```
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
```
Is there any way to see if an object exists? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4399304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54197/"
] | After the `getElementById` call, `codeName` is either a DOM Element or null. You can use an alert to see which:
```
alert(codeName);
```
So `if (codename != null)` should work.
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger. | Would a try/catch work for you? **[Example](http://www.jsfiddle.net/subhaze/v4MAg/)**
```
function toDoStuff(elem) {
codeName = document.getElementById(elem);
if (!codeName) throw "Object isn't here yet!"
}
for (var i = 0; i < 5; i++) {
try {
toDoStuff('someElem');
} catch (err) {
if (err == "Object isn't here yet!") {
alert("Object isn't ready yet leaving loop!");
break;
}
}
}
``` |
27,322,689 | I have a program that dynamically generates UIButtons in the center of
the screen with push of another button.
The buttons are not updating the x-coordinates when I rotate the device.
Here is my code for creating buttons:
```
- (IBAction)createButton:(UIButton *)sender {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor redColor]];
[button addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(self.xCoord,self.yOffset,100.0,120.0);
[self.view addSubview:button];
_yOffset = _yOffset+130;
}
```
The XCoord and self.yOffset were set in viewDidLoad:
```
- (void)viewDidLoad {
[super viewDidLoad];
self.yOffset = 109;
self.xCoord = self.view.bounds.size.width/2-50;
}
``` | 2014/12/05 | [
"https://Stackoverflow.com/questions/27322689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4329921/"
] | for anyone interested here's how i got round this.
I created a shared service between the two controllers. and created a callback on the service. i registered the call back on ctrl2 so when the shared variable changed the controller2 will do what i want it to and scope is freshed.
```html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script>
angular.module('app1', ['app2'])
.controller('ctrl1', ['$scope', '$controller', 'appointmentSharedProperties',
function($scope, appointmentSharedProperties) {
$scope.name1 = 'Controller 1';
console.log('ctrl1');
//just something to put in the ddp
$scope.data = [{
id: 1,
name: 'test'
}, {
id: 2,
name: 'test2'
}];
$scope.makeChanged = function(value) {
//ddp has changed so i refresh the ui with some other data which is in got by ctrl2.
appointmentSharedProperties.setDetail(value);
console.log('in makeChanged: ' + value);
}
}
]).service('appointmentSharedProperties', function() {
var test = '';
var __callback = [];
return {
getDetail: function() {
return test;
},
setDetail: function(value) {
test = value;
if (__callback.length > 0) {
angular.forEach(__callback, function(callback) {
callback();
});
}
},
setCallback: function(callback) {
__callback.push(callback);
}
};
});
angular.module('app2', [])
.controller('ctrl2', ['$scope', 'appointmentSharedProperties',
function($scope, appointmentSharedProperties) {
$scope.name2 = 'Controller 2';
console.log('ctrl2');
var getdata = function() {
console.log('in getdata');
$scope.app2Data = appointmentSharedProperties.getDetail();
}
appointmentSharedProperties.setCallback(getdata);
}
]);
</script>
</head>
<body ng-app="app1">
<div ng-controller="ctrl1">
<p>here is: {{name1}}</p>
<p>here is: {{name2}}</p>
<select ng-model="d" ng-options="d as dat.name for dat in data track by dat.id" ng-change="makeChanged(d.name)"></select>
<div>
{{app2Data}}
</div>
</div>
</body>
</html>
``` | General example of how to pass variables from one controller to other
```
<html>
<head>
<meta charset="ISO-8859-1">
<title>Basic Controller</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<div ng-controller="ctrl1">
{{greeting}}
</div>
<div ng-controller="ctrl2">
{{dataToHtml2}}
</div>
</body>
</html>
```
This is the javascript file for this
```
var myApp = angular.module('myApp',[]);
myApp.service('sampleService', function(){
var temp = '';
this.setValue = function(data){
temp = data;
}
this.getValue = function(){
return temp;
}
});
myApp.controller('ctrl1', function($scope,sampleService) {
$scope.greeting = 'This line is in first controller but I exist in both';
var data= $scope.greeting;
sampleService.setValue(data);
});
myApp.controller('ctrl2', function($scope, sampleService){
$scope.dataToHtml2 =sampleService.getValue();
});
```
Here is the blog that explains this flow : [Frequently asked questions in angularjs](http://technology.vishalsrini.com/frequently-asked-questions-in-angularjs-for-intermediates-who-already-knows-angular/)
It has the demo of what I written. Happy coding..!! |
2,858,134 | I have created a control and the mosemove for that control makes it change color, but I want to change it back to default when my mouse moves out of that control. I would have thought WM\_MOUSELEAVE would do it but it didn't.
Thanks | 2010/05/18 | [
"https://Stackoverflow.com/questions/2858134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146780/"
] | That would be the correct message.
Are you calling [TrackMouseEvent](http://msdn.microsoft.com/en-us/library/ms646265(VS.85).aspx)? | You could try with WM\_MOUSELEAVE (we have this in a CView derived class )
But I think the best way is to use \_TrackMouseEvent.
Max. |
19,084,382 | Using RStudio --> CompilePDF
In a .Rnw document to be processed with pdflatex, I'd like to get a list of all
user (me) packages loaded via library() or require() in the document. I tried
to use sessionInfo(), as in
```
\AtEndDocument{
\medskip
\textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}.
}
```
however, what this prints is just the list of packages used by knitr itself,
>
> Packages used: digest, evaluate, formatR, highr, stringr, tools.
>
>
>
not those I explicitly referred to. I believe this is because knitr runs the
code chunks within an internal environment, but I don't know how to access that.
I know about the file cache/\_\_packages that is created with cache=TRUE; is there
any way to generate this automatically without caching? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19084382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873697/"
] | Without cache (`cache = FALSE`), what you want is basically
```
unique(c(.packages(), loadedNamespaces()))
```
With cache enabled, it is slightly more complicated, because the package names are cached as well; the second time you compile the document, these packages are not loaded unless you have invalidated the cache. In this case, as you have noticed, there is a file `cache/__packages`, and you can read the packages names there, so
```
unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages')))
```
You may want to make the code more robust (e.g. check if `cache/__packages` exists first), and exclude certain packages from the list (e.g. `knitr` and its friends), as @sebastian-c pointed out. | So what you want is all the packages which are loaded except the base packages and knitr. If I then list all the packages and exclude those, you'll get what you want:
```
p <- setdiff(.packages(),
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets",
"methods", "base"))
p
```
You'll have to make some exceptions say if you're making a knitr document about making things in knitr or if you want to explicitly load base packages. |
19,084,382 | Using RStudio --> CompilePDF
In a .Rnw document to be processed with pdflatex, I'd like to get a list of all
user (me) packages loaded via library() or require() in the document. I tried
to use sessionInfo(), as in
```
\AtEndDocument{
\medskip
\textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}.
}
```
however, what this prints is just the list of packages used by knitr itself,
>
> Packages used: digest, evaluate, formatR, highr, stringr, tools.
>
>
>
not those I explicitly referred to. I believe this is because knitr runs the
code chunks within an internal environment, but I don't know how to access that.
I know about the file cache/\_\_packages that is created with cache=TRUE; is there
any way to generate this automatically without caching? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19084382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873697/"
] | So what you want is all the packages which are loaded except the base packages and knitr. If I then list all the packages and exclude those, you'll get what you want:
```
p <- setdiff(.packages(),
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets",
"methods", "base"))
p
```
You'll have to make some exceptions say if you're making a knitr document about making things in knitr or if you want to explicitly load base packages. | The problem with this approach is that the \Sexpr{} within the \AtEndDocument{} block in the preamble is evaluated at
knit-time (the beginning of the .Rnw file, so it returns an empty list. In the generated .tex file, this appears as
```
\AtEndDocument{
\medskip
\textbf{Packages used}: .
}
```
The only way this will work is to include the code to generate this text explicitly at the end of the .Rnw file
(which in my case is a child documenht, e.g.,
```
...
\bibliography{graphics,statistics}
Inside child document:
\textbf{Packages used}: \Sexpr{setdiff(.packages(),
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets",
"methods", "base"))}.
``` |
19,084,382 | Using RStudio --> CompilePDF
In a .Rnw document to be processed with pdflatex, I'd like to get a list of all
user (me) packages loaded via library() or require() in the document. I tried
to use sessionInfo(), as in
```
\AtEndDocument{
\medskip
\textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}.
}
```
however, what this prints is just the list of packages used by knitr itself,
>
> Packages used: digest, evaluate, formatR, highr, stringr, tools.
>
>
>
not those I explicitly referred to. I believe this is because knitr runs the
code chunks within an internal environment, but I don't know how to access that.
I know about the file cache/\_\_packages that is created with cache=TRUE; is there
any way to generate this automatically without caching? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19084382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873697/"
] | So what you want is all the packages which are loaded except the base packages and knitr. If I then list all the packages and exclude those, you'll get what you want:
```
p <- setdiff(.packages(),
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets",
"methods", "base"))
p
```
You'll have to make some exceptions say if you're making a knitr document about making things in knitr or if you want to explicitly load base packages. | A somewhat different, perhaps more explicit and detailed approach, expanding on answers given previously. This would appear in the `\backmatter` of a book. The value `nColOut` is the number of columns of the printed table containing the list of packages used.
```
\cleardoublepage
\printindex
\cleardoublepage
\chapter*{Packages}
<<packages, cache = FALSE, echo = FALSE, warning = FALSE, results = "asis">>=
nColOut = 7
packsAll <- unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages')))
packsReduced <- setdiff(packsAll,
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base"))
howManyPacks <- packsReduced %>%
length()
numLines <-
tibble(numPacks = howManyPacks + 0:(nColOut - 1),
n = numPacks %% nColOut)
howManyToAdd <- numLines %>%
filter(n == 0) %>%
mutate(diff = numPacks - howManyPacks) %>%
pull(diff)
packsReduced %>%
sort() %>%
as_tibble() %>%
add_row(value = rep('', howManyToAdd)) %>%
mutate(id = rep(1:(length(value) / nColOut), nColOut),
col = rep(letters[1 : nColOut], each = length(value) / nColOut)) %>%
pivot_wider(names_from = col, values_from = value) %>%
select(-id) %>%
kable("latex", booktabs = TRUE, longtable = TRUE) %>%
kable_styling(latex_options = "repeat_header") %>%
row_spec(0, align = "c")
@
``` |
19,084,382 | Using RStudio --> CompilePDF
In a .Rnw document to be processed with pdflatex, I'd like to get a list of all
user (me) packages loaded via library() or require() in the document. I tried
to use sessionInfo(), as in
```
\AtEndDocument{
\medskip
\textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}.
}
```
however, what this prints is just the list of packages used by knitr itself,
>
> Packages used: digest, evaluate, formatR, highr, stringr, tools.
>
>
>
not those I explicitly referred to. I believe this is because knitr runs the
code chunks within an internal environment, but I don't know how to access that.
I know about the file cache/\_\_packages that is created with cache=TRUE; is there
any way to generate this automatically without caching? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19084382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873697/"
] | Without cache (`cache = FALSE`), what you want is basically
```
unique(c(.packages(), loadedNamespaces()))
```
With cache enabled, it is slightly more complicated, because the package names are cached as well; the second time you compile the document, these packages are not loaded unless you have invalidated the cache. In this case, as you have noticed, there is a file `cache/__packages`, and you can read the packages names there, so
```
unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages')))
```
You may want to make the code more robust (e.g. check if `cache/__packages` exists first), and exclude certain packages from the list (e.g. `knitr` and its friends), as @sebastian-c pointed out. | The problem with this approach is that the \Sexpr{} within the \AtEndDocument{} block in the preamble is evaluated at
knit-time (the beginning of the .Rnw file, so it returns an empty list. In the generated .tex file, this appears as
```
\AtEndDocument{
\medskip
\textbf{Packages used}: .
}
```
The only way this will work is to include the code to generate this text explicitly at the end of the .Rnw file
(which in my case is a child documenht, e.g.,
```
...
\bibliography{graphics,statistics}
Inside child document:
\textbf{Packages used}: \Sexpr{setdiff(.packages(),
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets",
"methods", "base"))}.
``` |
19,084,382 | Using RStudio --> CompilePDF
In a .Rnw document to be processed with pdflatex, I'd like to get a list of all
user (me) packages loaded via library() or require() in the document. I tried
to use sessionInfo(), as in
```
\AtEndDocument{
\medskip
\textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}.
}
```
however, what this prints is just the list of packages used by knitr itself,
>
> Packages used: digest, evaluate, formatR, highr, stringr, tools.
>
>
>
not those I explicitly referred to. I believe this is because knitr runs the
code chunks within an internal environment, but I don't know how to access that.
I know about the file cache/\_\_packages that is created with cache=TRUE; is there
any way to generate this automatically without caching? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19084382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873697/"
] | Without cache (`cache = FALSE`), what you want is basically
```
unique(c(.packages(), loadedNamespaces()))
```
With cache enabled, it is slightly more complicated, because the package names are cached as well; the second time you compile the document, these packages are not loaded unless you have invalidated the cache. In this case, as you have noticed, there is a file `cache/__packages`, and you can read the packages names there, so
```
unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages')))
```
You may want to make the code more robust (e.g. check if `cache/__packages` exists first), and exclude certain packages from the list (e.g. `knitr` and its friends), as @sebastian-c pointed out. | A somewhat different, perhaps more explicit and detailed approach, expanding on answers given previously. This would appear in the `\backmatter` of a book. The value `nColOut` is the number of columns of the printed table containing the list of packages used.
```
\cleardoublepage
\printindex
\cleardoublepage
\chapter*{Packages}
<<packages, cache = FALSE, echo = FALSE, warning = FALSE, results = "asis">>=
nColOut = 7
packsAll <- unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages')))
packsReduced <- setdiff(packsAll,
c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base"))
howManyPacks <- packsReduced %>%
length()
numLines <-
tibble(numPacks = howManyPacks + 0:(nColOut - 1),
n = numPacks %% nColOut)
howManyToAdd <- numLines %>%
filter(n == 0) %>%
mutate(diff = numPacks - howManyPacks) %>%
pull(diff)
packsReduced %>%
sort() %>%
as_tibble() %>%
add_row(value = rep('', howManyToAdd)) %>%
mutate(id = rep(1:(length(value) / nColOut), nColOut),
col = rep(letters[1 : nColOut], each = length(value) / nColOut)) %>%
pivot_wider(names_from = col, values_from = value) %>%
select(-id) %>%
kable("latex", booktabs = TRUE, longtable = TRUE) %>%
kable_styling(latex_options = "repeat_header") %>%
row_spec(0, align = "c")
@
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.