text:
Q: Adwords Exported CSV Report Parsing in PHP not working I have created a table which I am trying to populate with data from a CSV file exported from AdWords. Following is my table -

The table is only displayed when ajax call is successful because the table HTML is returned by the page I make ajax request to. As you can see I'm getting the table columns and the table is being populated properly but I'm not getting the values for some reason.
GENERATING TABLE WITH VALUES FROM FUNCTION
        $campaigns_data = getCampaignsCSVData($account_name);

        $campaigns_columns = $campaigns_data['columns'];
        $campaigns_values = $campaigns_data['values'];

        if(!empty($campaigns_columns) && !empty($campaigns_values)){
            echo '
Campaign Totals
'.PHP_EOL;
            getCampaignsTable($campaigns_columns,$campaigns_values,$campaigns_included_cols,'Clicks','DESC');
        }

FUNCTION TO GENERATE CAMPAIGNS TABLE
function getCampaignsTable($columns,$values,$included_cols,$sort_by='',$sort_dir='ASC'){

        $values_by_column_key = array();

        foreach($values as $key=>$row){
            $processed_cols = array();

            foreach($row as $key=>$col){
                if(is_numeric(str_replace(',','',$col))){
                    $col = str_replace(',','',$col);
                }

                if($col[0] == '$'){
                    $processed_cols[$columns[$key]] = str_replace('$','',$col);
                }else{
                    $processed_cols[$columns[$key]] = $col;
                }
            }

            $values_by_column_key[] = $processed_cols;
        }

        if(!empty($sort_by)){
            usort($values_by_column_key, function($a,$b)use($sort_by,$sort_dir){

                if($sort_dir == 'ASC'){
                    return $a[$sort_by] > $b[$sort_by];
                }elseif($sort_dir == 'DESC'){
                    return $a[$sort_by] < $b[$sort_by];
                }
            });
        }

        echo '
'.PHP_EOL;
            echo '
'.PHP_EOL;
                echo '
'.PHP_EOL;

                    if(!empty($included_cols)){
                        foreach($included_cols as $col){
                            echo ''.$col['label'].'	'.PHP_EOL;
                        }
                    }

                echo '
'.PHP_EOL;
            echo '
'.PHP_EOL;
            echo '
'.PHP_EOL;

            $row_count = 0;

            foreach($values_by_column_key as $key1=>$row){
                $row_count++;

                if($row_count <= RESULT_LIMIT){
                    echo '
'.PHP_EOL;

                    foreach($included_cols as $key2=>$inc_cols){
                        if($inc_cols['format'] == 'currency'){
                            echo ''.$inc_cols['currency_symbol'].$row[$key2].'	'.PHP_EOL;
                        }else{
                            echo ''.$row[$key2].'	'.PHP_EOL;
                        }
                    }

                    echo '
'.PHP_EOL;
                }
            }

            echo '
'.PHP_EOL;
        echo '
'.PHP_EOL;
    }

FUNCTION TO READ AND PARSE CSV FILE
function getCampaignsCSVData($account){

        $data = array();

        $dir = ADWORDS_REPORTS_DIR.$account.'/';

        $filename = ADWORDS_CAMPAIGN_FILE;
        $filepath = $dir.$filename;

        $row_count = 0;

        if(file_exists($filepath)){
            $csvfile = @fopen($filepath,'r');

            if($csvfile){
                while(!feof($csvfile)){
                    $row = fgets($csvfile);

                    $row = preg_replace("/[^a-zA-Z ]/", "", $row);

                    $row_count++;

                    $row_data = '';

                    if(stristr($row,CAMPAIGNS_REPORT_IN_COLUMNS_WORD)){
                        $row_data = str_replace('Impr.','Impressions',$row);
                        $row_data = str_replace('Interactions','Clicks',$row_data);

                        $data['columns'] = str_getcsv($row_data);
                        $columns_row_index = $row_count;

                    } elseif($row_count > $columns_row_index && !empty($columns_row_index)){
                        $row_data = $row;

                        if(!stristr($row,'Total') && !empty($row)){
                            $data['values'][] = str_getcsv($row_data);
                        }
                    }
                }
            }

            fclose($csvfile);
        }else{
            $data = false;
        }

        return $data;
    }

This code has been working for a long time but it suddenly stopped working recently without changing anything. I can't seem to get my head around it because I can't find any error. Please help. Thanks!


text:
Q: How to convert to formula to disjunctive normal form (DNF)? I know how to convert a formula to a CNF, but how do I convert to a DNF?
Can I use the first three steps of CNF and change the distributive transformation to

*

*$P \land (Q \lor R) \text{ becomes } (P \land Q) \lor (P \land R)$

*$(P \lor Q) \land R \text{ becomes } (P\land R)\lor (Q \land R)$
?

A: Yes. Like putting a statement into CNF, first rewrite all operators in terms of $\land$, $\lor$, and $\neg$, and then bring all negations inside (using DeMorgans's Laws) as far as possible, and removing any Double Negations.  At this point, the statement is in Negation Normal Form (NNF)
Then, to get the statement into  CNF, distribute $\lor$ over $\land$
But to get it into DNF, distribute $\land$ over $\lor$
Example:
Starting statement:
$P \rightarrow (Q \land (\neg (\neg R \land S))$
rewrite into $\land$, $\lor$, and $\neg$:
$\neg P \lor (Q \land (\neg (\neg R \land S))$
bring negations inside with DeMorgan:
$\neg P \lor (Q \land (\neg \neg R \lor \neg S))$
remove double negations:
$\neg P \lor (Q \land (R \lor \neg S))$
Now it is in NNF
To put NNF into CNF, distribute $\lor$ over $\land$:
$(\neg P \lor Q) \land (\neg P \lor R \lor \neg S)$
To put NNF into DNF, distribute $\lor$ over $\land$:
$\neg P \lor (Q \land R) \lor (Q \land \neg S)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing running processes of two linux devices I have two embedded devices with identical hardware, which I am developing app for. Identical apps are running on both devices, however memory consumption is significantly larger on device A compared to  device B. I've gathered process list on both devices via:
ps -A > psListDeviceA.txt
and
ps -A > psListDeviceB.txt
Both files were transferred to fully functional Ubuntu desktop workstation. How do I compare these files so I can see which processes are running in addition on device with higher memory consumption?

A: You could try this,
ps -o pid,user,%mem,command ax > FileDeviceA

and
ps -o pid,user,%mem,command ax > FileDeviceB

to get the procceses on both devices with memory.
To take a look at the difference and sort it use
diff FileDeviceA FileDeviceB | sort -b -k3 -r.

Good luck with your application.


text:
Q: brew install mysql, error when trying to stop the server After:
brew install mysql
mysql_install_db

and I try to stop the MySQL server:
$ mysql.server stop
Shutting down MySQL
.. ERROR! Manager of pid-file quit without updating file.

How can I fix the above error? Thanks!
Info:
$ mysql -v
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.51 Source distribution

A: The install instructions for mysql suggest copying /usr/local/Cellar/mysql/5.1.54/com.mysql.mysqld.plist to ~/Library/LaunchAgents so that Mac OS X will automatically launch mysqld when you login.
If you've set up mysqld this way then the launchd process, which controls LaunchAgents in Mac OS X v10.4 and above, will automatically restart the mysqld process as soon as it is being killed by the mysql.server stop command. This might be the reason for the error message, because the server is being automatically restarted.
Just tested this on my Mac. Ran the mysql.server stop command ten times and each time 'launchd' restarted the msyqld process after about a second. Six times the command ended with a "SUCCESS!" message. Four times it ended with the "ERROR! Manager of pid-file quit without updating file" message.
UPDATE: Just realised I didn't mention how to stop the mysqld server if it is being started by launchd.
Here is the command to stop the mysqld daemon.
launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist

A: Have you tried running killall mysqld?

A: Give this a try..

*

*Navigate to the problem's parent directory cd YOURPATH/usr/local/mysql

*rm -rf *.local.err (deletes file)

*touch YOURUSERNAME.local.pid (generates new *.local.pid file the error thrown was complaining about)

*cd back into your project and restart mysql using mysql.server start


text:
Q: Advantage over using inner or nested class in AsynTask Whether in Android or Java, when we call an AsyncTask or SwingWorker it can be used a inner or nested class. I'm concerned about memory leak issues most in Android devices. If you take an inner class the activity reference it's automatically passed. By taking a nested class you'll have to manually pass the activity reference so inner/nested are basically doing the same work.
One problem I've had is that the activity dies and when the AsyncTask ends it will broke the app. I know and have used headless fragments, but here my question is about using inner/nested classes in both Android and Java, which one do you recommend? For example, I perform this task in JFrame, of course I want to use a specific class that does the particular task (one class for each task) instead of placing inline code.
new SwingWorker<Void, Void>() {
        private Exception exception = null;

        @Override
        protected Void doInBackground() throws Exception {
            try {
                callback.login();
            } catch(SQLException e) {
                exception = e;
            }

            return null;
        }

        @Override
        protected void done() {
            if(exception != null) {
                // show fail
            } else {
                update();
            }
        }
    }.execute();
}

A: I would make a class as inner class if the class has no identity without parent class and mark the inner class as static to avoid the issues that you have mentioned.
In Android you can pass the Weak reference of parent Activity to avoid leaks and ensure that AsyncTask is cancelled in onStop. Generally try to avoid usage AsyncTask as much as possible. Use it for trivial usecases. For major use-cases, rely on Services/IntentService.
From programmer's point of view its quite convenient to just create a inner class and let the class access the parent class's data. But it causes some workload on compiler. Internally compiler generates getter methods and adds it your code before generating .class files. This is not a great idea since it impacts the encapsulation of the parent class

A: In Android, you can handle this situation with the implementation of interface. Let us have an interface like the following.
public interface HttpResponseListener {
    void httpResponseReceiver(String result);
}

Now from your Activity while calling the login function through an AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {

    public HttpResponseListener mHttpResponseListener;
    private final Context mContext;

    HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
        this.mContext = mContext;
        this.mHttpResponseListener = listener;
    }

    @Override
    protected String doInBackground(Void... params) {
        String result = null;

        try {
            result = login(mContext); // use the context if necessary
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onPostExecute(final String result) {
        mHttpResponseListener.httpResponseReceiver(result);
    }

    @Override
    protected void onCancelled() {
        mHttpResponseListener.httpResponseReceiver(null);
    }
}

Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
    // ... Other code and overriden functions

    public void callAsyncTaskForLogin() {
        // Pass the listener here
        HttpRequestAsyncTask loginTask = new HttpRequestGetAsyncTask(
            YourActivity.this, this);
            loginTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    public void httpResponseReceiver(String result) {
        // Get the response callback here
        // Do your changes in UI elements here.
    }
}

This is how you can avoid the potential memory leak, as you are changing the UI elements using the context of the activity inside your activity. When the background AsyncTask finishes, it passes the responsibility to the callback function and does not hold the reference of the context.
In case of finishing of the application, the AsyncTask will execute and will pass the reference to the calling activity and in that case, the activity will not be available to receive. However, this will not generate any memory leak either.


text:
Q: find minimal polynomial of $T(p)=p'+p$ I'm trying to solve the following question:
let $T: \mathbb C_n[x] \to \mathbb C_n[x]$, $T(p)=p'+p$
find the characteristic and minimal polynomial of $T$.
What I'm trying to do is the following: I saw how $T$ interacts with the standard basis of polynomials, $1,x,x^2,...x^n$, and I wrote down $T$ as a matrix so I can easily find its characteristic polynomial.
Lucky for us, the matrix $T$ is triangular:
$T=\begin{pmatrix} 1 & 1 & 0 & 0 & 0&\cdots & 0 \\0 & 1 & 2 & 0 &0&\cdots & 0 \\0&0&1&3&0&\cdots & 0\\ \vdots & \vdots & \vdots &\ddots &\ddots &\cdots & 0\end{pmatrix}$
I'm not that good at mathjax, basically, below the diagonal there are only $0$. on the diagonal only $1$, and at index $(k-1,k)$ there is $k-1$.
It is very easy to see that the characteristic polynomial $p_T(x)=(x-1)^{n+1}$.
The minimal polynomial is harder to find. I know they are equal because I looked at the answers, but how do I prove it?

A: Note that $T-1$ maps $p\mapsto p'$. Clearly $(T-1)^n\ne0$, as is witnessed by $x^n\mapsto\ldots\mapsto n!$.


text:
Q: Google appmaker making a confirmation dialog I want to ask a user for confirmation upon clicking submit on a form. I am not sure what tools to use to implement the logic.
I thought this would be possible with showDialog's callback even though I wasn't sure how to communicate the "ok" and "cancel" signals, in any case it turns out that the success callback is called as soon as the dialog displays (maybe on attach or otherwise). So I am not sure how to have some clean logic that does the confirmation.
In more details, the goal is to upon submission prepare lots of data for the item/record creation, then present a summary to the user and ask for confirmation. What I hoped to achieve was to have after data preparation a call to a dialog that will halt the execution at that call and return with confirmation or denial at which point the record will be created or not.
One way I see how the confirmation can be done is to send all the data to the dialog page which in turn will create the record upon confirmation. But this seems unnecessary, non-reusable and honestly tedious, so is there a better way of making a confirmation dialog?

A: Your form and the confirmation dialog should both have the same datasource, i.e. the create datasource should be same for both. Once you have this set up, you bind the values to labels/textboxes inside the dialog. Then, all you have to do is to create the item on the dialog's OK button or just close the dialog on the dialog's CANCEL button.


text:
Q: Create table stored procedure in SQL Server I have a table Persons (Id, Name), and I need to create a table with name Results_NameUser (where NameUser is the name of the user). This table is automatically generated after I create a user on my Form. I need use a stored procedure for this operation, but I don't know how to write this.
I have preliminarily code of a procedure (this procedure will called in code after create user)
CREATE PROCEDURE createResult
    @userName VARCHAR(50)
AS
BEGIN
    CREATE TABLE Result_@userName
    (
        resultId UNIQUEIDENTIFIER NOT NULL,
        scores INT
    );
END

But the code is not correct. Please, tell me, how create this procedure

A: I would add a check for an existing table before I try to create one, something like....
CREATE PROCEDURE createResult
    @userName NVARCHAR(120)
AS
BEGIN
  SET NOCOUNT ON;

  Declare  @Create_Sql  NVARCHAR(MAX)
         , @Drop_Sql    NVARCHAR(MAX)
         , @TableName   SYSNAME     = N'Result_' + @userName

 IF OBJECT_ID( @TableName , 'U') IS NOT NULL
  BEGIN
      SET @Drop_Sql = N' DROP TABLE ' + QUOTENAME(@TableName) + N';' ;
      Exec sp_executesql @Drop_Sql
  END

 SET @Create_Sql = N' CREATE TABLE ' + QUOTENAME(@TableName)
                +  N' (resultId uniqueidentifier not null, '
                +  N' scores int); ';

 Exec sp_executesql @Create_Sql

END

Also use QUOTENAME() to protect yourself against SQL-Injection attacks.


text:
Q: Certificados SSL para 3 web en el mismo servidor Necesito instalar certificados SSL para 3 web que están en un mismo servidor. He estado leyendo y creo que si tienen la misma IP no es posible pero no entiendo muy bien lo de la misma IP. Me imagino que el servidor sí tendrá la misma IP pero los dominios no.
Los certificados los conseguiría de Let´s Encrypt pero a ver si me pueden guiar en cómo instalarlos y si es posible. En principio no contemplo el Certificado Multidominio. El servidor es de Hostalia y creo que es dedicado.
Cualquier ayuda o comentario será bienvenido.

A: Este es un problema que se solventó con el uso de las extensiones SNI de TLS detalladas en la RFC3546 (a parte de los certificados comodín y los certificados SAN).
El problema radicaba en que el navegador debe establecer y asegurar la conexión HTTPS (apretón de manos) ANTES de poder enviar la cabecera host que permite al servidor elegir entre un sitio web virtual u otro.
Por desgracia las extensiones SNI no están soportadas por todos los navegadores, además, tampoco por todos los servidores web.
Apache tiene un ejemplo de cómo configurar un servidor apache con varios certificados sobre una misma dirección IP.
Para otros servidores web habría que consultar la compatibilidad en el manual del producto.
Si el servidor es dedicado, tal y como indicas, es probable que puedas usar SNI, en caso contrario deberías contactar con soporte de tu proveedor para conocer la forma en la que se podría activar o usar dicha extensión en su servicio.


text:
Q: Implicit conversion causing error part of the time I have been scratching my head about this one for the last day or so - I just can't see why a procedure works in one environment, but then fails in another due to a conversion error (same data, same code).
The plan for (a heavily cut down version of) the working server is here: https://www.brentozar.com/pastetheplan/?id=B1jZWTfOf
(This doesn't seem to be working, so I've uploaded the plan XML to pastebin here: https://pastebin.com/47Q6nniw)
A bit of background for the relevant columns causing the problem:
The propertyInst table holds a column called ValueStr, which is an nvarchar data type. The GeneralLedgerCode table has a column id of data type int. Our developers are attempting to join between the two tables. The ValueStr column holds text data, XML data, int data, decimal data etc. As a matter of course we decided to add a function to ensure only integers are parsed (ISNUMERIC(ValueStr) = 1). What we didn't realise is that this would then also try to convert any decimal values - this is causing a conversion error in production of the nature:
Conversion failed when converting the nvarchar value '0.1' to data type int.
My question here is, given that the Table Scan of the propertyInst table will be picking up all numeric values including decimals, why is the implicit conversion in the scalar operator then not failing with the same conversion error? The output of the ISNUMERIC query returns some of these decimals. I can't see how the attached plan is working at all.
Does an implicit conversion operator never fail outright, and is the conversion error coming from the probe residual in the hash match operator? Then again, how could the value even make it to the operator when it would fail the implicit conversion?
As a small assistance, the plan image is here, with the Compute Scalar I'm asking about circled.

In addition, I can see that there are no actual rows logged against the scalar operator - does this mean the engine decided not to use that particular operator at runtime due to the conversion error?

Any help would be appreciated.

A: The calculation of the compute scalar operator is deferred to when it is actually used (the probe residual of Node ID = 1) and the rows that would have failed for you are filtered out by the previous Hash Match (Node ID = 3).
Have a look at Compute Scalars, Expressions and Execution Plan Performance by Paul White for more information.
There is no indication in execution plans that evaluation of an expression is deferred, or when (at which node) it was actually evaluated. You can normally code defensively around this using CASE (which comes with an evaluation order guarantee) and/or TRY_CONVERT.
Related Microsoft feedback: SQL Server should not raise illogical errors


text:
Q: How to get symbol of pressed key IE8-? I have this code:
document.onkeydown = function(event) {
    if (!event) {
        event = window.event;
    }
    var keyCode = event.keyCode || event.which;

   console.log(event);
   console.log(keyCode);
}

This works in IE8 browser. But, I still need to know the symbol of the pressed key.
In newer browsers, I can use "e.key". I tried to output event to the console, but I didn't find anything similar to the symbol of the pressed key. How do I solve this?

A: The answer has been found. This code works even in IE5 (checked on the Emulator).
document.onkeydown = function(event) {
  if (!event) {
    event = window.event;
  }
  var keyCode = event.keyCode || event.which;
  var pressedKeySymbol = event.key || String.fromCharCode(keyCode).toLowerCase();
  console.log(event);
  console.log(keyCode);
}

Thank very much to Valerii from the glorious island of Sakhalin.


text:
Q: Load file inside a constructor, bad practice? Is this a bad practice?
I've seen few peoples say that constructor should not do the real work.
class FooConfig {
   public FooConfig(File file) {
      loadFile(file);
   }

   private void loadFile(File file) {
      // do something...
   }
}

Or I should do this instead?
class FooConfig {
   private final File file;

   public FooConfig(File file) {
      this.file = file;
   }

   public void loadFile(File file) {
      // do something...
   }
}

FooConfig config = new FooConfig(file);
config.loadFile();

Thank you.

A: It depends, but in general, unless you know what you're doing, there is nothing wrong in it. It's actually more simpler to initialize in the constructor. This is what the caller of your code would expect anyway: an object accepting a file is expected to process it upon initialization. The caller would also avoid bugs where they forget to call the initialization method manually.
I'm pretty sure that if you look at third-party libraries (e.g. Spring), you will find occurrences of such constructors accepting files. For example, FileSystemXmlApplicationContext offers a parameter to do a "refresh" based on the input files, so that the user can have control over the refreshing of the context (either the constructor does it, or the refresh has to be done manually).


text:
Q: Invoked function not returning result in React I have 2 functions one is invoking another. The inner invoked function add is checking if in this.state.selectedBookList exists bookName got from an input field, if not exists its adding bookName to this.state.selectedBookList, otherwise is returning to function that is invoked by. But I have the problem that the result of book.selectedBookName === bookName is always false. that cannot be, and my arr is at the end always empty. Can any check, what is wrong?
import React, { Component } from 'react';
import EnteredBooks from '.././components/EnteredBooks/EnteredBooks';

class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
            bookName: '',
            bookDescription: '',
            bookUrl: '',
            bookPrice: '',
            enteredBookList: [],
            selectedBookId: '',
            selectedBookName: '',
            selectedBookDescription: '',
            selectedBookUrl: '',
            selectedBookPrice: '',
            selectedBookList: [],
            activeIndex: '',
        }
    }

        submitHandler = (event) => {

            event.preventDefault();

            let bookId = Math.floor((Math.random() * 100) + 1);
            let bookName = this.state.bookName;
            let bookDescription = this.state.bookDescription;
            let bookUrl = this.state.bookUrl;
            let bookPrice = this.state.bookPrice;

            this.setState({
                enteredBookList: this.state.enteredBookList.concat({bookId, bookName, bookDescription, bookUrl, bookPrice})
            })
        }

     add = (bookName, bookUrl, bookDescription, bookPrice, index) => {
            let arr = this.state.selectedBookList;

            let found = arr.some(book => {
                return book.selectedBookName === bookName;
            });

            if (!found) {
                return arr.concat({bookName, bookUrl, bookDescription, bookPrice, index});
            }
             console.log(found);
        }

    selectedBookHandler = (bookName, bookUrl, bookDescription, bookPrice, index) => {
        let arr = this.add(bookName, bookUrl, bookDescription, bookPrice, index);

        this.setState({
            selectedBookName: bookName,
            selectedBookUrl: bookUrl,
            selectedBookDescription: bookDescription,
            selectedBookPrice: bookPrice,
            selectedBookId: index
        });
        console.log(this.state.selectedBookList);
    }

    render() {

        const enteredBooks = this.state.enteredBookList.map((enteredBook, index) => {
            const active = this.state.activeIndex;
            return <EnteredBooks
                key={index}
                enteredBook={enteredBook}
                active={index === active}
                selected={this.selectedBookHandler.bind(this, enteredBook, enteredBook.bookName, enteredBook.bookUrl,
                    enteredBook.bookDescription, enteredBook.bookPrice, index)}
            />
        });

        return (

                   <form>

                            Product name:
                            <input
                                type="text"
                                placeholder="Book"
                                value={this.state.BookName || ''}
                                onChange={event => this.setState({bookName: event.target.value})}
                            />

                            Product description:
                            <textarea
                                placeholder="Sample description..."
                                value={this.state.bookDescription || ''}
                                onChange={event => this.setState({bookDescription: event.target.value})}
                            >
                            </textarea>

                            Product image:
                            <input
                                type="text"
                                placeholder="http://...jpg"
                                value={this.state.bookUrl || ''}
                                pattern="https?://.+" required
                                onChange={event => this.setState({bookUrl: event.target.value})}
                            />

                            Product price:
                            <input
                                type="number"
                                min="0"
                                placeholder="20.5"
                                value={this.state.bookPrice || ''}
                                onChange={event => this.setState({bookPrice: event.target.value})}
                            />

                        <button
                            type="submit"
                            onClick={event => this.submitHandler(event)}
                        >
                            Add a new Task
                        </button>
                    </form>

                       {enteredBooks}

        );
    }
}

export default App;

A: The .some() function invoked not using the predicate watch to test against each element of the array.
It needs to use the predicate to test against each element by changing watch to book as follows:
let found = arr.some(book => {
  return book.selectedBookName === bookName;
})

As @Andreas pointed out below, the arr.concat function does not change the change the state.selectedBookList array but returns a new one. You will also have to set this to the state once it is returned from .add as follows:
let arr = this.add(bookName, bookUrl, bookDescription, bookPrice, index);

this.setState({
   selectedBookList: arr,
   selectedBookName: bookName,
   selectedBookUrl: bookUrl,
   selectedBookDescription: bookDescription,
   selectedBookPrice: bookPrice,
   selectedBookId: index
});

Also should let arr = this.state.selectedWatchList; be this.state.selectedBookList?

A: When adding a book and it's not found you are concatenating it to you contextual array arr instead of your selectedWatchlist.
return arr.concat({bookName, bookUrl, bookDescription, bookPrice, index});

Should be
return this.state.selectedWatchList.concat({bookName, bookUrl, bookDescription, bookPrice, index});

A: Based on your code snippet :
this.state.selectedWatchList is not defined in this.state = {};
i think you use this.state.selectedWatchList instead of this.state. selectedBookList
let arr = this.state.selectedWatchList;


text:
Q: How to use array elements as labels using for loop in Template Django? I have the following template code,presently i m getting for loop counter as label for my formset. How can i get elements of array 'month' (eg  month.counter, where counter is loop) as my label?? I tried {{month.forloop.counter}} but that didnt worked

<title>Actuals</title>

Actuals Data

Your Account Number is : {{ Account_Number }}

You Chose {{ Year }} {{month}} as period.

{% if form.errors %}

   Please correct the error{{ form.errors|pluralize }}below.

   {% endif %}

<form action="." >
    {{ formset.management_form }}

      {% for form in formset %}

    {{form.id}}

                {{ form.Value.errors }}
                {{months}}.{{forloop.counter}}
                {{ form.Value }}

      {% endfor %}

</form>

A: You can do this using custom templatetags. Sample code is given below:
add following to /{app_name}/templatetags/app_tags.py
from django import template
register = template.Library()

@register.filter
def month(value, counter):
    try:
        month = value[counter]
    except IndexError:
        month = ""
    return month

put following in your template
{% load app_tags %}

............
............

{% for form in formset %}
    {{form.id}}

        {{ form.Value.errors }}
        {{ months|counter:forloop.counter }}
        {{ form.Value }}

{% endfor %}

............
............

View this link, some person has also tried different methods to do this; although none of them worked. ;)

A: There isn't ready-made filter/tag for this in django template.
You could try writing your custom filter/tag. Refer Custom template tags and filters


text:
Q: Cant locate a SQL Server backup job that is running and failing There is a backup job that is running for master and msdb which is trying to use Azure blob storage as the backup location and I dont know where it's configured.
I need to delete this job but cannot find it anywhere. The only reason I know its running is because it's failing and littering up the SQL logs. There are no maintenance plans or scheduled jobs running any backups. I am using Azure Recovery Vault with VM agent tools to do our backups and those are all working as expected.
At some point someone must of set up a job, script, or something that keeps trying to take these backups but for the life of me I cannot find where/how it's running. Are there any recommended places (queries, DMVs. etc) I can look to locate where/what is running this?
What I know:

*

*It tries daily to run and continues to try for a few hours

*There are no SQL Agent Jobs

*There are no maintenance plans

*It gets logged to the SQL logs

*It gets logged to windows event viewer under 'Windows Logs > Application'

A: Based on the comment from Jeff, the solution was disabling the Azure Managed Backups that had previously been configured.


text:
Q: Python 2D-plotting of already binned arrays I have two really large arrays that can't fit in memory at once. I am interested in plotting a 2D histogram of these two arrays with a colorbar. In my case I loop over subsequent chunks of arrays and keep appending first data to x and y, such that:
n_bins=99
histogram = np.zeros(shape=(1,n_bins), dtype=np.float64)
histogramy = np.zeros(shape=(1,n_bins), dtype=np.float64)

and below happens in each (for) loop iteration when desired chunk length of x is reached:
add_coip, _ = np.histogram(np.asarray(x)[:], bins=(xedges))
add_coipy, _ = np.histogram(np.asarray(y)[:], bins=(yedges))

histogramx += add_coip.astype(np.float64)
histogramy += add_coipy.astype(np.float64)
x,y=[],[] # reset lists to append next chunk

Though I get histogramx and histogramy binned properly, I am unable to plot a 2D histogram using these arrays. Note that histogramx and histogramy doesn not contain data, rather a binned-version of the data. Any suggestions please?
PS: I understand using plt.bar as in this post but that's for a 1D plot!

A: In case someone else comes across this, you can use plt.matshow as explained here, it has many of the options available that work for plt.hist2d.


text:
Q: java numeric type conviersion when the underlying platform is big endian I'm wondering what happens when I write the following java code on a big-endian platform:
int a = 1;
byte b = (byte)a;

On a little-endian platform, the layout of variable a's four bytes are x01000000, so converting a to a byte, we still get x01, which makes b equals to 1. However, on a big-endian platform, a is laid out as x00000001, so will b still equal to x01? If it does, how does this magic happen?

A: Operations are performed in registers in the CPU, not in memory.  Registers are neither big-endian nor little-endian and they are not randomly accessible.
In any case, the behaviour is defined in the Java Language Specification as keeping the lower bits in each case, so it wouldn't matter how the CPU works.

how does this magic happen?

No magic, the CPU just discards the higher bits. (Technically the CPU may also do a sign extension as many CPUs have 32-bit or 64-bit registers)  How those bytes were stored in memory before it did this doesn't matter.


text:
Q: Setting Up SYS_REFCURSOR in PL\SQL to return dataset I have a PL\SQL that returns a data set that essentially verifies volumes by account||product in two different tables.
My end goal is to have this data set pull directly into a spreadsheet (using Excel-VBA) by passing date parameters (provided through Excel) and calling the stored-procedure.
After reading a bit on PL\SQL it appears that I need a cursor variable to store the end result data set that is provided so I can then write it to the spreadsheet (as a recordset).
Following examples online, I've written my procedure like so
CREATE OR REPLACE PROCEDURE PROC_REG_SPLIT_RECON (dStart IN Date, dEnd IN Date)
-- procedure to check regional splits creation is okay
-- procedure checks volumes by account and product from FACT_TRADE_PRESPLIT_ROLLUP to FACT_TRADE_ROLLUP

-- SQLDeveloper doesn't like this section and I can't figure out how to set this up correctly, no matter what I do and research.

RETURN SYS_REFCURSOR
AS
l_return SYS_REFCURSOR;
-- end of section not working

BEGIN

OPEN l_return FOR

    SELECT OpStats.Account, OpStats.Platform, OpStats.Volume OpStatsVol, RegSplits.Volume RegSplitsVol, (OpStats.Volume-RegSplits.Volume) Difference FROM

   (a bunch of union queries) OpStats,

   (a bunch of other union queries) RegSplits

WHERE OpStats.Account = RegSplits.Account (+) And OpStats.Platform = RegSplits.Platform (+)
ORDER BY OpStats.Account ASC, OPStats.Platform DESC;

RETURN l_return;

END;

FWIW, the queries work fine and return results as expected. Does anyone know why my PL\SQL is not compiling? Or if I am way off base in my approach?

A: You are creating a Oracle procedure and a procedure cannot have a RETURN keyword with a specified return datatype. Create a Oracle function to do what you want to do.
CREATE OR REPLACE FUNCTION FUN_REG_SPLIT_RECON
...
RETURN SYS_REFCURSOR
....

A: Try creating Function as RETURN statement is only  used in FUCNTION. RETURN statement in PROCEDURE is only used for TERMINATING the procedure normally at desired position. Hope below code helps.
CREATE OR REPLACE FUNCTION PROC_REG_SPLIT_RECON( --Function has to be incorporated
    dStart IN DATE,
    dEnd   IN DATE)
  -- procedure to check regional splits creation is okay
  -- procedure checks volumes by account and product from FACT_TRADE_PRESPLIT_ROLLUP to FACT_TRADE_ROLLUP
  -- SQLDeveloper doesn't like this section and I can't figure out how to set this up correctly, no matter what I do and research.
  RETURN SYS_REFCURSOR
AS
  l_return SYS_REFCURSOR;
  -- end of section not working
BEGIN
  OPEN l_return FOR SELECT OpStats.Account, OpStats.Platform, OpStats.Volume OpStatsVol, RegSplits.Volume RegSplitsVol, (OpStats.Volume-RegSplits.Volume) Difference FROM (a bunch OF
  UNION queries) OpStats, (a bunch OF other
  UNION queries) RegSplits WHERE OpStats.Account = RegSplits.Account (+) AND OpStats.Platform = RegSplits.Platform (+) ORDER BY OpStats.Account ASC, OPStats.Platform DESC;
  RETURN l_return;
END;


text:
Q: Android: Custom ImageView I'm trying to add touch functionality to an image by creating a custom ImageView, however when I run it I am getting a Null point exception in the logcat. My code is as follow:
TouchImageView.java

package com.android.wayfinder;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

public class TouchImageView extends ImageView {

Matrix matrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;

float redundantXSpace, redundantYSpace;

float width, height;
static final int CLICK = 3;
float saveScale = 1f;
float right, bottom, origWidth, origHeight, bmWidth, bmHeight;

ScaleGestureDetector mScaleDetector;

Context context;

public TouchImageView(Context context) {
    super(context);
    super.setClickable(true);
    this.context = context;
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
    matrix.setTranslate(1f, 1f);
    m = new float[9];
    setImageMatrix(matrix);
    setScaleType(ScaleType.MATRIX);

    setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            mScaleDetector.onTouchEvent(event);

            matrix.getValues(m);
            float x = m[Matrix.MTRANS_X];
            float y = m[Matrix.MTRANS_Y];
            PointF curr = new PointF(event.getX(), event.getY());

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    last.set(event.getX(), event.getY());
                    start.set(last);
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        float deltaX = curr.x - last.x;
                        float deltaY = curr.y - last.y;
                        float scaleWidth = Math.round(origWidth * saveScale);
                        float scaleHeight = Math.round(origHeight * saveScale);
                        if (scaleWidth < width) {
                            deltaX = 0;
                            if (y + deltaY > 0)
                                deltaY = -y;
                            else if (y + deltaY < -bottom)
                                deltaY = -(y + bottom);
                        } else if (scaleHeight < height) {
                            deltaY = 0;
                            if (x + deltaX > 0)
                                deltaX = -x;
                            else if (x + deltaX < -right)
                                deltaX = -(x + right);
                        } else {
                            if (x + deltaX > 0)
                                deltaX = -x;
                            else if (x + deltaX < -right)
                                deltaX = -(x + right);

                            if (y + deltaY > 0)
                                deltaY = -y;
                            else if (y + deltaY < -bottom)
                                deltaY = -(y + bottom);
                        }
                        matrix.postTranslate(deltaX, deltaY);
                        last.set(curr.x, curr.y);
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    mode = NONE;
                    int xDiff = (int) Math.abs(curr.x - start.x);
                    int yDiff = (int) Math.abs(curr.y - start.y);
                    if (xDiff < CLICK && yDiff < CLICK)
                        performClick();
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
            }
            setImageMatrix(matrix);
            invalidate();
            return true; // indicate event was handled
        }

    });
}

@Override
public void setImageBitmap(Bitmap bm) {
    super.setImageBitmap(bm);
    bmWidth = bm.getWidth();
    bmHeight = bm.getHeight();
}

public void setMaxZoom(float x)
{
    maxScale = x;
}

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        mode = ZOOM;
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float mScaleFactor = (float)Math.min(Math.max(.95f, detector.getScaleFactor()), 1.05);
        float origScale = saveScale;
        saveScale *= mScaleFactor;
        if (saveScale > maxScale) {
            saveScale = maxScale;
            mScaleFactor = maxScale / origScale;
        } else if (saveScale < minScale) {
            saveScale = minScale;
            mScaleFactor = minScale / origScale;
        }
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        if (origWidth * saveScale <= width || origHeight * saveScale <= height) {
            matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
            if (mScaleFactor < 1) {
                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                if (mScaleFactor < 1) {
                    if (Math.round(origWidth * saveScale) < width) {
                        if (y < -bottom)
                            matrix.postTranslate(0, -(y + bottom));
                        else if (y > 0)
                            matrix.postTranslate(0, -y);
                    } else {
                        if (x < -right)
                            matrix.postTranslate(-(x + right), 0);
                        else if (x > 0)
                            matrix.postTranslate(-x, 0);
                    }
                }
            }
        } else {
            matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
            matrix.getValues(m);
            float x = m[Matrix.MTRANS_X];
            float y = m[Matrix.MTRANS_Y];
            if (mScaleFactor < 1) {
                if (x < -right)
                    matrix.postTranslate(-(x + right), 0);
                else if (x > 0)
                    matrix.postTranslate(-x, 0);
                if (y < -bottom)
                    matrix.postTranslate(0, -(y + bottom));
                else if (y > 0)
                    matrix.postTranslate(0, -y);
            }
        }
        return true;

    }
}

@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    width = MeasureSpec.getSize(widthMeasureSpec);
    height = MeasureSpec.getSize(heightMeasureSpec);
    //Fit to screen.
    float scale;
    float scaleX =  (float)width / (float)bmWidth;
    float scaleY = (float)height / (float)bmHeight;
    scale = Math.min(scaleX, scaleY);
    matrix.setScale(scale, scale);
    setImageMatrix(matrix);
    saveScale = 1f;

    // Center the image
    redundantYSpace = (float)height - (scale * (float)bmHeight) ;
    redundantXSpace = (float)width - (scale * (float)bmWidth);
    redundantYSpace /= (float)2;
    redundantXSpace /= (float)2;

    matrix.postTranslate(redundantXSpace, redundantYSpace);

    origWidth = width - 2 * redundantXSpace;
    origHeight = height - 2 * redundantYSpace;
    right = width * saveScale - width - (2 * redundantXSpace * saveScale);
    bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
    setImageMatrix(matrix);
}

}

ImageView.xml

<?xml version="1.0" encoding="utf-8"?>

<com.android.wayfinder.TouchImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/arasnalaoi"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/aras_na_laoi" />

Activity:

public class ImageActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            TouchImageView touch = (TouchImageView) this.findViewById(R.id.arasnalaoi);
            touch.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.aras_na_laoi));
            touch.setMaxZoom(4f);
            setContentView(touch);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    }

}

The null pointer exception is pointing at the line: touch.setImageBitmap...

I'm absolutely stumpt so any help would be greatly appreciated.

Shaw

A: Your call to this.findViewById returns null (i.e. touch is null). It cannot find the R.id.arasnalaoi TouchImageView because you haven't loaded a content view into your activity yet.
You'll want to do things in a different order, i.e.

*

*Load your content using setContentView(R.layout.imageView);, assuming your xml is in the layout folder.

*Find your view using TouchImageView touch = (TouchImageView) this.findViewById(R.id.arasnalaoi);

*Set the properies of the touch object.

A: You are getting the NullPointerException because you call findViewById before you set a content view for the activity, so TouchImageView touch = (TouchImageView) this.findViewById(R.id.arasnalaoi) can not find any view with R.id.arasnalaoi as id, it will surely return null, yes, touch is null, that's why a NullPointerException is thrown.


text:
Q: how can i resolve Hackerrank "terminated for timeout"? the question is to find no of reversible no.s below the following test cases and here reversible no.s means like 36 + 63 = 99 (contains both odd digit).
both 36 and 63 are reversible . and we have to find total reversible no.s
below a number.
i have also declared functions as inline , but it is still giving timeout error . for test case#1  to test case#5
inline std::string IntToString ( int number )
    {
      std::ostringstream oss;
       oss<< number;
      return oss.str();
    }

inline int replacer (int n)

{
int r,R=0;

while(n!=0)
    {
       r=n%10 ;
    R=R*10+r ;
     n=n/10;
}

return R ;

}

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */

int i,n,t,j,R,Q,L,k,d=0,M=0,D;

cin>>t ;

for(i=0;i<t;i++ )
    {
    M=0;
    cin>>n ;

    for(j=1;j<n;j++)
        {

        if(j%10!=0)
       { d=0;
        R= replacer(j) ;

       Q=R+j ;
        std::string C = IntToString (Q);

        L=C.size() ;

        for(k=0;k<L;k++)
           if(C[k]%2==0)
            d=1 ;
           if(d==0)
          M++ ;
       }
    }
    cout<<M<<endl ;
    }

return 0;
}

A: A simple generic answer would be "by making your code to do things quickly" i.e. by optimizing it.
Profiling tools may help you to point out "hot" part of code, but the resolution has to be done by you.

A: You don't need to have a string in order to get a number's digits.
Transforming the int into string is a expensive operation given the fact that you use streams.
If you want to loop through a number's digits use this piece of code:
void loopThroughDigits(int n)
{
    while(n > 0)
    {
        int digit = n % 10;
        n /= 10;
        //do something with digit
    }
}

Other than that, you should consider to store earlier result and start calculating from the previous 'checkpoint'. I don't know neither of memory limit or the biggest input, so I'm not sure that this is a reliable method.


text:
Q: Scatter plot size too small with ggplot2 I have data for all car models, close to 300 model details. I am trying to plot all of them in a scatter plot sales over month and I am able to do that with ggplot2:
ggplot(data=cars,aes(x=sales,y=accidents))+
 geom_point()+
 facet_wrap(~model)

But the graph size is too small and difficult to visualize. Is there a way to increase the graph size and better visual?

A: it is important that you put a reproducible code to know what's your problem.
Maybe you could resize the output image using:
png(file="name_of_img_save.png",width=3300 ,height=2000,res=150)
ggplot(data=cars,aes(x=sales,y=accidents))+ geom_point()+facet_wrap(~model)
dev.off()

Luck!

A: If it is only for visualization you should probably try the manipulate package for RStudio. You can adapt it easily to have axis controls.
https://support.rstudio.com/hc/en-us/articles/200551906-Interactive-Plotting-with-Manipulate


text:
Q: Why are the optional query parameters appearing in child action when using Html.Action inside of a view? In an MVC application I have 2 action methods. One displays part of layout and in the middle of it, it tries to render the other action (which renders a list of items). For convenience sake I made it so, that if I ajax the first action I will get the result of the second one instead.
The code looks something like this:
public ActionResult Action1(int? foo = null, int? bar = null, string search = null)
{
    ViewBag.Foo = foo;
    ViewBag.Bar = bar;
    ViewBag.Bar = search;
    if (Request.IsAjaxRequest() || this.ControllerContext.IsChildAction)
    {
        return Action2(foo, bar, search);
    }
    var model = GetSomeData();
    return View(model);
}

public ActionResult Action2(int? foo = null, int? bar = null, string search = null)
{
    ViewBag.Foo = foo;
    ViewBag.Bar = bar;
    ViewBag.Bar = search;
    var model = GetSomeOtherData(foo, bar, search);
    return View();
}

Then in View for Action1:
@model SomeClass

    Some layout and stuff from the model goes here
    @Html.Action("Action2", new { foo = ViewBag.Foo, bar = ViewBag.Bar })

And View for Action2:
@model IEnumerable<SomeOtherClass>

    <form action="@Url.Action("Action1", new { foo = ViewBag.Foo, bar = ViewBag.Bar })">
        <input type="text" name="search"/>
        <input type="submit" value="Search"/>
    </form>
    Here we render a list of items from the model

When both foo and bar are null and I ajax Action1 or just request Action2, the URL in the form will not include the query parameters that are null. The problem appears when I request Action1 normally (not through ajax). Even though both foo and bar are null, the URL contain a query: ?foo=&bar=.
Does anybody know why does this happen and\or how to prevent it from happening? I mean I don't want to add query parameters if they are null.

A: Well why don't you check if they are null in View ? and if they are just use:
@{
var foo = ViewBag.Foo;
var bar = ViewBag.Bar;
}

@if(foo == null && bar == null){

@Html.Action("Action2","ControllerName")
}

A: Andreiyfrag's answer gave me an idea on how to solve my problem. In the view for Action2 I just construct my routevaouedictionary manually like this:
var searchArguments = new Dictionary<string, object>();
if (ViewBag.Foo != null)
{
    searchArguments.Add("foo", ViewBag.Foo);
}
if (ViewBag.Bar != null)
{
    searchArguments.Add("bar", ViewBag.Bar);
}

And then use it like this:
@Url.Action("Action1", new RouteValueDictionary(searchArguments) )

It appears that if I construct an url in a view of a child action (Url.Action), all the provided query parameters will be included (even if they are null), but if the same action was run as a normal one (non-child action), then null parameters would have been omitted. I have no idea why does this happen, could it be that it's a bug in Razor or MVC?


text:
Q: Docker in VirtualBox cannot access shared folders Host OS: macOS Catalina
Guest OS: Ubuntu Server 20.04
Hi,
I'm really scratching my head here.  I am setting up a Docker VM on my file server.  I have my main Docker server running Ubuntu Server natively.  Unfortunately, there are some Docker containers I need to use that needs the storage on my file server.  It's a 2008 Mac Pro, so Docker for Mac isn't possible.  Docker Toolbox wouldn't work either.   So I just cut out the middle-man and just created a Linux VM manually and running Docker in there.  Now, Docker runs great but the containers cannot write to the shared folders I set up in VirtualBox.
I have installed the Guest Additions.  I have made my user a member of the vboxsf group (as well as the docker group so I don't have to use sudo for everything Docker related).  I can read and write to the shared folders just fine from the VM machine using nano or whatever tool I need, and Docker itself can create any directory it needs on running docker-compose up -d... it's just the Docker containers that can't write to it.  It makes no difference if I run docker-compose with sudo or not.
Right now, I'm running Portainer, Bazarr, Radarr, Sonarr, Syslog-ng, and I will be running BackupPC or UrBackup once I get the rest of them being able to write to the shared folders.  Most of my containers are running on my dedicated Docker machine, but those that need access to lots of storage will be on this machine.
VirtualBox is running under my user account.  Permissions for the folders are 755.  I cannot figure out why they cannot write.  Any ideas?
Thanks
Edit 8/11/20:
I've changed up things a bit, Portainer after a couple of hiccups started working.  Then I found you could set docker's API to be monitored from a remote Portainer, so I deleted that one. It seems that Docker itself can use them fine... it's the containers that are having problems.  The bind mapping is done correctly.  But the containers cannot see what's in those folders nor write to them.
At this point, I am working just with Bazarr, Radarr, and Sonarr, since they are so similar or I would have just went to one container.  They are running now that I've mapped their /config folders to a folder within the VM.  But for them to access the storage array, I still have to use shared folders and they cannot seem to cross 2 levels of virtualization.  Docker > Ubuntu Server guest OS > macOS Catalina host OS.
Edit 2 by request:
Here's my docker-compose.yml file.  The commented out containers are that way because I'm trying to work on one thing at a time.  The three that aren't commented out are so similar that they may as well be one, so thought it might help me to figure something out if one suddenly started working and the others didn't.
version: "3.7"

networks:
  docker:
    name: DockerBridge
    driver: bridge

services:
############################# NetData
  # netdata:
  #   image: netdata/netdata
  #   container_name: NetData
  #   hostname: azeroth.local
  #   ports:
  #     - 19999:19999
  #   environment:
  #     PUID: ${PUID}
  #     PGID: ${PGID}
  #     TZ: ${TZ}
  #     DOCKER_HOST: proxy:2375
  #   restart: unless-stopped
  #   cap_add:
  #     - SYS_PTRACE
  #   security_opt:
  #     - apparmor:unconfined
  #   volumes:
  #     - /etc/passwd:/host/etc/passwd:ro
  #     - /etc/group:/host/etc/group:ro
  #     - /proc:/host/proc:ro
  #     - /sys:/host/sys:ro
  #     - /etc/os-release:/host/etc/os-release:ro
  #     - ${USERDIR}/netdata/lib:/var/lib/netdata
  #     - ${USERDIR}/netdata/cache:/var/cache/netdata
  #     - ${USERDIR}/netdata/config:/etc/netdata
  #     - ${USERDIR}/nginx/letsencrypt/live:/ssl:ro
  #   network_mode: bridge
  #   depends_on:
  #     - proxy
  # proxy:
  #   image: tecnativa/docker-socket-proxy
  #   container_name: DockerProxy
  #   environment:
  #     PUID: ${PUID}
  #     PGID: ${PGID}
  #     TZ: ${TZ}
  #     CONTAINERS: 1
  #   volumes:
  #     - /var/run/docker.sock:/var/run/docker.sock:ro
  #   network_mode: bridge

############################# Bazarr
  bazarr:
    image: linuxserver/bazarr
    container_name: Bazarr
    environment:
      PUID: ${PUID}
      PGID: ${PGID}
      TZ: ${TZ}
      UMASK_SET: 022 #optional
    volumes:
      - ${USERDIR}/Docker/Bazarr:/config
      - ${MEDIADIR}/Movies:/movies
      - ${MEDIADIR}/TV\ Shows:/tv
    ports:
      - 6767:6767
    restart: unless-stopped
    networks:
      - docker

############################# Radarr
  radarr:
    image: linuxserver/radarr
    container_name: Radarr
    environment:
      PUID: ${PUID}
      PGID: ${PGID}
      TZ: ${TZ}
      UMASK_SET: 022 #optional
    volumes:
      - ${USERDIR}/Docker/Radarr:/config
      - ${MEDIADIR}/Movies:/movies
      - ${MEDIADIR}/Downloads:/downloads
    ports:
      - 7878:7878
    restart: unless-stopped
    networks:
      - docker

############################# Sonarr
  sonarr:
    image: linuxserver/sonarr
    container_name: Sonarr
    environment:
      PUID: ${PUID}
      PGID: ${PGID}
      TZ: ${TZ}
      UMASK_SET: 022 #optional
    volumes:
      - ${USERDIR}/Docker/Sonarr:/config
      - ${MEDIADIR}/TV\ Shows:/tv
      - ${MEDIADIR}/Downloads:/downloads
    ports:
      - 8989:8989
    restart: unless-stopped
    networks:
      - docker

############################# syslog-ng
  # syslog-ng:
  #   image: balabit/syslog-ng:latest
  #   container_name: Syslog-ng
  #   ports:
  #       - 514:514/udp
  #       - 601:601/tcp
  #       - 6514:6514/tcp
  #   environment:
  #       PUID: ${PUID}
  #       PGID: ${PGID}
  #       TZ: ${TZ}
  #   volumes:
  #       - ${HOSTDIR}/Docker/Syslog-ng/syslog-ng.conf:/etc/syslog-ng/syslog-ng.conf
  #       - ${HOSTDIR}/Docker/Syslog-ng/logs:/var/log
  #   restart: always
  #   networks:
  #     - docker

Here is the .env file, parts of it redacted:
PUID=1000
PGID=1000
TZ=America/New_York
USERDIR=/home/scott/Docker
BACKUPDIR=/media/sf_Backup
HOSTDIR=/media/sf_Host
MEDIADIR=/media/sf_Media
DOMAIN=xxxxxxxx.us
EMAIL=xxxxxxxx@xxxxx.com

VirtualBox has 3 shared folders.

*

*

*

*Backup is mapped to /Volumes/Backup

*

*Host is mapped to /Users/scott

*

*Media is mapped to /Volumes/Media

#1 is going to be for containerizing BackupPC once I get the rest of these working and will be the backup for all my computers.  As such, it's not used yet.
#2 is from an earlier setup where I had the /config directories also mapped to a shared folder.  I realized I didn't need that, but haven't yet deleted the shared folder in VirtualBox.
#1 is an external eSata ZFS pool.  Currently one 6TB drive with the pool set up to easily add more drives as I need them.
#2 is mapped to my macOS home folder on the main SSD.
#3 is a five 4TB hard drive ZFS array with one drive worth of parity, for a capacity of 16TB.  The reason for the discrepancy between this and the backup pool is that this array is still mostly empty.

A: I've tested your setup, but I could not find any issues. My setup:
Setup
First: There is no difference during runtime when starting a container with sudo or not. By default, the Unix socket is owned by the user root and other users can only access it using sudo The Docker daemon always runs as the root user. Source: here

*

*Host:

*

*Microsoft Windows 10 Enterprise

*Virtual Machine (using Virtual Box 6.1.2)

*

*Ubuntu 20.04.1 LTS

*Docker Installation

*

*Docker version 19.03.8, build afacb8b7f0

*docker-compose version 1.26.0, build d4451659

Docker-Files
I'm invoking in a folder with the following content
developer@appdev:~/tmp$ ls -l
total 16
drwxrwxr-x  2 developer developer 4096 Aug 14 08:59 .
drwxrwx--- 11 developer developer 4096 Jul 29 09:50 ..
-rw-rw-r--  1 developer developer  261 Aug 14 08:23 docker-compose.yaml
-rw-rw-r--  1 developer developer  111 Aug 14 08:17 .env

The docker-compose.yaml file
sonarr:
    image: linuxserver/sonarr
    container_name: Sonarr
    environment:
      PUID: ${PUID}
      PGID: ${PGID}
      UMASK_SET: 022 #optional
    volumes:
      - ${HOSTDIR}/testdir:/Documents
    ports:
      - 8989:8989
    restart: unless-stopped

The .env file
PUID=1000
PGID=1000
TZ=America/New_York
HOSTDIR=/media/sf_Documents
DOMAIN=xxxxxxxx.us
EMAIL=xxxxxxxx@xxxxx.com

Virtual Box's shared folders
My shared folder is mapped to  /media/sf_Documents
developer@appdev:~$ ls -l /media/
total 8
drwxrwx---  1 root vboxsf 4096 Aug 12 09:01 sf_Documents

The folder sf_Dockument contains a folder testdir which has been created by the Host (Windows)
Testing
For testing I stared up the docker-file using
docker-compose up

and let it run. To enter the container with bash interactively:
docker exec -it Sonarr bash

Tried adding a file using cd Documents/, touch test and mkdir mytestdir . An ls -l
outputs the following
total 4
drwxrwx--- 1 root  998    0 Aug 14 07:08 .
drwxr-xr-x 1 root root 4096 Aug 14 06:23 ..
drwxrwx--- 1 root  998    0 Aug 14 07:08 mytestdir
-rwxrwx--- 1 root  998    0 Aug 14 06:24 test

A powershell dir invoke outputs the files as expected.
PS D:\UserData\***\Documents\testdir> dir

    Verzeichnis: D:\UserData\***\Documents\testdir

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       14.08.2020     09:08                mytestdir
-a----       14.08.2020     08:24              0 test

My suggestions to narrow down the problem
Since I was not able to reproduce your issues, I want to give you some suggestions I would try:

*

*Mount another folder which is not a shared folder (e. g. /home/) and try if you can write to it from your docker-container.

Since I don't use Mac OS as a host system, I can't verify this. Maybe there are permission issues with your host.

*

*Is writing to your shared folder from your VM (not docker!) possible? Try adding a file or a folder to the shared folders and check if it is possible to write to it.

*Check if Virtual Box can write or read the folders you mapped to the VM. Check the permissions on the folder you want to map to your VM.

*Check in the Virtual-Box Shared-Folders-Settings if you have ticked Read Only by mistake.


text:
Q: Wordpress Mediaelement - Youtube Videos Embed Options I have a custom field where I define the Youtube Url as a string.
https://www.youtube.com/watch?v=3VqHtEF3LPE

This then becomes the src in my theme's shortcode:
<?php
    $ysrc = get_field('fl_tube');
    if($ysrc) :
        $poster = wp_get_attachment_image_src( get_post_thumbnail_id( $entry_id ), 'entry-fullwidth', false );
        echo do_shortcode( '[x_video_player src="' . $ysrc . '" poster="' . $poster[0] . '" preload="metadata" hide_controls="false" autoplay="false" loop="false" muted="false" no_container="true"]' );
?>

Wordpress renders this code and produces:
<div class="mejs-mediaelement">
    <iframe class="me-plugin" id="me_youtube_0_container" frameborder="0" allowfullscreen="1" title="YouTube video player" width="480" height="270" src="https://www.youtube.com/embed/3VqHtEF3LPE?controls=0&wmode=transparent&enablejsapi=1&origin=https%3A%2F%2Fwww.mydomain.com&widgetid=1">
    </iframe>
</div>

In order to hide relative videos and info, I need to append to the url in iframe src:
&rel=0&showinfo=0

I cannot add this in my custom field string because then the iframe src output displays erroneously as:
src="https://www.youtube.com/embed/3VqHtEF3LPE?rel=0?controls=0&wmode=transparent&enablejsapi=1&origin=https%3A%2F%2Fwww.mydomain.com&widgetid=1"

Is there a workaround using javascript or a function maybe to append &rel=0&showinfo=0 to the iframe src for all youtube videos embedded on my site.

A: Try to wordpress function embed
<?php
        global $wp_embed;
        echo $wp_embed->run_shortcode('[embed width="123" height="456"]http://www.youtube.com/watch?v=dQw4w9WgXcQ[/embed]');
?>


text:
Q: check if pandas data frame column (string/object) is numeric (ignore empty/NULL/NAN) I tried this inspired by the accepted answer here:
df = pd.DataFrame({'col1':['1', '']})
all_numeric = pd.to_numeric(df['col1'], errors='coerce').notnull().all().item()
print(all_numeric)

to detect that a columns is numeric (ignoring blanks + NULLs + NANs).
In the above code all_numeric is False (Python bool), which does not make sense or maybe it does? I thought I try to impute nan as the reason might be the empty value:
df = pd.DataFrame({'col1':['1', '']})
df = df.apply(lambda x: x.str.strip()).replace('', np.nan)
all_numeric = pd.to_numeric(df['col1'], errors='coerce').notnull().all().item()
print(all_numeric)

Same outcome. Maybe my way of checking if all values of a column are numeric (ignoring NULL/NAN/empty strings) is wrong? Thanks!

A: You could strip white spaces and convert empty string to NaN, then drop it; then do the test:
out = pd.to_numeric(df['col1'].str.strip().replace('', pd.NA).dropna(), errors='coerce').notna().all().item()

Output:
True

This test throws False for the following input:
df = pd.DataFrame({'col1':['1', 's']})

A: According to the official pandas doc, you can check a series of data if it's numeric or not.
>>df = pd.DataFrame({'col1':['1', '']})
>>df.col1.str.isnumeric()

0     True
1    False


text:
Q: Maven minify tool configuration I am using minify-maven-plugin tool to minify the js and css files in my project. The configuration is as shown below.
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
            <warSourceExcludes>**/*.css, **/*.js</warSourceExcludes>
        </configuration>
    </plugin>
    <plugin>
        <groupId>com.samaxes.maven</groupId>
        <artifactId>minify-maven-plugin</artifactId>
        <version>1.7.4</version>
        <executions>
            <execution>
                <id>default-minify</id>
                <configuration>
                    <skipMerge>true</skipMerge>
                    <nosuffix>true</nosuffix>
                    <webappSourceDir>${basedir}/src/main/webapp</webappSourceDir>
                    <cssSourceDir>resources/public/css</cssSourceDir>
                    <jsSourceDir>resources/public/js</jsSourceDir>
                    <cssSourceFiles>
                        <cssSourceFile>bootstrap-select.css</cssSourceFile>
                        <cssSourceFile>bootstrap-switch.css</cssSourceFile>
                    </cssSourceFiles>
                    <jsSourceFiles>
                        <jsSourceFile>bootbox.js</jsSourceFile>
                        <jsSourceFile>bootstrap-select.js</jsSourceFile>
                    </jsSourceFiles>
                    <jsEngine>CLOSURE</jsEngine>
                    <closureCreateSourceMap>true</closureCreateSourceMap>
                </configuration>
                <goals>
                    <goal>minify</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

When I run the command mvn clean compile package with the above pom.xml, the war file gets generated.
I deploy the war file to the server which is on Amazon EC2 instance.
When I access the js files on the browser after the deployment, I can see the files are minified too, but failing to load the css and js files!
But if I comment the line from the above pom.xml,
<configuration>
    <warSourceExcludes>**/*.css, **/*.js</warSourceExcludes>
</configuration>

then, everything works fine, but the files are not minified.
What is that thing I am doing wrong in this configuration?


text:
Q: Indexing items in a Wt List Model Why when using Wt list models must you specify a column in the data and index methods?
The WAbstractListModel doc says, "An abstract list model specializes WAbstractItemModel for one-dimensional lists (i.e. a model with 1 column and no children)."
The WAbstractListModel::index prototype is index (int row, int column, const WModelIndex &parent=WModelIndex()).  Wouldn't it make sense to also have index (int row, const WModelIndex &parent=WModelIndex())?
The same situation is found in WStringListModel::data, whose prototype is data (int row, int column, int role=DisplayRole, const WModelIndex &parent=WModelIndex())?  Wouldn't it make sense for WStringListModel (or any implementation of WAbstractListModel) to provide a method data (int row, int role=DisplayRole, const WModelIndex &parent=WModelIndex())?
I realize that Wt is incomplete in many ways.  Is the lack of a one-dimensional API for list models simply a result of that incompleteness?  Or is there some conceptual reason to require specification of column numbers here?

A: Response from Wt developer:

WAbstractListModel doesn't add much (besides expressing intent).
The item models and views have been modelled after those in Qt, and
  are in most ways the same as those provided by Qt. See for example
  http://doc.qt.io/qt-5/qstringlistmodel.html

That Qt link shows that both of my suggestions are implemented there.
QAbstractListModel::index does not require you to specify a column:
QModelIndex QAbstractListModel::index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const
And, QStringListModel::data does not have a column parameter:
QVariant QStringListModel::data(const QModelIndex & index, int role) const
So, I'm chalking this up to "incompleteness."


text:
Q: Variable number of days for time based workflows Is it possible to setup a time based workflow which depends on a variable number of days?

A: You can use a formula field that returns a date or date/time based on whatever variable calculations you'd like to use, then specify the time-based action as "0 hours after Formula Field". In short, any sort of calculation you can perform in a formula may be used to create a variable delay.


text:
Q: ¿Como puedo hacer que se guarden datos de una tabla en otra después de actualizarla? Tengo una aplicación WEB en NETBEANS Y base de datos de ORACLE
lo quisiera es que al momento de actualizar mi formulario, se guarden los datos en otra tabla automáticamente y no solo en su Tabla original.
en mi tabla 1 llamada "tareas" que actualiza tengo.
proceso 1 = 100
proceso 2 = 50
proceso 3 = 20
lo que quiero es que al actualizar sus valores a (por ejemplo)
proceso 1 = 100
proceso 2 = 100
proceso 3 = 100
se actualice en su tabla "Tareas" y en la otra tabla que tengo llamada "respaldo"
les menciono que mi aplicación sirve perfectamente, puedo actualizar y puedo visualizar los datos actualizados en mi base de datos, mi unico problema es que quiero guardarlo en otra tabla.
Muchas gracias anticipadas!


text:
Q: Can't disable jQuery cache Update
I figured out that it must be caching problem but I can't turn cache off.
Here is my changed script:

It updates part of a web page every 3 sec. It works only once after clearing web browser cache, after that it doesn't work - requests are made to /Home/Refresh without interval of 3 seconds, data is send from the server, but nothing is displayed on the web page; subsequent requests send cookie ASP.NET_SessionId=wrkx1avgvzwozcn1frsrb2yh.
I am using ASP.NET MVC 2 and c#.

I have a problem with jQuery, here is how my web app works

*

*Search.aspx web page which contains a form and jQuery script posts data to Search() action in Home controller after user clicks button1 button.

Search.aspx:
<%@ Page Title="" Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<GLSChecker.Models.WebGLSQuery>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Title
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Search

    <% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm()) {%>
        <fieldset>

                <%: Html.LabelFor(model => model.Url) %>

                <%: Html.TextBoxFor(model => model.Url,
                    new { size = "50" } ) %>
                <%: Html.ValidationMessageFor(model => model.Url) %>

                <%: Html.LabelFor(model => model.Location) %>

                <%: Html.TextBoxFor(model => model.Location,
                    new { size = "50" } ) %>
                <%: Html.ValidationMessageFor(model => model.Location) %>

                <%: Html.LabelFor(model => model.KeywordLines) %>

                <%: Html.TextAreaFor(model => model.KeywordLines, 10, 60, null)%>
                <%: Html.ValidationMessageFor(model => model.KeywordLines)%>

                <input id ="button1" type="submit" value="Search" />

        </fieldset>

    <% } %>

</asp:Content>

        [HttpPost]
        public ActionResult Search(WebGLSQuery queryToCreate)
        {
            if (!ModelState.IsValid)
                return View("Search");

            queryToCreate.Remote_Address = HttpContext.Request.ServerVariables["REMOTE_ADDR"];
            Session["Result"] = null;

            SearchKeywordLines(queryToCreate);

            Thread.Sleep(15000);

            return View("Search");
        }//Search()

*

*After button1 button is clicked the above script from Search.aspx web page runs.

*Search() action in controller runs for longer period of time. I simulate
this in testing by putting Thread.Sleep(15000); in Search()action.

*5 sec. after Submit button was pressed, the above jQuery script calls
Refresh() action in Home controller.

        public ActionResult Refresh()
        {
            ViewData["Result"] = DateTime.Now;

            return PartialView();
        }

*

*Refresh() renders this partial

<%@ Control Language="C#"
  Inherits="System.Web.Mvc.ViewUserControl"
  %> <%= ViewData["Result"] %>

The problem is that in Internet Explorer 8 there is only one request to /Home/Refresh;
in Firefox 3.6.3 all requests to /Home/Refresh are made but nothing is displayed on the web page. Another problem with Firefox is that requests to /Home/Refresh are made every second not every 5 seconds.
I noticed that after I clear Firefox cache the script works well first time button1 is pressed, but after that it doesn't work.
I would be grateful for helpful suggestions.

A: This is a bit of an old question now. But I had an issue that I thought was related to caching, but turned out to be something else and I thought someone at some point might find it useful.
I had a set of routines that went something like this

*

*MAIN PAGE calls SUB PAGE via .load.
SUB PAGE has table for data entry
and hyperlinks for kicking off SQL PAGE to execute relevant sql

*Following data entry into SUB PAGE
(via MAIN PAGE), click on hyperlink
updates database using SQL PAGE and then refreshes
MAIN PAGE div that contains SUB PAGE
Well ... for hours I kept inputting data, then clicking the relevant links only to find that the MAIN PAGE div sometimes refreshed, sometimes didn't. F5 always worked though. So I was pretty sure I had a cache problem. So I stopped using .load and started using .ajax, using the 'cache: false'. I could see that .ajax was now suitably randomising the get url, yet still my MAIN PAGE div was not refreshing. I was certain I had a caching problem ...
But I did not.
Using Google Chrome's development tools - I could see that sometime my jQuery routine was doing exactly what it was supposed to do, i.e.
a) Click SUB PAGE; execute SQL PAGE; refresh MAIN PAGE div
And sometimes things happened in this order ...
b) Click SUB PAGE; refresh MAIN PAGE div; execute SQL PAGE
My code was written to do a), but because SQL PAGE took a while to execute, b) was actually what was happening. And b) was bad - my MAIN PAGE div was actually refreshing, but the SQL to update my data tables was not executing prior to the refresh.
Once I realised this, the fix was easy. Using .ajax, I implemented the following logic:
i) Click SUB PAGE
ii) Execute SQL PAGE
iii) Conditional on the successful execution of the SQL PAGE (using the 'success:' option in .ajax), then refresh MAIN PAGE div containing SUB PAGE
iv) I left the 'cache: false' in place, just in case
This fix works 100% of the time for my code
So if you are pulling your hair out trying to work out why caching won't turn off, just make sure that you actually have a caching problem and not the problem I have described above.
Good luck

A: You could change the URL you are requesting by adding a timestamp as part of the GET parameters:
function refreshResult()
{
  jQuery("#divResult").load("/Home/Refresh?"+(+new Date()));
}

This should ignore the browser cache (as the url is changing every time).  Of course - this is what setting the jQuery cache parameter to false on ajax requests does, I'm just not 100% sure that .load() will use that setting.

A: Any browser ajax handling. Never cached.
// Global Vars
var ajaxRefreshCount = 0;
var ajaxRequestsCount = 0;

// Call this function for the ajax request
function ajaxRequest(name)
{
    ajaxRefreshCount++;
    ajaxRequestsCount++;
    var reqAjax = jQuery.get("/?ajax=" + name + "&r="+ajaxRefreshCount+"&s="+new Date().getTime(), function (data) { ajaxCallback(data, name)} );
}

function ajaxCallback(data, ajaxRequestName)
{
    ajaxRequestsCount--;

        // Your Stuff
        if (ajaxRequestName == "home_refresh")
            jQuery("#divResult").html(data);

    if (ajaxRequestsCount == 0) ajaxFullyLoaded();
}

function ajaxFullyLoaded()
{
    // Execute when all ajax requests where processed
}

// Example for home refresh
ajaxRequest("home_refresh");

A: The IE8 problem might be that IE caches similar requests, but I'm not too familiar with JQueries internals if they handle this or not, a solution could be to add a random get var.

A: I found the solution, I replaced
<% using (Html.BeginForm()) {%>

with
<% using (Ajax.BeginForm(null)) {%>


text:
Q: Find Number of CPUs and Cores per CPU using Command Prompt I am trying to retrieve the Number of CPUs and Cores per CPU using Command Prompt.
I have executed the following command:
wmic cpu get NumberOfCores, NumberOfLogicalProcessors/Format:List
I get this error: wmic' is not recognized as an internal or external command, operable program or batch file
I am executing this on a Windows Server 2008 R2 machine.  I believe the 'wmic' command is compatible on this windows.
The directory I am running the command promt from is 'C:\Windows>
Any advice please?

A: You can use the environment variable NUMBER_OF_PROCESSORS for the total number of processors:
echo %NUMBER_OF_PROCESSORS%

A: Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

A: If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:
@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:
GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

A: You can also enter msinfo32 into the command line.
It will bring up all your system information. Then, in the find box, just enter processor and it will show you your cores and logical processors for each CPU. I found this way to be easiest.

A: In order to check the absence of physical sockets run:
wmic cpu get SocketDesignation


text:
Q: Using Load Balancer in Rackspace cloud for website HA I have tested tomcat specific clustering with apache mod_jk and mod_proxy on ubuntu local VMs for our website high availability and load balancing. The real servers are hosted by Rackspace cloud server provider. I tested tomcat clustering with 1 load balancer and 2 web servers. As single load balancer is again a single point of failure, I'm trying to add one more LB as slave.
In Rackspace there is an option Load Balancers and here is the link which guides how setting up load balancer which I am not sure to setup because of some doubts as I never did this before anytime.
Could anybody recommend me step-by-step what I should and what I shouldn't with only necessary resource avoiding unnecessary costs?
The following are the things which I'm not sure and requesting someone who is already using Rackspace help me out here in setting up load balancing:

*

*I want to add atleast 4 machines, 2 as web servers, 1 as load balancer server and one more as Failover load balancer server. I think I can add new machines from the Rackspace Load Balancer option?

*I just heard that one could cut down the cost of static IPs by setting up the cluster in LAN assigning private ip address to cluster computers and thus I can cut down bandwidth costs too. Is it really possible to join cluster computers in a LAN in Rackspace?

*As far as I know I will point the domain name(website name) to the Load Balancer in the DNS where the domain is registered and both the LBs should have Static Public IP assigned(i'm thinking I'm right here). As I already said I want to add one more LB to avoid single point of failure, Is there any option in Rackspace where I can  point the website domain to both the LBs so that only one is active and if active fails, it should point to another LB(similar to ip failover) so that I can make it zero-down-time website?.
I request if possible if anybody give me step-by-step list on how to do them in Rackspace with your own recommendations on what I should and shouldn't.
Thank you in advance!
EDIT: 1
I heard Rackspace offers to share an ip between computers, is that so?, then I can use this option. I will specify public/shared ip as virtual ip by eth0:0 in the network interface file on both the load balancers. Do you really think it works flawless even if specified the public ip as virtual ip with eth0:0 interface without any interruption?
EDIT: 2
I was thinking the setup like all the computer(web servers & load balancers) in a LAN(in Rackspace) with some network(192.168.x.x) using eth0 interface. For load balancers, for the interface eth0:0 or eth1, a public ip is shared between LBs and mod_proxy & mod_jk on LBs redirect them to web servers as they could be in same network(192.168.x.x).
After some analysis I realized that I could not directly access the web servers for testing from my place as they don't have the public ip assigned and so again I thought of adding some proxy redirection like ProxyPass /web1 http://web1-ip-here on the LBs to access the web servers with share public ip or site domain name(I think it redirects as all the servers are in lan). But again to update or to install some packages on web servers, need internet connection. I am again wondering if there is an option to connect web server to WAN with single public ip on LBs and if so if it works with no issue. Else I have to use public ip for web servers each.

A: First off, why do you need 4 machines when you can use only 2. You can set up load balancer on the same machines you are planning to use as webservers. Next, you can buy a so-called "shared IP" from Rackspace and set up Heartbeat to manage it. I've tried this setup the on Rackspace cloud and it worked pretty well. I used HAProxy as a balancer and I highly recommend you to use it too, it's quite easy to configure.

A: Two good options work here:
1: Hardware-based Load Balancing as Rackspace Service
Very recently Rackspace added its load balancing service and for plain web forwarding this is going to be your more reliable and cost-effective bet. from your account management panel, you can get to the load balancing options under Hosting -> Load Balancing
2: Software-based Load Balancing with Failover
You can of course set up two servers for load balancing and use software like HAProxy to round-robin incoming traffic. This will require you to pay for and maintain both servers as well as an extra cost for an extra public IP address to share between them.
The servers don't actually "share" the IP address - the "master" controls it and is the public point of contact for your load balancing. The two machines are linked together via heartbeat monitoring, and if the "slave" server detects the "master" is not responding, it will bind the public IP address and become the master.
Rackspace has an article where they describe the process for setting up the heartbeat load balancing solution on their web site here: http://www.rackspace.com/knowledge_center/index.php/IP_Failover_-_Setup_and_Installing_Heartbeat

A: According to RS support a RS LoadBalancer can handle up 150,000 connections. They are actually multiple (i'd guess virtual) machines with a public facing IP. From our experience they have a pretty good uptime and they are very easy to set up and shutdown. One major drawback I find in using RS LBs is they don't do SSL termination (yet).


text:
Q: adding up row values in VBAProject Say I have EXCEL 1 column (100 rows) of integers with values between 1 and 10 (with lrow being the last row).  With VB, I am trying to add the rows UP TO a given sum (ex:25) to FIND THE ROW when the given sum (or less if adding the last row will bring the sum to over 25) is achieved.
For i = 1 To lRow
       Do While sum < 25
            sum= sum+ Cells(i, 1).Value
            Cells(2, 5).Value = sum
        Next j
        i = j-1
    Loop
Next i

var j doesn't increment.  It keeps adding the fist row.  WHY?
note: I want to continue to add the rest of the rows starting with the end position (row) of the first iteration.  The reason for why i=j-1 is there.

A: You do not need two loops:
For i = 1 to lRow
    Sum =Sum + ActiveSheet.Cells(i, 1).Value
    If Sum >= 25 then exit for
Next i
ActiveSheet.Cells(2, 5).Value = sum
Msgbox "Stopped at Row: " & i

to continue down the column and get a print out every time it exceeds 25:
For j = 1 To lrow
    For i = j To lrow
        Sum = Sum + ActiveSheet.Cells(i, 1).Value
        If Sum >= 25 Then Exit For
    Next i
    ActiveSheet.Cells(i, 5).Value = Sum
    Sum = 0
    j = i
Next j

A: I'd go like follows
For i = 1 To lRow
    sum = sum + Cells(i, 1).Value
    If sum <= 25 Then i25 = i
Next

so:

*

*sum will store the total sum of the cells values

*i25 will store the row at which the sum was 25, or less if the sum exceeds 25 at row i25+1


text:
Q: Ideas for simplified linkedlist Implementation in Kotlin I want to implement something like a linkedlist in Kotlin. What I want is the ability to append more elements at the beginning or end of the list later on. I read that in java, there is unshift and push for doing this? But I couldnt find the equivalent ones in Kotlin.
I dont need the ability to delete elements from the list. If at all I have to delete, I would delete the whole list.
Kotlin experts, please let me know what is a good option for this.
Thanks.


text:
Q: Pushdown Menu - Modified Bootstrap Template I'm by no means a coder.  But I've been OK at piecing the odd piece together.
I've ran into a little snag.  I've created this dropdown / pushdown menu for a website i'm trying to put together.
It works - to a degree! the problem ive ran into is that once you select a 2nd or 3rd etc button - it would put a new pushdown menu below the original rather than removing the original and displaying the current.
Anyone know how to amend this?  I'm sure its something fairly handy but i've been looking at it all day getting it to this point so something to help finish this mini project for the day would be greatly appriciated.
EDIT - ok so i removed my javascript to see whats going on and it turns out the bootstrap.min.js along with the jquery.js are doing all the work so that leaves me even further confused.
javascript is melting my head :%

https://codepen.io/anon/pen/oVLYNr
Thanks!
Andrew


text:
Q: Can I use a Radeon GPU and a NVIDIA GPU together to increase performance? if so how? I currently have an Nvidia gtx 650 with 2gb VRAM. I want to get more quality and performance in games. I have been looking at the XFX Radeon R9 295X2 with 8gb VRAM. I want to know if I can use both of them together at the same time to make it to 10gb VRAM?

A: No, SLI only work for 2 nVIDIA and crossfire for 2 AMD cards. Mixing 2 different cards doesn't work.


text:
Q: Prove G is non-planar by contradiction $G=(V,E). |V| = 25; |E| = 50.$ For every vertex $v \in V$, the degree of that vertex $d(v)=4.$ I am given that the shortest cycles in $G$ are 4-cycles (i.e. with 4 vertices).
For a contradiction I assumed that G is planar. Hence G would have a number of regions/faces $|R|$ with boundary lengths $b(r)$. From this I got:
\begin{equation*}
\sum_{r \in R} b(r) = \sum_{v \in V}d(v) = 2|E| = 100,
\end{equation*}
and by Euler's theorem:
\begin{equation*}
|V| - |E| + |R| = |R| - 25 \geq 2 \implies |R| \geq 27.
\end{equation*}
So a lower bound on the first summation would be:
\begin{equation*}
\sum_{r \in R} b(r) \geq 27 b(r)_{min}.
\end{equation*}
where $b(r)_{min}$ is just the length of the smallest boundary for  a region. My guess here is to say that $b(r)_{min}$ = 4, given the information I made bold at the start. This would give me the $100 \geq 108$ contradiction I'm after, but this is just a guess and I don't know why/if this is true. I know that the boundaries in a planar drawing are cycles, and maybe these cycles don't change/get shorter when going from planar to non-planar, but again I'm guessing here. Could someone help me finish this proof and tell me if my intuition is right/wrong? Thanks!

A: Suppose it exist. So each face has at least 4 edges. By double counting  between edges and faces we have$$2 |E| \geq 4|F|\implies |E|\geq 2|F|$$ By Euler theorem we have $$|V|-|E|+|F|= 2$$
so $$ |E| \geq 2(2+|E|-|V|)$$
and thus
$$2|V|-|E|\geq 4 \implies 50-50\geq 4$$
A contradiction.


text:
Q: The getter 'docs' was called on null. Receiver: null Tried calling: docs when I run my app, there is always an error appears which is:
The getter 'docs' was called on null.
Receiver: null
Tried calling: docs

but everything works correctly, How can I solve it?
I think there is an update to flutter which make this code wrong, because I faced many problems like that.
important parts in my code:
return StreamBuilder(
        stream: FirebaseFirestore.instance
        .collection('medicine')
        .where('userId', isEqualTo: user.uid)
        .snapshots(),
    builder: (context, snapshot) {

    final doc = snapshot.data.docs;
    return ListView.builder(
    itemCount: doc.length,
    itemBuilder: (ctx, index) {

    if (snapshot.data == null) {
    return Center(
    child: CircularProgressIndicator(),
    );
    }
    return Container(
    child: Stack(
    children: [
    Row(
    children: [
    Flexible(
    child: Column(
    children: [
    Text(
    'اسم الدواء: ' + doc[index]['medicationName'],
    textAlign: TextAlign.start,
    ),
    ],
    ),
    )
    ],
    ),
    ],
    ),
    );
    },
    ));

A: The first stream can emit an empty snapshot.
You should check if the snapshot has data before accessing the documents:
if(!snapshot.hasData) {
 return Center(child: CircularProgressIndicator());
}
// if it has data, do your thing:
final doc = snapshot.data.docs;
return ListView( ..... )

A: Another solution to make your code work, is to use null safety and replace snapshot.data to snapshot?.data


text:
Q: Alsamixer 200% without VLC When I change VLC Player's volume to 200%, it appears to make everything else 200% volume after closing it. Once I open Alsamixer it still says 200%. However, if I try changing the volume at all, whether up or down, it automatically jumps to 100% and everything becomes drastically quieter.
Being that this shows that my speakers are not working at their full capacity, how can I change the volume to 200% and use the full capacity of my speakers without VLC Player?
I'm using KDE on Fedora. At one point, I was told to change my asound.conf file to have
pcm.!default{
    type plug
    slave.pcm "softvol"
}

pcm.softvol{
    type softvol
    slave{
        pcm "dmix"
    }
    control{
        name "Pre-Amp"
        card 0
    }
    min_dB -5.0
    max_dB 20.0
    resolution 6
}

which did not work. I rebooted, I shutdown and turned my computer back on, etc. Alsamixer and KMix refused to acknowledge a "Pre-Amp."
Any other suggestions for making my volume higher?


text:
Q: Why do I have to add a /128 ipv6 address explicitly to a device if I have a /64 already? On a Fedora server, I have the following line in my /etc/sysconfig/network-scripts/ifcfg-eth0:0:
IPV6ADDR=<REDACTED>:48ea::1/64

Now binding to that specific address works:
$ nc -l <REDACTED>:48ea::1 1025

However, binding to another address in the same netmask space fails:
$ nc -l <REDACTED>:48ea::2 1025
Ncat: bind to <REDACTED>:48ea::2:1025: Cannot assign requested address. QUITTING.

If explicitly add <REDACTED>:48ea::2/128 (either by adding it to IPV6ADDR_SECONDARIES or by running ip addr add <REDACTED>:48ea::2/128 dev eth0), then I can bind to it.
Why adding the /64 address is not enough? Do I have to explicitly add every single /128 address to the device before using it?

A: The number after the / is the subnet size, which is (almost) always a /64 in IPv6. It doesn't say anything about your local machine. Just like with IPv4 you still have to assign each individual address to the interface.
With IPv4 you can write both 192.168.0.1/24 and 192.168.0.1/255.255.255.0. They mean exactly the same.
With IPv6 writing <REDACTED>:48ea::1/ffff:ffff:ffff:ffff:: (or even <REDACTED>:48ea::1/ffff:ffff:ffff:ffff:0000:0000:0000:0000) would become a bit unwieldy, so only the <REDACTED>:48ea::1/64 notation is used.


text:
Q: Проблема в написании функции получения таблицы базы данных с использованием psycopg2 Нужно написать функцию для получения данных из таблицы базы данных, чтобы функция на входе принимала название таблицы и после передать её в запрос
def list_db_table_content(self):
    table = dict()
    self.cur.execute("Select * FROM test")
    colnames = [desc[0] for desc in self.cur.description]
    data = (self.cur.fetchone())

    for t1, t2 in zip(colnames, data):
        table[t1] = t2
    return table

В строке self.cur.execute("Select * FROM test") вместо test(моя локальная бд и таблица в ней) нужно как-то передать разные названия таблицы. Если сделать переменной,то это уже будет строковый тип данных и выдаст ошибку. Может быть я выбрал в корни не правильный подход, или же этот код можно исправить?


text:
Q: Add Duplicates keys to NameValueCollection I have read that NameValueCollection allows for duplicate keys to be added, however this does not seem to be the case when I try to use it.
My Code
using (var wb = new WebClient())
{
     var data = new NameValueCollection();
     var sourceData = (List<Dictionary<string, object>>)dic["mapData"];
     var countSource = sourceData.Count;

     foreach (var item in (List<Dictionary<string, object>>)dic["mapData"])
     {
          data.Add("pp", item["Latitude"].ToString() + "," + item["Longitude"].ToString());
     }

     var dataCount = data.Count;
     var response = wb.UploadValues(@"http://dev.virtualearth.net/REST/V1/Imagery/Map/road/?mapArea=" + swLat.ToString() + "," + swLong + "," + neLat + "," + neLong + "&mapSize=800,600&key=" + key, "POST", data);

     return this.LargeJson(new { imageData = CreateBase64Image(response) });
}

What I am observing
my sourceData contains 36 items

I am iterating through sourceData and adding items to my NameValueCollection data and add items with the same key "pp"
I was expecting to have 36 items in my data NameValueCollection, but I am only getting 1 and all of my values get appended to the same key.
What am I missing ?

A: This is the expected behaviour - see the documentation:

If the specified key already exists in the target NameValueCollection
  instance, the specified value is added to the existing comma-separated
  list of values in the form "value1,value2,value3". The values are
  associated with the same key in the target NameValueCollection
  instance.