text:
Q: sphinx_rtd_theme is no longer a hard dependency since version 1.4.0
C:\Users\Administrator\Desktop\item\code_serv\documents\api>make html
  Running Sphinx v1.6.2 loading pickled environment... failed:
Can't get attribute 'WarningStream' on <module 'sphinx.util.nodes' from 'c:\\users\\administrator\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\\sphinx\\util\\nodes.py'>

Theme error:

sphinx_rtd_theme is no longer a hard dependency since version 1.4.0.
  Please install it manually.(pip install sphinx_rtd_theme)

How do I solve this?

A: I found another issue, I had two installations of sphinx, one via pip and another one via brew. Deleting one (I chose to remove installation done via brew ) solved this issue.
brew remove sphinx-doc

If it still doesnt work, try uninstalling and reinstalling
pip3  uninstall sphinx sphinx_rtd_theme
pip3  install sphinx sphinx_rtd_theme

A: Your question does not indicate whether you searched the web for "how to install sphinx_rtd_theme" or read its documentation.
The error message provides a clue:

Please install it manually. (pip install sphinx_rtd_theme)

Or you could try following the directions in the manual.

A: On my Mac OS X installation, I encountered this problem, despite following the simple instructions to the letter.
Others have reported having the problems as well, on this Github issue: https://github.com/readthedocs/sphinx_rtd_theme/issues/618
In my case, the problem turned out to be an issue with my python environment (I was using the default system python 2.7 for Mac). I ended up switching to pyenv with python 3.7.3, and that fixed the issue.
Instructions for Mac (from https://opensource.com/article/19/5/python-3-default-mac):
$ brew install pyenv

$ pyenv install 3.7.3

$ pyenv global 3.7.3

$ pyenv version
3.7.3 (set by /Users/mbbroberg/.pyenv/version)

$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.zshrc

To verify that it worked:
$ which python
/Users/mbbroberg/.pyenv/shims/python

$ python -V
Python 3.7.3

$ pip -V
pip 19.0.3 from /Users/mbbroberg/.pyenv/versions/3.7.3/lib/python3.7/site-packages/pip (python 3.7)

Don't forget to pip install sphinx sphinx_rtd_theme afterward.

A: In my case (building from RTD theme source), the problem seemed to be caused by a change in behaviour of the html_theme_path config value in conf.py. Whilst paths relative to the makefile directory used to be accepted, paths must now be relative to the configuration directory:

html_theme_path
A list of paths that contain custom themes, either as subdirectories or as zip files. Relative paths are taken as relative to the configuration directory.
New in version 0.6.
— Sphinx documentation > Configuration

A: I had the same problem on a Windows 10 Pro laptop. I had installed Python 3.9 from the Windows store. I had to first find where Python and pip applications were installed and add that to the PATH variable. This was in a folder that was looked:
c:\users\<username>\appdata\local\programs\python\python39\Scripts

Then I installed sphinx using:
pip install -U sphinx

Then I had to set the SPHINXBUILD env variable to the right value:
SPHINXBUILD="c:\users\<username>\appdata\local\programs\python\python39\Scripts\sphinx-build.exe"

When I tried to use the sphinx_rtd_theme I kept getting the error:
Theme error:
sphinx_rtd_theme is no longer a hard dependency since version 1.4.0. Please install it
manually.(pip install sphinx_rtd_theme)

I ran the following command:
pip install sphinx_rtd_theme

But when I tried to run make html it gave the error:
Running Sphinx v3.5.1

Configuration error:
There is a syntax error in your configuration file: bad input (conf.py, line 57)

Finally I had to make the following changes in my conf.py file:
# Add this to the top of the conf.py file
import os
import sys
sys.path.insert(0, os.path.abspath('C:\\Users\\ <username>\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages'))
import sphinx_rtd_theme

extensions = [
   "sphinx_rtd_theme",
]

It looks like sphinx-build is not able to get the location of the sphinx_rtd_theme package unless you give the explicit path in the manner above. "¯_(ツ)_/¯"


text:
Q: The Source And Refactor menus in Eclipse are missing for XML files The menus Source and Refactor in the eclipse's menubar are missing.
When i am looking a java file, in the java perspective, they appear, but when i change to an XML in the same perspective the menus disappear.
Can you help me with that? So Much Thanks

A: This is actually a correct behavior, since most actions from mentioned menus cannot be applied to XML. Or do you want some specific menu item?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate the moment of inertia of a solid cube? How do I calculate the moment of inertia of a uniform solid cube about an axis passing through its center of mass?
I also wanted to know if the moment of inertia of a body is independent of its shape. Also, recently I read somewhere that the moment of inertia of a  uniform solid cube is minimum about an axis passing through its COM because the mass is more concentrated at its center. Does the statement make any sense?

A: First you need to define the orientation of the cube relative to the axis you want to measure. Typically a 3×3 rotation matrix $E$ does the job transforming local coordinates along the principal axes to the world coordinates. The use the transformation $E I_{body} E^\intercal$
Example:
A single rotation $\theta$ about the world $z$ axis is

$$E  = \begin{pmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{pmatrix} $$
If the mass moment of inertia matrix about the principal axes $(x,y,z)$ is
$$I_{body} = \begin{vmatrix} I_{xx} & & \\ & I_{yy} & \\ & & I_{zz} \end{vmatrix} $$
then the mass moment of inertia about the world coordinates is
$$ I_{world} = E\,I_{body}\, E^\intercal $$
where $E^\intercal$ is the inverse rotation found by the transpose operator. The result is $$ I_{world} = \begin{vmatrix}
  I_{yy}+(I_{xx}-I_{yy})\cos^2\theta & (I_{xx}-I_{yy})\sin\theta\cos\theta & 0\\
 (I_{xx}-I_{yy})\sin\theta\cos\theta & I_{xx}+(I_{yy}-I_{xx})\cos^2\theta & 0\\
0 & 0& I_{zz}
\end{vmatrix} $$
This represent the mass moment of inertia about the three world coordinates. To get the MMOI about a specific axis $\hat{e}$ you calculate $$I_{ee} = \hat{e}^\intercal I_{world} \hat{e} $$
So to get the MMOI about the world $X$ axis with $\hat{e}=(1,0,0)$ you find that $$I_{XX} = \begin{pmatrix}1 & 0 & 0 \end{pmatrix} I_{world} \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix} = I_{yy}+(I_{xx}-I_{yy})\cos^2\theta $$
Alernatively
You can find the local coordinates of the world $X$ axis as $\hat{x} = E^\intercal \hat{e}$ and then compute $$\boxed{ I_{XX} = \hat{x}^\intercal I_{body} \hat{x} }$$

A: The moment of inertia can be defined as the volume integral of the density times the position vector (centered at the origin of the axis you choose):
$$
I_{obj}=\int dV\,\rho\left(\mathbf{r}\right)\mathbf{r}^2
$$
which should work always.
As for your other questions, if we had a thin, solid cylinder and rotated it about its end point:

The moment of inertia would be
$$
I_{cyl,end}=\frac13mL^2
$$
If we took the same rod and rotated it about it's center,

Then the moment of inertia ends up being
$$
I_{cyl,mid}=\frac1{12}mL^2
$$
If we instead had a sphere rotating about its center,

the moment of inertia is
$$
I_{sph}=\frac25mr^2
$$
So clearly the shape and the axis affect the moment of inertia.
If we rotated an object about an axis that does not line up with its center of mass, then we need to use the parallel-axis theorem. This tells us that the total moment of inertia is then
$$
I_{tot}=I_{cm} + mr^2
$$
where the $r$ denotes the distance from the object's center of mass to the axis of rotation and $I_{cm}$ is the normal moment of inertia for the object (e.g., the above few ones).

A: Two theorems worth knowing about when it comes to calculations like this:
1) Parallel axis theorem. For any object of mass $m$, the moment of inertia $I_A$ about an axis A that is parallel to but displaced by a distance $x$ from an axis $C$ through the center of mass, is given by
$$I_A = mx^2 + I_C$$
From this, it follows immediately that the moment of inertia about an axis through the center of mass is a minimum (for that direction of rotation) since $mx^2$ will always be >0 for any nonzero value of $x$ (the offset).
2) Perpendicular axis theorem. For a lamina (thin sheet), the moment of inertia about an axis perpendicular to the sheet is equal to the sum of moments of inertia about two perpendicular axes in the sheet.
This theorem is handy to calculate the moment of inertia of a square plate of mass $m$ and side $s$. It is easy to calculate the moment of inertia about an axis in the plane of the plate and parallel to the sides of the square - about that axis the mass distribution of the object is no different than the distribution of a rod, for which we have the result
$$I_x = \frac{1}{12} m s^2$$
By symmetry, $I_y = I_x$. From the perpendicular axis theorem, $I_z = I_x + I_y$ so
$$I_z = \frac{1}{6} m s^2$$
Considering a cube as being made up of a stack of lamina, it follows that the moment of inertia of a cube about an axis through the center of mass (and through the face of the cube) is the same as the above.
You can see a pretty comprehensive listing of other moments of inertia for different shapes at this link


text:
Q: How do you UNION with multiple CTEs? How do you use UNION with multiple Common Table Expressions?
I'm trying to put together some summary numbers but no matter where I put the ;, I always get an error
SELECT  COUNT(*)
FROM    dbo.Decision_Data
UNION
SELECT  COUNT(DISTINCT Client_No)
FROM    dbo.Decision_Data
UNION
WITH    [Clients]
          AS ( SELECT   Client_No
               FROM     dbo.Decision_Data
               GROUP BY Client_No
               HAVING   COUNT(*) = 1
             )
    SELECT  COUNT(*) AS [Clients Single Record CTE]
    FROM    Clients;

I appreciate in the example above I can move the single CTE to the beginning, but I have a number of CTEs I'd like to UNION

A: You can do it like this:
WITH    [Clients]
          AS ( SELECT   Client_No
               FROM     dbo.Decision_Data
               GROUP BY Client_No
               HAVING   COUNT(*) = 1
             ),
        [Clients2]
          AS ( SELECT   Client_No
               FROM     dbo.Decision_Data
               GROUP BY Client_No
               HAVING   COUNT(*) = 1
             )
SELECT  COUNT(*)
FROM    Clients
UNION
SELECT  COUNT(*)
FROM    Clients2;

A: If you are trying to union multiple CTEs, then you need to declare the CTEs first and then use them:
With Clients As
    (
    Select Client_No
    From dbo.Decision_Data
    Group By Client_No
    Having Count(*) = 1
    )
    , CTE2 As
    (
    Select Client_No
    From dbo.Decision_Data
    Group By Client_No
    Having Count(*) = 2
    )
Select Count(*)
From Decision_Data
Union
Select Count(Distinct Client_No)
From dbo.Decision_Data
Union
Select Count(*)
From Clients
Union
Select Count(*)
From CTE2;

You can even use one CTE from another:
With Clients As
        (
        Select Client_No
        From dbo.Decision_Data
        Group By Client_No
        Having Count(*) = 1
        )
        , CTE2FromClients As
        (
        Select Client_No
        From Clients
        )
    Select Count(*)
    From Decision_Data
    Union
    Select Count(Distinct Client_No)
    From dbo.Decision_Data
    Union
    Select Count(*)
    From Clients
    Union
    Select Count(*)
    From CTE2FromClients;

WITH common_table_expression (Transact-SQL)


text:
Q: Search form with Cakephp 3 i try to make a search form in my application, i want search the post with one input and his search on title and content.
EDIT : I use the CakePHP Search plugin
My controller
public function initialize(){
    parent::initialize();
    $this->loadComponent('Search.Prg', ['actions'=>'index','lookup']);
}
public function search(){
    $query = $this->Posts
        ->find('search',['search' => $this->request->query])
        ->contain(['Users','Categories'])
        ->where(['Posts.status' => 1]);

        $this->set(compact('posts', $this->paginate($query)));
}

My Model
use Search\Manager;
$this->addBehavior('Search.Search');
     $this->searchManager()
        ->add('q', 'Search.Like', [
            'before' => true,
            'after' => true,
            'mode' => 'or',
            'comparison' => 'LIKE',
            'wildcardAny' => '*',
            'wildcardOne' => '?',
            'field' => [$this->aliasField('name'), $this->aliasField('content')]
        ]);

And in my view
 <?= $this->Form->create();  ?>
    <?= $this->Form->input('q');  ?>
    <?= $this->Form->button('Search', ['action'=>'index']);  ?>
    <?= $this->Form->end();  ?>

Now, how show the results of query ?

A: Your query should be something like this.
$query = $this->find('all')
        ->where(['title LIKE' => '%' . $this->request->query('q') . '%'])
        ->orWhere(['content LIKE' => '%' . $this->request->query('q') . '%']);

A: To display the search result do the following "additional" things:
1st:
Load your component in AppController
class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Search.Prg', [
        // This is default config. You can modify "actions" as needed to make
        // the PRG component work only for specified methods.
        'actions' => ['index', 'lookup']
        ]);
}

2nd:
Add the following code in your search method:
$query = $this->SystemUsers->find('search', ['search' => $this->request->query]);
        $vari = $this->request->getQuery('q');
        if ($vari != "") {
            $posts= $this->paginate($query);

            $this->set(compact('posts'));
            $this->set('_serialize', ['posts']);
        }

3rd: edit your search.ctp file to view the result:

                <?= $this->Paginator->sort('id') ?>
                <?= $this->Paginator->sort('name') ?>
                <?= $this->Paginator->sort('content') ?>
                <?= $this->Paginator->sort('created') ?>
                <?= $this->Paginator->sort('modified') ?>
                <?= __('Actions') ?>

            <?php foreach ($posts as $post): ?>

                <input type="checkbox" value="">
                <?= $this->Number->format($post->id) ?>
                <?= h($post->name) ?>
                <?= h($post->content) ?>
                <?= h($post->created) ?>
                <?= h($post->modified) ?>

                    <?= $this->Html->link(__('View'), ['action' => 'view', $post->id]) ?>
                    <?= $this->Html->link(__('Edit'), ['action' => 'edit', $post->id]) ?>
                    <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $post->id], ['confirm' => __('Are you sure you want to delete # {0}?', $post->id)]) ?>

            <?php endforeach; ?>

            <?= $this->Paginator->first('<< ' . __('first')) ?>
            <?= $this->Paginator->prev('< ' . __('previous')) ?>
            <?= $this->Paginator->numbers() ?>
            <?= $this->Paginator->next(__('next') . ' >') ?>
            <?= $this->Paginator->last(__('last') . ' >>') ?>

<?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?>

In above view, edit the table's entity name according to your table.


text:
Q: Is possible to change the motherboard of a HP Touchsmart 1080la tablet pc? I want to upgrade a HP Touchsmart 1080la tablet pc, with a faster processor and better memory. Is this possible? Which hardware is compatible?
I've performed an Internet search about this, but I haven't found a list of compatible motherboards to perform an upgrade.

A: As far as CPU, it's very unlikely.  It is extremely rare when a tablet, notebook or laptop PC can have it's CPU upgraded without replacing the entire motherboard.  The majority of the time in these devices, the CPU is soldered to the motherboard and not in a removable socket like most desktop PCs.  And that's only if you can find one that fits the same format and shell.  In your case, it's a custom HP motherboard and depending on the exact variant of model you bought, you may find HP offering a motherboard with a faster CPU, but it's pretty much guaranteed it will be cheaper for you to just buy a new tablet in that case.
It's far more likely that the memory can be upgraded.  In your case, the answer is yes, but it depends on what you already have installed.  If you already have the largest amount of memory the device supports (8 GB in your case in two 4 GB SODIMMS), then you can go no further.  If you don't have 8 GB of memory, that's about your only upgrade path with this device.
Your device's hardware manual.


text:
Q: Does the "filter" opacity option in CSS transfer to sub-elements? #box{
    filter: alpha(opacity=50);
}

Will "goat" have an opacity of 50?

A: Yep it will http://jsfiddle.net/AlienWebguy/SxLe4/
Tested in IE9

A:
@thirtydot: Yes, I only want the
  background of the box to be
  transparent. nothing else. I don't
  want the text inside to be transprent.
  I don't want its children to be
  transparent.

You could use:
#box {
    background: url(semi-transparent-matching-the-rgba.png);
    background: rgba(0,0,255,0.5)
}

*

*Browsers that support rgba will use the second background declaration with rgba.

*Browsers that do not will ignore the second background declaration and use the .png.

For a solution that does not involve a .png image, see:
http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/
Splitting into two elements also works, but it's covered by the other answers here, so I'll leave it alone.

A: To prevent the double semiopacity and only apply it on the background, you can split it into two boxes.
CSS
#box {position: relative;}

#goat, #background {
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

#goat{z-index:1;}

#background {
    filter: alpha(opacity=50);
    opacity:0.5;
    z-index:-1;
}

HTML

This of course depends on your content and how


text:
Q: React.JS: Error: Invalid hook call. Hooks can only be called inside of the body of a function component I have been working on a front-end (following a tutorial) for React.js and have ran into an error:

× Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

*

*You might have mismatching versions of React and the renderer (such as React DOM)

*You might be breaking the Rules of Hooks

*You might have more than one copy of React in the same app

I have looked into each one of these issues and cannot seem to find the problem.. If anyone has a pointer that would be very helpful..
The 'App' Code:
import React from "react";
import { Container, AppBar, Typography, Grow, Grid } from "@material-ui/core";

import memories from "./images/memories.png";
const App = () => {
  return (
    <Container maxwidth="lg">
      <AppBar position="static" color="inherit">
        <Typography variant="h2" align="center">
          Memories
        </Typography>
        <img src={memories} alt="memories" height="60" />
      </AppBar>
    </Container>
  );
};

export default App;

The 'Package.json' Code:
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

The 'index.js' Code:
import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

EDIT: as requested, i've added a few more files which maybe causing the issue.


text:
Q: Why does co_argcount return 2, instead of 4? In the following function, there are four parameters a, b, c, and d.
def f(a, b = 10, *c, **d):
    return (a, b, c, d)

But, when I log the co_argcount attribute of this function's code object, I get 2 returned.
>>> f.__code__.co_argcount
2
>>> f.__code__.co_nlocals
4

Why is this so? Shouldn't co_argcount return 4 since the function has four parameters.
Why are c and d referred to as local variables, not parameters?

A:
Returns the number of positional arguments (including arguments with
default values).

https://python-reference.readthedocs.io/en/latest/docs/code/argcount.html

Returns the number of local variables used by the function (including
arguments).

https://python-reference.readthedocs.io/en/latest/docs/code/nlocals.html
so in your case only two positional parameters ( a and b )
while there are for local variables a,b,c,d
Output of nlocal if we define a extra local variable:

official link : https://docs.python.org/3/library/inspect.html

A: From 3.2 The standart type hierarchy:

Special read-only attributes: co_name gives the function name; co_argcount is the total number of positional arguments (including positional-only arguments and arguments with default values);
[...]
The following flag bits are defined for co_flags: bit 0x04 is set if the function uses the *arguments syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments;

0x04 flag is denoted VARARGS
0x08 flag is denoted VARKEYWORDS
This and the rest can be seen using the function dis.show_code
>>> import dis
>>> def f(a, b = 10, *c, **d):
...     return (a, b, c, d)
...
>>> dis.show_code(f)
Name:              f
Filename:          <stdin>
Argument count:    2
Positional-only arguments: 0
Kw-only arguments: 0
Number of locals:  4
Stack size:        4
Flags:             OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, NOFREE
Constants:
   0: None
Variable names:
   0: a
   1: b
   2: c
   3: d


text:
Q: C malloc() memory space released after program ends?
Possible Duplicate:
What REALLY happens when you don't free after malloc?
Is freeing allocated memory needed when exiting a program in C

During my first C class, it was drilled into me that I should call free() after malloc() or calloc() as it releases the space after dynamically allocating memory or otherwise it will be gone (I assume until system reboot). However, recently I started reading on various coding sites that this memory will be released back when the program ends.
Which one is the correct statement?
I would look in the official spec, but I have no idea where to get it (tried Googling).
Thanks.

A: Really short answer..
Both of the statements are correct.

A longer more elaborate one..
Both of them are correct, when your application fully terminates the allocated memory will (probably) be released back to the system.
I wrote "probably" since all modern/widely-used OSes will deallocate the memory used, but some primitive systems might not have this "feature" available.
Because of the above you should always use free to deallocate memory of allocated but unused variables, especially during run-time (otherwise you'll have a memory leak that might/will slowly eat up all available memory).
If you wanna live on the wild side and not deallocate memory before the application terminates, that's fine by me and most people.B ut, please make sure that the platform you are going to run the application in really does release the memory back to the operating system afterwards.

Regarding looking in the standard ("official spec")
The standard most often/always leaves out implementation details, therefor there is nothing in there saying what will happen to allocated memory that hasn't been deallocated when the running application terminates.
That's implementation specific, and therefor depends in/on/at what you are running it.

A: On any system with protected memory (e.g. Windows 4.x+, Linux, Unix, …), the memory is released when the program terminates.
Some embedded systems may not always do so, however.
Regardless, it's definitely good form to free() everything correctly.

A: This is valid within the program, that's while the process is running.
Out of it, this is OS dependent. There is no spec, but the big majority of systems will clean up all the memory used by the process after it is finished.

A: All memory for a given process is released back to the system at its termination. However, before a program exits, it's important to always free() your memory, especially for long-running programs. In short-running programs, it's still good practice. It's always nice when valgrind spits out a clean bill of health!


text:
Q: gcc 4.8.4 "pragma GCC diagnostic not applied" Using g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
In a pre-compiled-header I have the following:
63 #pragma GCC diagnostic push
64 #pragma GCC diagnostic ignored "-Wunused-variable"
65 #include <boost/filesystem.hpp>
66 #pragma GCC diagnostic pop

Now when I go to run our build system, I get the following build error:
from <>../../../../Core_Pch.h:65,
    from <command-line>:0:
<>/../../../../external/include/BoostBase/boost/system/error_code.hpp: At global scope:
<>/../../../../external/include/BoostBase/boost/system/error_code.hpp:221:36: error: 'boost::system::posix_category' defined but not used [-Werror=unused-variable]
     static const error_category &  posix_category = generic_category();

There appears to be a possible bug already opened in GCC's bug tracker. However, I am wondering if anyone has this working? The bug eludes to the fact that the behavior of the preprocessor used by the C lexer works differently than that used by the C++ lexer.

This might be related to something else in our build system. Note that if I create the most simple of examples:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
int main(void)
{
  int x;

  return 0;
}
#pragma GCC diagnostic pop

This works as expected if I invoke:
~/Devel/pragma $ gcc -Werror -Wall -pedantic main.c
~/Devel/pragma $ g++ -Werror -Wall -pedantic main.c

Commenting out the ignored line results in:
mhoggan@mhoggan-Precision-T3600 ~/Devel/pragma $ gcc -Werror -Wall -pedantic main.c
main.c:2:1: error: C++ style comments are not allowed in ISO C90 [-Werror]
 //#pragma GCC diagnostic ignored "-Wunused-variable"
 ^
main.c:2:1: error: (this will be reported only once per input file) [-Werror]
main.c: In function 'main':
main.c:5:7: error: unused variable 'x' [-Werror=unused-variable]
   int x;
       ^
cc1: all warnings being treated as errors
mhoggan@mhoggan-Precision-T3600 ~/Devel/pragma $ g++ -Werror -Wall -pedantic main.c
main.c: In function 'int main()':
main.c:5:7: error: unused variable 'x' [-Werror=unused-variable]
   int x;
       ^
cc1plus: all warnings being treated as errors

A: I've got the same warning on g++ 5.3.0. I've found a nasty solution by adding a dummy function under the definitions such as:
...
static const error_category & posix_category = generic_category();
static const error_category & errno_ecat     = generic_caregory();
static const error_category & native_ecat    = system_category();

inline void dummy()
{
    (void) posix_category;
    (void) errno_ecat;
    (void) native_ecat;
}
...


text:
Q: How to attach js/css to a StreamField block when it is rendered? I know that you can include javascript in the form by using the django forms Media API and the js_initializer() method, and I've done so successfully. But I need to include a javascript and CSS file in the page when an instance of this custom block I've written gets displayed.
Is there a specific mechanism for that? Or do I just need to include the js/css files in the Page template? I'd really like to avoid including them on every single Page which has a StreamField that might have this block, since the vast majority won't, and that means a lot of wasted page load time.

A: This was previously discussed at https://github.com/wagtail/wagtail/issues/2490 - I haven't tried it, but I believe you could implement this by defining a frontend_media property on the relevant block classes that returns a django.forms.Media object, along with a function (a method on the page model is probably a good fit...) that collects those media definitions into a single object:
from django.forms import Media

class MyPage(Page):
    body = StreamField(...)

    def body_media(self):
        media = Media()
        for block_val in self.body:
            if hasattr(block_val.block, 'frontend_media'):
                media += block_val.block.frontend_media
        return media


text:
Q: ByteBuddy - transform all methods I am trying to mimic mock creation with byte buddy.
Is it possible to intercept all methods at once?
I tried the following:
new ByteBuddy()
   .subclass(Object.class)
   .method(nameMatches(".*"))
   .intercept(FixedValue.nullValue())

but it unfortunately does not work

A: This is possible doing this:
new ByteBuddy()
  .subclass(Object.class)
  .method(any())
  .intercept(StubMethod.INSTANCE);

You cannot use nullValue() as some methods do not return anything or a primitive type where null cannot be assigned. Therefore, Byte Buddy throws an exception for your example which indicates this.


text:
Q: Axios get request via NextJs is taking too long when under load I have a page that makes API call to a Django based backend in getInitialProps(). This call is taking 50-70s on average. I'm using Axios request/response interceptors to log the request duration. Initially we were assuming it was backend that is slow, but it seems to return a response in fraction of a second while at the same time NextJS application which is under 7req/s load is taking more than a minute. Also we see a significant increase in memory during this load.
Any hints as to how we can debug this?
We're using Node 10 and Next 10.


text:
Q: should virtual environments reside in envs folder? I am new to virtual environment concept in python and I am confused with something which may arise because of my lack of knowledge in general computer science.
I know that whenever I want to create a python .py file in spyder, I set my desired directory as my working directory in spyder (for example driver D).
What if I want to create a virtual directory? I mean I've created a virtual directory with some instructions on the internet and it successfully created in this path:

C:\Users\my_name\AppData\Local\Continuum\anaconda3\envs

If I want to create a new python .py file in that virtual environmrnt, should I set the directory in spyder, the above mentioned path?

A: You don't need to create a python file in that directory, you can create it anywhere in any directory. You just need to activate/choose the environment before running that python file.
Also virtual environments can be created anywhere but that's not recommended.


text:
Q: Node.JS/Express store DB config for different environment in JSON I'm running NodeJS Express app,
Currently have dev env, test env, and prod env.
However, the DB connection settings are in the code, is there a secure and best practice way to store DB config and all other configs in JSON file format by declaring them in a module (separately for each env or all in one module to be exported, maybe have a default.JSON, Dev.JSON, Prod.JSON...etc) for each environment then require them accordingly by setting the correct configuration for the correct environment in app.js.
I would like to achieve this without depending on any 3rd party package like .env or ncof.

A: You can require file based on the environment.
const env = 'test';  // This value can be taken from config or .env
const configs = require(`../path/${env}`);
console.log('DB Config', configs.DB_PATH);

Depending on your environment you can load the file. And value for environment can be retrieved from .env or any other config.

A: Most of the main NodeJs hosting providers uses a simple environment variable. You can use this :
process.env.NODE_ENV

For defining it by yourself, for exemple 'development' on your local, you can do :
NODE_ENV=developpment node yourapp.js

With this, I suggest you to use a config tool, like nconf (there are some good competitors). You can do like this for example :
nconf
    .argv() // Takes arguments from CLI
    .file('./env.' + process.env.NODE_ENV + '.json') // takes from specific env file
    .file('package', './package.json'); // takes from package.json

Here priority is from the most important to the least :
1) argv
2) specific environment file
3) package.json


text:
Q: Html 5 required field validator is not showing validation message I am having a simple html form with the required validator set to one of its input field, but I do not get the validation message
Can you please help where am I going wrong??

<form id="newrentalform">

    Customer

      <input id="customer" type="text" class="form-control" required>

    Movie

      <input id="movie" type="text" value="" class="form-control">

  <button class="btn btn-primary">Submit</button>
</form>


text:
Q: TikZ flowchart child Is it possible to show block C as a single block rather than having 3 blocks?

\documentclass[landscape]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[margin=1in]{geometry}
\usepackage{tikz-qtree}
\usetikzlibrary{shadows,trees}
\begin{document}
\tikzset{font=\small,
edge from parent fork down,
level distance=1.75cm,
every node/.style=
    {top color=white,
    bottom color=blue!25,
    rectangle,rounded corners,
    minimum height=8mm,
    draw=blue!75,
    very thick,
    drop shadow,
    align=center,
    text depth = 0pt
    },
edge from parent/.style=
    {draw=blue!50,
    thick
    }}

\centering

\begin{tikzpicture}
\Tree [.A
        [.{B}
            [.{C} ]
]
        [.{D}
            [.{C} ]
 ]
 [.{C}
]
        [.{E}
]
]
\end{tikzpicture}

\end{document}

A: Since the required object will no longer be a tree (it has cycles), then it could be better to draw it without tikz-qtree; the following code shows some possibilities:
\documentclass[landscape]{article}
\usepackage{tikz}
\usetikzlibrary{positioning,shadows}

\begin{document}

\tikzset{font=\small,
every node/.style=
    {top color=white,
    bottom color=blue!25,
    rectangle,rounded corners,
    minimum height=8mm,
    draw=blue!75,
    very thick,
    drop shadow,
    align=center,
    text depth = 0pt
    },
myedge/.style=
    {draw=blue!50,
    thick
    }}

\begin{tikzpicture}
\node (a) {A};
\node[below=of a] (d) {D};
\node[right=of d] (e) {E};
\node[left=of d] (b) {B};
\node[below=of b] (c) {C};
\foreach \pare/\chil in {a/b,a/d,a/e,b/c,d/c}
  \draw[myedge] (\pare.south) -- (\chil.north);
\draw[myedge] (a.south) -- (c.north);
\begin{scope}[xshift=5.5cm]
\node (a) {A};
\node[below=of a] (d) {D};
\node[right=of d] (e) {E};
\node[left=of d] (b) {B};
\node[below=of b] (c) {C};
\foreach \pare/\chil in {a/b,a/d,a/e,b/c,d/c}
  \draw[myedge] (\pare.south) -- (\chil.north);
\draw[myedge] (a.south) .. controls (-3.5cm,-1.5cm) .. (c.north);
\end{scope}
\begin{scope}[xshift=8cm]
\node (a) {A};
\coordinate[below=of a] (aux);
\node[right=of aux] (b) {B};
\node[right=of b] (d) {D};
\node[right=of d] (e) {E};
\node[below=of aux] (c) {C};
\foreach \pare/\chil in {a/b,a/d,a/e,b/c,d/c}
  \draw[myedge] (\pare.south) -- (\chil.north);
\draw[myedge] (a) -- (c);
\end{scope}
\end{tikzpicture}

\end{document}

If you want to keep the tikz-qtree syntax and style, then you could do something like this:
\documentclass[landscape]{article}
\usepackage{tikz-qtree}
\usetikzlibrary{shadows,trees,calc}

\begin{document}
\tikzset{font=\small,
edge from parent fork down,
level distance=1.75cm,
every node/.style=
    {top color=white,
    bottom color=blue!25,
    rectangle,rounded corners,
    minimum height=8mm,
    draw=blue!75,
    very thick,
    drop shadow,
    align=center,
    text depth = 0pt
    },
edge from parent/.style=
    {draw=blue!50,
    thick
    }}

\begin{tikzpicture}
\Tree [.\node (a) {A};
        [.{B}
            [.\node (c) {C}; ]
]
        [.\node (d) {D};
 ]
        [.{E}
]
]
\draw[edge from parent] let \p1=(d.south), \p2=(c.north) in
  (d.south) |- ( $ (d.south) + (0,0.5*\y2-0.5*\y1) $ ) -| (c.north);
\draw[edge from parent] let \p1=(a.south), \p2=(d.north) in
  (a.south) -- ++(0,0.5*\y2-0.5*\y1) -- ++(-1.3,0) |- ( $ (c.north) - (0,0.5*\y2-0.5*\y1) $ ) -- (c.north);
\end{tikzpicture}

\end{document}


text:
Q: Interpretting a linear regression model with interactions I'm running a linear regression model to understand the affect of my treatment (reminders) on my outcome variable (Class attendance).
I ran my model with two dummy covariates (age and previously attended class) along with the interaction of these dummies with treatment. The table below shows the results of the regression
If I were to interpret model 3, would it be accurate to think that while the treatment was effective in increasing attendance, this main effect is diminished somewhat when considering the positive and significant interaction the treatment had with individuals who previously attended the class? How do I interpret the second, non-significant interaction term in my regression and comparing it to the main effect for treatment?
Thanks you!

A: It's risky to ignore an interaction with a substantial magnitude even if it doesn't pass a test of "statistical significance." The magnitude of your point estimate of the older:treatment interaction term is 5 times larger than that of  the "significant" previous_attended:treatment interaction. It's twice the magnitude of the treatment single-predictor coefficient.
Once you have a model, it's unwise to remove a term just because it doesn't pass an arbitrary threshold of "statistical significance"; that's to a great extent just a function of sample size. See Frank Harrell's online notes, for example Section 4.12: "Don't remove insignificant individual effects from the model."
With the interactions you should be very wary of interpreting what you seem to consider the "main effect" coefficients (the first 3 rows of the table). There is no single "main effect" for a predictor involved in an interaction, as its association with outcome depends on the values of its interacting predictors. The estimate of its "main effect" and the corresponding p-value depends on the coding of the predictors with which it interacts. See this page for example.
When you have interaction terms, it's safest not to try to interpret the single-predictor coefficients on their own. Evaluate the overall significance of each predictor, including all of its interactions, via ANOVA. Then display the model predictions for representative combinations of predictor values.


text:
Q: Generating a URL in ActionFilterAttribute based on a Controller and Action I am using an ActionFilterAttribute in ASP.NET Core project. Apart of this method under some circumstances will generate a URL pointing to a controller/action which will be used by our React.js project.
For example we want to generate a URL like this http://localhost:1234/api/GetSomething/1
Currently i am using the ActionExecutingContext and  Microsoft.AspNetCore.Mvc.Routing.UrlHelper to generate a URL for action method
e.g.
var action = new UrlHelper(actionContext).Action("get", "Controller", new {id});
This works fine when running the code normally, however it is causing a unit test to fail with an index out of range exception when it try to call the Action extension helper.
The test is creating an ActionExecutingContext and setting actionContext, I have tried creating a new RouteData and adding a couple of fake values, but it still fails.
I presume that something is being set during startup.cs perhaps app.UseMvc()? That the test is not doing.
Does anyone have any suggestions both on how to properly generate a URL in ActionFilterAttribute ideally based on a controller and action or on how to get my test working?


text:
Q: Tracy debugger: No output with ajax exceptions Whenever I make an ajax request that throws an exception, the Tracy debugger is killing all output.
I've tested with Tracy turned off and exceptions get output.  I've tested with just a page (ie: not ajax) and the exception gets output by Tracy properly.
I believe I've traced the problem to Bluescreen::render():

public function render($exception)
    {
        if (Helpers::isAjax() && session_status() === PHP_SESSION_ACTIVE) {
            echo $exception->getMessage();

            ob_start(function () {});

            $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/content.phtml');
            $contentId = $_SERVER['HTTP_X_TRACY_AJAX'];
            $_SESSION['_tracy']['bluescreen'][$contentId] = ['content' => ob_get_clean(), 'dumps' => Dumper::fetchLiveData(), 'time' => time()];

        } else {
            $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/page.phtml');
        }
    }

I added the echo line at the top.  It gets output.
The reason I'm asking on SO and not filing a bug report, is because just this morning it was working - the exception text was output, followed by a backtrace, followed by a message saying "unable to log error...".  So I'm fairly certain the problem is mine, but I can't figure out where.
I have deleted my copy of Tracy and re-pulled from GitHub, so I'm using the latest & greatest version.


text:
Q: ffmpeg - Cannot use rename on non file protocol, this may lead to races and temporary partial files error I'm getting the following error when I convert my video to hls
Cannot use rename on non file protocol, this may lead to races and temporary partial files

As far as I can see, it doesn't cause any problems, but I want to know what I'm doing wrong.
Here's the command I use to convert to HLS:
ffmpeg -i "C:\Video\my_video.mp4" -codec: copy -start_number 0 -muxdelay 0 -hls_time 4 -hls_list_size 0 -f hls "C:\Video\hls\my_video"

I'm not doing any re-encoding or any renaming.

A: I found the message is logging from the tool only.
Please try with:
ffmpeg -i input.mp4 -profile:v baseline -level 3.0 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls output.m3u8


text:
Q: Why does my router stop serving sites/endpoints? When I am browsing Imgur, for example, if I move too quickly between images with the right arrow after about 20 images my router will stop serving that endpoint. Other sites will continue to work for a while, but slowly one by one each site I try to go to will stop working. When I restart the router, everything works again.
Why is this happening? Is there a way to reconfigure my (Earthlink) router to prevent it?

A: It is possible that Imgur is using all your Internet bandwidth. If you close the Imgur Window before your connection freezes do the other sites then load?

A: Ok and you say it is a router. Are you able to cable your machine directly to the modem? That would eliminate the router being the issue. Also, this could be caused by security software, content filters or Ad Blockers as well.


text:
Q: VPN and internet access on Linux My aim is to connect through a VPN via L2TP to my 4G router at home to exploit an SSH connection. I have linux KDE installed. The connection is established correctly but most of the most heavy websites (stackoverflow itself) will not work (instead wikipedia is working). The SSH connection is established via terminal but it is not working on VS Code.
What I tried to now:
reduce the MTU on 4G router and also change the router.
connecting to the same router via MacOs is working fine.
connecting to another router (completely different internet provider/connection) works.


text:
Q: '' is not a valid value of the atomic type 'xs:integer' xml can contain an element whose data type is integer and it could be empty also. I am getting the error
'' is not a valid value of the atomic type 'xs:integer'
Is there a way to specify only min length for this element or something like the value of this element is optional in xsd?

A: There are two approaches:
(a) define a union type that allows either an integer, or a zero-length string
(b) define a list type with an item type of xs:integer, with minLength=0 and maxLength=1.
Both are equivalent from the point of view of validation. (a) is more commonly seen, but in my view (b) is simpler. They will likely give different results if you are doing data typing with the schema rather than just validation, for example if you are using schema-aware XSLT or XQuery, or JAXP-style data binding.

A: Michael Kay has given two possible solutions, but a third (and in some ways simpler) option is to indicate the element as nillable. When it is nillable, you can leave it blank and indicate it as nil using xsi:nil="true".
However, if you don't have any control over the XML such that you could include xsi:nil, then you'd need to go with one of Michael Kay's suggestions.
Schema:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="n">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="count" minOccurs="0"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="count" type="xsd:integer" nillable="true" />
</xsd:schema>

XML:
<n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <count xsi:nil="true" />
</n>


text:
Q: Adding multiple keywords with Exiftool, but only if they're not already present I'm running the following command to add multiple keywords to an image:
exiftool  -keywords+="Flowering"  -keywords+="In Flower"  -keywords+="Primula vulgaris"  -overwrite_original "/pictures/Some Folder/P4130073.JPG"

However, I've noticed that if I do this for an image which already contains a particular keyword, then it'll get added a second time.
How can I ensure that keywords are added only if they're already missing, and that if they exist, it'll do a no-op (and ideally leave the file untouched). I've read a few questions on the forum and the docs, but NoDups docs isn't clear to me (I'm an exiftool n00b) and all the answers I've found only process a single keyword addition.
For an added bonus, if the 'exists' check could be case-insensitive, so much the better (e.g., so that if I'm doing keywords+="Flowering" and the image already has the keyword "flowering", nothing will be done.
I also need this to work on Linux, MacOS and Windows (I know the quotes can complicate things!).

A: See Exiftool FAQ #17

To prevent duplication when adding new items, specific items can be
deleted then added back again in the same command. For example, the
following command adds the keywords "one" and "two", ensuring that
they are not duplicated if they already existed in the keywords of an
image:
exiftool -keywords-=one -keywords+=one -keywords-=two -keywords+=two DIR

The NoDups helper function is used to remove duplicates when they already exist in the file.  It isn't used to prevent duplicates from being added in the first place.


text:
Q: Can the angular velocity of a prolate spheroid change over time in the absence of external forces? Given a prolate spheroid (ie a Rugby Ball/American Football), with an initial angular velocity about an axis that coincides with one of the shape's primary axes, it seems obvious that in the absence of external forces, the body will continue to rotate with unchanging angular velocity about that axis.
However, if the initial angular velocity is about an axis that does not correspond to one of the shape's primary axes, is this still true? Or does the angular velocity change over time, eventually aligning it self with the long axis of the ball?
The reason I ask this is because in my modelling, this seems to be what happens, and I don't know if it's correct or not!
I should add that if I change the Inertia Tensor of my model to that of a sphere, rather than an prolate spheriod, I do not observe this phenomenom - in this case, the angular velocity remains constant. The code I have written is based directly on the examples given in this paper:
https://www.cs.cmu.edu/~baraff/sigcourse/notesd1.pdf

A: Yes it's almost normal. In the reference of your ball, the angular momentum traces out a line determined by the conservation of rotational energy and of angular momentum magnitude (intersection of two surfaces).
Mathematically, writing (everything in the ball's perspective) $\Omega,M,J$ the angular velocity, angular momentum and inertia tensor, you have $M=J\Omega$ and conservation of energy:
$$
K_{rot}= \frac{1}{2}\Omega\cdot M
$$
and angular momentum magnitude:
$$
M^2
$$
So in $M$ space, the curve is the intersection of an ellipsoid and a sphere. Check out Arnold's Mathematical Methods for Classical Mechanics for more.
In the case of two equal principal moments of inertial (rotational symmetry about an axis like a rugbyball), then this curve is even a circle from symmetry.
In the case of a completely isotropic inertia tensor (ex: sphere) this curve degenerates to a point (two surfaces coincide as rotational energy is a function of angular momentum magnitude).
Note that rigorously from the exact conservation laws, the angular momentum (or equivalently the angular velocity) will never align itself to the principal axis unless you included friction. In this case, this is due to numerical dissipation due to your inexact solver. In general, checking conservation laws it a good test for solvers. You could also check out symplectic solvers which deal with this problem.
Hope this helps.

A: Well, numerical analysis is by its nature approximation.
You describe that the model tends to slide towards a state where angular velocity becomes aligned with a principal axis.
If the model would be a perfect representation of the idealized case then the motion would not slide towards a simpler pattern of motion.
Example: Feynman's wobbling plate.
In the idealized case the wobbling pattern remains the same forever. (If the wobbling plate is in air then air friction will dissipate the kinetic energy associated with the wobbling, and the motion pattern will shift to spinning without wobbling.)
With a perfect model both angular momentum and kinetic energy are conserved. The drift that you see indicates that one of them, or both, are not conserved in the numerical analysis, presumably due to the fact that numerical analysis cannot be exhaustively precise. As a consequene in long runs there will be accumulation of error.

One way to mitigate drift of quantities that are supposed to be conserved is to include at regular intervals (or simply every step) a rectification. This rectification would then consist of adjusting the current velocities in such a way that quantities that you want to be conserved are conserved.
Presumably there are trade-offs involved with any type of numerical analysis solver.
In the other answer symplectic solvers are mentioned, which have the property of not leaving room for the conserved quantities to drift. (It may be, I don't know, that with symplectic solvers you get drift just as well, but with the drift manifesting itself elsewhere.)

The bottom line, in my opinion:
Numerical analysis comes with accumulation of error. If you let the numerical analysis model run for a long time significant accumulation of error is inevitable. I submit that numerical analysis should be used only for short runs. More precisely, the rate of accumulation of error should be assessed, then you set a limit of acceptable error, and that gives you an estimate for how long the model can be run until it has accumulated the earlier decided limit of acceptable error.

You mention:
"[...] if I change the Inertia Tensor of my model to that of a sphere, rather than an prolate spheriod, I do not observe this phenomenom - in this case, the angular velocity remains constant."
Hypothesis:
The way the numerical solver is implemented does not drift the angular veloicity if the starting motion is a particularly simple motion pattern (in this case circular motion)
That is, I expect that the difference that you have observed does not arise from a physics circumstance, but that it arises from some mathematical property of the solver implementation.


text:
Q: PHP headers already sent while redirecting page
Possible Duplicate:
Headers already sent by PHP

Hello there when i go to the site it says
Warning: session_register() [function.session-register]: Cannot send session cache limiter - headers already sent (output started at /home/content/49/5712349/html/c/admin/admin.php:17) in /home/content/49/5712349/html/c/admin/admin.php on line 39

Warning: Cannot modify header information - headers already sent by (output started at /home/content/49/5712349/html/c/admin/admin.php:17) in /home/content/49/5712349/html/c/admin/admin.php on line 41

I saw other questions and none answered me.
Here is the code thanks a lot.
<?php

if (isset($_SESSION['mattyc-admin'])){
    header ('Location: admin/home.php');
}

if (!isset($_GET['me'])){
    header ('Location: http://www.stat-me.com/mattyc');
}

if ($_GET['me'] != 'mattyc'){
    header ('Location: http://www.stat-me.com/mattyc');
}

?>

<?php

if ($_POST['name'] != "" && $_POST['password'] !="") {

//require "../../scripts/connect_to_mysql.php";

$name = $_POST['name'];
$pass = $_POST['password'];

$name = strip_tags($name);
$pass = strip_tags($pass);
//$name = mysql_real_escape_string($name);
//$pass = mysql_real_escape_string($pass);
$name = eregi_replace("`", "", $name);
$pass = eregi_replace("`", "", $pass);

//$pass = md5($pass);

if ($name == 'mattyc' && $pass == 'qwerty'){
    if (isset ($_SESSION['mattyc-admin'])){
        header ('Location: admin/upload.php');
    }else{
     session_register('mattyc-admin');
     $_SESSION['mattyc-admin'] = ('mattyc-adminp');
     header ('Location: admin/upload.php');
    }
}

}
?>

A: the problem is between lines 16 and 18:
?>

<?php

this will write some whitespace (and send headers)

A: ob_clean();

Add the above before the offending code. Cleans the buffer or something.
If you would have googled for it http://www.google.co.in/search?q=Warning%3A+session_register%28%29+[function.session-register]%3A+Cannot+send+session+cache+limiter+-+headers+already+sent
the first result has the solution which says

make sure you have added ob_start();
  at the first line of webpage and
  ob_end_flush(); at the end of webpage //i have used ob_end_clean() or ob_clean() in a similar case

Update:
I was downvoted. So let me clarify.
In the code in question , the space between the php tags was seen clearly and so the solution was straightforward. However, if the question in issue was not that simple, perhaps it was a include file which was problematic. What if the code ran into reams and reams before generating a space or other output and you couldn't track it? What if?
If you enclose stuff you do not want output for between ob_start() and ob_end_clean(). The output is not sent. ob_clean() does something similar.
Update 2
As Col. Shrapnel said

Never gag an error

Soultion: Remove the offending space.
Update for @meagar
While the answer to this problem should be removal of the space, I am posting a solution for the problem using, ob_clean() just for the upvote(I hate downvotes! :))
<?php
ob_start(); //started buffering
?>
Hello World and other dangerous texts
<?php
if (isset($_SESSION['mattyc-admin'])){
    header ('Location: admin/home.php');
}

if (!isset($_GET['me'])){
    header ('Location: http://www.stat-me.com/mattyc');
}

if ($_GET['me'] != 'mattyc'){
    header ('Location: http://www.stat-me.com/mattyc');
}

?>

<?php
if ($_POST['name'] != "" && $_POST['password'] !="") {

//require "../../scripts/connect_to_mysql.php";

$name = $_POST['name'];
$pass = $_POST['password'];

$name = strip_tags($name);
$pass = strip_tags($pass);
//$name = mysql_real_escape_string($name);
//$pass = mysql_real_escape_string($pass);
$name = eregi_replace("`", "", $name);
$pass = eregi_replace("`", "", $pass);

//$pass = md5($pass);
ob_clean(); //can use ob_end_clean() too
if ($name == 'mattyc' && $pass == 'qwerty'){
    if (isset ($_SESSION['mattyc-admin'])){
        header ('Location: admin/upload.php');
    }else{
     session_register('mattyc-admin');
     $_SESSION['mattyc-admin'] = ('mattyc-adminp');
     header ('Location: admin/upload.php');
    }
}

}
?>

With output buffering set to Off in my php.ini, I tested the above code. Just add ob_start to the start of the page. ob_clean() is only needed to end buffering. If you are sure that the page will show no output and only redirect then ob_clean is not needed too. (Otherwise use ob_clean() before the problematic code segment.)
Thanks to @meagar for the code and inspiration.

A: Between your two PHP tags you have whitespace.
?>

<?php

This'll cause your headers to be sent before starting any session and sending more headers.
I suggest just removing that bit of code.


text:
Q: Desafio em python. Dúvida O desafio: receber uma string s  e um numero inteiro k, então deve separar a string em sub-strings de comprimento s/k e por fim retirar as letras repetidas em cada sub-strings. Segue o código:
def merge_the_tools(string,k):
n=len(string)
merge= n//k
separador=[]
lista=[]
for i in range(merge):
    start= int(i*n/merge)
    end= int((i+1)*n/merge)
    separador.append(string[start:end])
for i in range(len(separador)):
    lista.append(list(separador[i]))
return lista

aux=[]
result=merge_the_tools('AABCAAADA', 3)

for i in range(len(result)):
    aux.append(list(set(result[i])))
    print(aux[i])

Porém na hora de imprimir a saída tenho que ter a seguinte resposta:
AB
CA
AD

E o que eu tenho é uma resposta invertida quando uso o set():
BA
AC
DA

não consigo entender o motivo disso.

A: Se você verificar a documentação verá que diz:

A set object is an unordered collection of distinct hashable objects.

Tradução livre:

Um objeto set (conjunto) é uma coleção não-ordenada de objetos "hasheable" distintos.

Assim como os conjuntos que estudamos na matemática, um conjunto é um grupo de elementos onde sua ordem e repetição de elemento não é relevante.
Se você acessar a Wiki sobre o conceito de conjuntos verá que o conjunto A = {1, 2, 2, 1, 3, 2} é equivalente ao conjunto A = {1, 2, 3}. E isso se reflete python também:
a = {1, 2, 2, 1, 3, 2}
b = {1, 2, 3}

a == b
# True

a
# {1, 2, 3}
b
# {1, 2, 3}

Se você precisa que a ordem seja mantida no seu código, você de usar uma sequência, que é uma coleção onde a ordem importa. Por exemplo: listas e tuplas.
PS: Há um tempo li em algum lugar que a implementação de sets do CPython é uma "modificação" da implementação de dict, ou seja, sets seriam como dicionários sem valores, apenas as chaves. Confesso que, apesar de ter confirmado a afirmação após ter verificado o código fonte na época, não consigo mais achar esta referência. Porém é relevante deixar aqui a informação de que a partir do Python 3.7 a implementação de dict do CPython mantém a ordem de inserção das chaves do dicionário (veja no change log) então esta informação pode não ser mais verdadeira.


text:
Q: order rows based on some sequence I have a table like this
ID   Subject       StatusCd     Date
------------------------------------------
1    abc           3            01/03/2013
2    def           1            01/03/2013
3    ghi           2            05/03/2013
4    jkl           3            02/03/2013
5    mno           3            06/03/2013

How can I write a SQL query which will order rows in this sequence of StatusCd (3, 1, 2).
Also I want to sort each row in a group based on its Date.

A: You can use a CASE expression the the ORDER BY clause:
select id, subject, statuscd, date
from yt
order by
  case statuscd
    when 3 then 0
    when 1 then 1
    when 2 then 2
  end, date

See SQL Fiddle with Demo. This gives a result:
| ID | SUBJECT | STATUSCD |       DATE |
----------------------------------------
|  1 |     abc |        3 | 2013-01-03 |
|  4 |     jkl |        3 | 2013-02-03 |
|  5 |     mno |        3 | 2013-06-03 |
|  2 |     def |        1 | 2013-01-03 |
|  3 |     ghi |        2 | 2013-05-03 |

A: Please try:
select
    ID,
    [Subject],
    StatusCd,
    [Date]
from
    YourTable
order by case StatusCd when 3 then 0 else StatusCd end,
    [date]


text:
Q: How do I continue using an iterator after calling take? I want to collect a few items from an iterator, then iterate through the rest, something like this:
let iterator = text.split_whitespace();
let first_ten_words = iterator.take(10).collect();

for word in iterator {
    // This should iterate over the remaining words.
}

This doesn't work because take() consumes the iterator.
Obviously I can use split_whitespace() twice and skip(10) but I assume that will do the splitting of the first 10 words twice, and therefore be inefficient.
Is there a better way to do it?

A: You can use .by_ref() like this:
let iterator = text.split_whitespace();
let first_ten_words = iterator.by_ref().take(10).collect();

for word in iterator {
    // This should iterate over the remaining words.
}


text:
Q: Moving from one android app to another directly How can i make my android application use the default applications like mesaaging,etc. I also want to use a bluetooth terminal application from my android application! How do i do this??
Thanks in advance:D


text:
Q: How to modify data type of a column that is foreign key or primary key? I have a three tables. One is course, section and other is prerequisite.
CREATE TABLE course(
  course_number int(11) NOT NULL AUTO_INCREMENT,
  course_name varchar(20) NOT NULL,
  credit_hours int(11) NOT NULL,
  department varchar(5) NOT NULL,
  PRIMARY KEY (course_number)
)

CREATE TABLE section (
  section_id int(11) NOT NULL,
  course_number` int(11) NOT NULL,
  semester varchar(6) NOT NULL,
  year year(4) NOT NULL,
  instructor varchar(20) DEFAULT NULL,
  PRIMARY KEY (section_id),
  FOREIGN KEY (course_number) REFERENCES course (course_number)
)
create table prerequisite(
    course_number int not null auto_increment,
    prerequisite int not null,
    primary key (course_number),
    foreign key (prerequisite) references course(course_number)
    );

I want to change datatype of my course_number in both tables, but when I run the query
alter table course change course_number course_number varchar(20);

I see the following error:

Cannot change column 'course_number': used in a foreign key constraint 'section_fk' of table 'university.section'

What is the problem in here? What is the best solution? By saying the best solution, I mean, not loosing any data or dropping any table and creating from scratch.

A: Drop the foreign key, change both tables and add the foreign key. It is btw good idea to name your constraints explicitly. Now you will have to look up what the constraint name is in the catalog:
select CONSTRAINT_NAME from information_schema.REFERENTIAL_CONSTRAINTS
where TABLE_NAME = 'prerequisite'
  and REFERENCED_TABLE_NAME = 'course'

alter table prerequisite drop constraint ...;

alter table course change course_number course_number varchar(20);
alter table prerequisite change course_number course_number varchar(20);

alter table prerequisite add constraint <name>
    foreign key (course_number)
    references course (course_number)
        <actions>;


text:
Q: Linux terminal-based CSV or TSV editor - command-line Calc? I'm trying to find a command line editor (or vim plugin) for large CSV or TSV files that will fix the width of cells and keep the row and column headers in view so I can move between cells and edit data.  Basically something like the old DOS versions of Lotus 123 or Quattro Pro.
I find myself continually doing quick fixes in tabular data and don't want to fire up Calc every single time I want to change a few cells in column 32.  I am not looking for perl/awk solutions since most of the fixes are one-off spelling/case data entry errors.

A: Take a look onto sc or Gnu Oleo, the may fit your need's
Also a look onto the Emacs based Spreadsheets may be worth a look
cheerio
   Steve

A: Sounds like you could use vim with ts/sw and friends to set up your columns widths, and then :1split to keep headers in view.  You can also (assuming your CSV data doesn't have tabs in it already) do something like:
%s/,/\t/g

to switch commas to tabs, and
%s/\t/,/g

to switch them back, since it's easier to format TSV than CSV.

A: i suggest emeditor through wine


text:
Q: How to resolve the following error in Django(1.4.2) Am getting the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\__init__.py", line 459, in execute_manager
utility.execute()
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\base.py", line 232, in execute
output = self.handle(*args, **options)
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\base.py", line 371, in handle
return self.handle_noargs(**options)
File "C:\Users\Blue\Anaconda\lib\site-packages\django\core\management\commands\syncdb.py", line 57, in handle_noargs
cursor = connection.cursor()
File "C:\Users\Blue\Anaconda\lib\site-packages\django\db\backends\dummy\base.py", line 15, in complain
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check
settings documentation for more details.

following is my settings.py:-
    # Django settings for ecomstore project.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

SITE_NAME = 'Modern Musician'
META_KEYWORDS = 'Music, instruments, sheet music, musician'
META_DESCRIPTION = 'Modern Musician is an online supplier of instruments, sheet music, and other accessories for musicians'

# CURRENT_PATH = os.path.abspath('.').decode('utf-8').replace('\\','/')
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

# Upon deployment, change to True
ENABLE_SSL = False

# Uncomment the following line after you have installed memcached on your local development machine
#CACHE_BACKEND = 'memcached://127.0.0.1:11211/'

MANAGERS = ADMINS

DATABASE_ENGINE = 'django.db.backends.mysql'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME =os.path.join(BASE_DIR, 'db.mysql'),
             # Or path to database file if using sqlite3.
DATABASE_USER = 'root'             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Los_Angeles'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

CACHE_TIMEOUT = 60 * 60

PRODUCTS_PER_PAGE = 1
PRODUCTS_PER_ROW = 4

LOGIN_REDIRECT_URL = '/accounts/my_account/'

SESSION_COOKIE_DAYS = 90
SESSION_COOKIE_AGE = 60 * 60 * 24 * SESSION_COOKIE_DAYS

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'static')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/static/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/static/admin_media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'io_)m-ijh_g#cz-k1p3=tzazb6v3d)h_u8b9cvex9yn%zbakmn'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'ecomstore.utils.context_processors.ecomstore',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.csrf.middleware.CsrfMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'djangodblog.DBLogMiddleware',
    'ecomstore.marketing.urlcanon.URLCanonicalizationMiddleware',
    'ecomstore.SSLMiddleware.SSLRedirect',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)

AUTH_PROFILE_MODULE = 'accounts.userprofile'

ROOT_URLCONF = 'ecomstore.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(CURRENT_PATH, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.flatpages',
    'ecomstore.catalog',
    'ecomstore.cart',
    'ecomstore.accounts',
    'ecomstore.search',
    'ecomstore.checkout',
    'ecomstore.utils',
    'ecomstore.stats',
    'djangodblog',
    'tagging',
    'django.contrib.sitemaps',
    'django.contrib.redirects',
    'ecomstore.billing',
    'ecomstore.caching',
)
# for use with URL Canonicalization Middleware:
# this is the canonical hostname to be used by your app (required)
CANON_URL_HOST = 'www.your-domain.com'
# these are the hostnames that will be redirected to the CANON_URL_HOSTNAME
# (optional; if not provided, all non-matching will be redirected)
CANON_URLS_TO_REWRITE = ['your-domain.com', 'other-domain.com']

# Google Checkout API credentials
GOOGLE_CHECKOUT_MERCHANT_ID = ''
GOOGLE_CHECKOUT_MERCHANT_KEY = ''
GOOGLE_CHECKOUT_URL = 'https://sandbox.google.com/checkout/api/checkout/v2/merchantCheckout/Merchant/' + GOOGLE_CHECKOUT_MERCHANT_ID

# Authorize.Net API Credentials
AUTHNET_POST_URL = 'test.authorize.net'
AUTHNET_POST_PATH = '/gateway/transact.dll'
AUTHNET_LOGIN = ''
AUTHNET_KEY = ''

# Google Analytics tracking ID
# should take the form of 'UA-xxxxxxx-x', where the X's are digits
ANALYTICS_TRACKING_ID = ''

try:
    from settings_local import *
except ImportError:
    pass

I am using Django-1.4.2 and mysql.Please help resolve this error as tomorrow I have my project submission.

A: DATABASES option is not configured in settings.py
Add this,
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

More information is at https://docs.djangoproject.com/en/1.4/ref/settings/


text:
Q: How to format numbers in Google API Linechart? I need to format the numbers in the axis and the numbers that appear when you hover your mouse over the line chart.

A: There are two steps involved. The first step is to find out what pattern you should use; the second step is to put the pattern in the proper place in your code. To make this post more beautiful, I show you step 2 and then step 1.
Step 2: Putting the pattern in your code
Here's the code:
var options = {
        hAxis: {format:'###,###'}
        vAxis: {title: 'Time', format:'0.0E00'},
    };
    var formatter1 = new google.visualization.NumberFormat({pattern:'###,###'});
    formatter1.format(dataTable, 0);
    var formatter2 = new google.visualization.NumberFormat({pattern:'0.0E00'});
    formatter2.format(dataTable, 1);
    var fchartvar = new google.visualization.LineChart(document.getElementById('fchart'));
    fchartvar.draw(dataTable, options);

vAxis: {title: 'Time', format:'0.0E00'} formats the  labels on the vertical axis.
This formats the numbers you see when you hover over points on the line chart:
var formatter1 = new google.visualization.NumberFormat({pattern:'0.0E00'});
formatter1.format(dataTable, 1);

Note how (dataTable,0) formats the hAxis information while (dataTable,1) formats the vAxis information (again, which you see when you hover over the points on the line chart).
The last two lines of code:
var fchartvar = new google.visualization.LineChart(document.getElementById('fchart'));
fchartvar.draw(dataTable, options);

are for you two compare with your own chart. Replace fchartvar,dataTable and fchart by the names used in your code. If you're using something other than line chart, replace LineChart with the chart you're using.
An example of 0.0E00 is turning 1,234 into 1.2E03.
Step 1: Finding the right pattern
Google NumberFormat documentation
NumberFormat supports the following options, passed in to the constructor: (source: Google NumberFormat documentation)
decimalSymbol

*

*A character to use as the decimal marker. The default is a dot (.).

fractionDigits

*

*A number specifying how many digits to display after the decimal. The
default is 2. If you specify more digits than the number contains, it
will display zeros for the smaller values. Truncated values will be
rounded (5 rounded up).

groupingSymbol

*

*A character to be used to group digits to the left of the decimal
into sets of three. Default is a comma (,).

negativeColor

*

*The text color for negative values. No default value. Values can be
any acceptable HTML color value, such as "red" or "#FF0000".

negativeParens

*

*A boolean, where true indicates that negative values should be
surrounded by parentheses. Default is true.

pattern

*

*A format string. When provided, all other options are ignored, except
negativeColor.
The format string is a subset of the ICU pattern set. For instance,
{pattern:'#,###%'} will result in output values "1,000%", "750%", and
"50%" for values 10, 7.5, and 0.5.
prefix

*

*A string prefix for the value, for example "$".

suffix

*

*A string suffix for the value, for example "%".

ICU DecimalFormat Reference
As you might have noticed from the Google NumberFormat documentation above, you can find out more detailed information about formatting the numbers from the ICU DecimalFormat Reference. Here is some of the most important information from the ICU DecimalFormat Reference (it's in the 'middle' of the webpage):

A DecimalFormat pattern contains a postive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric part, and a suffix. If there is no explicit negative subpattern, the negative subpattern is the localized minus sign prefixed to the positive subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit negative subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are ignored in the negative subpattern. That means that "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)".
The prefixes, suffixes, and various symbols used for infinity, digits, thousands separators, decimal separators, etc. may be set to arbitrary values, and they will appear properly during formatting. However, care must be taken that the symbols and strings do not conflict, or parsing will be unreliable. For example, either the positive and negative prefixes or the suffixes must be distinct for parse() to be able to distinguish positive from negative values. Another example is that the decimal separator and thousands separator should be distinct characters, or parsing will be impossible.
The grouping separator is a character that separates clusters of integer digits to make large numbers more legible. It commonly used for thousands, but in some locales it separates ten-thousands. The grouping size is the number of digits between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 0000". There are actually two different grouping sizes: One used for the least significant integer digits, the primary grouping size, and one used for all others, the secondary grouping size. In most locales these are the same, but sometimes they are different. For example, if the primary grouping interval is 3, and the secondary is 2, then this corresponds to the pattern "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a pattern contains multiple grouping separators, the interval between the last one and the end of the integer defines the primary grouping size, and the interval between the last two defines the secondary grouping size. All others are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####".
Illegal patterns, such as "#.#.#" or "#.###,###", will cause DecimalFormat to set a failing UErrorCode.

A: If you need to simply format all numbers shown in the graph, in the hover and in the axis according to the locale of a country, the simplest in IMHO is to use the country code when loading the library.
E.g.:

google.charts.load('44',  {packages: ['corechart', 'bar', 'sankey'], 'language': 'fr'});

That is the way I would format all numbers using space separators for thousands and a comma for the decimal place.


text:
Q: How to plot a greek letter on a 3D plot label with hist3D()? I am plotting a 3D histogram using hist3D(), and want to change xlab so that it includes a Greek letter with a subscript.
I used
xlab=expression(theta[1]).

It doesn't work, and I just get the string "theta[1]" in the label. It works fine, on the other hand, for just the regular plot command.
So how can I introduce subscripted Greek letters to hist3D() plots?
(hist3D() is in the plot3D library)

A: The hist3Dfunction does not accept expressions for axis labels. One workaround is to use the Unicode character for theta, θ.
# example data
library(plot3D)
x <- seq(-pi, pi, by = 0.2)
y <- seq(-pi, pi, by = 0.3)
grid <- mesh(x, y)
z <- with(grid, cos(x) * sin(y))

hist3D(z = z, x = x, y = y, border = "black", xlab = "θ1")

This displays a theta symbol but no subscript 1.

A: Another workaround is to use text3D function from the same plot3D package. It accepts the math expressions as labels so we can write as usual  expression(theta[1]). The only minor issue in this workaround is to find the suitable coordinates of our label
# example data
library(plot3D)
x <- seq(-pi, pi, by = 0.2)
y <- seq(-pi, pi, by = 0.3)
grid <- mesh(x, y)
z <- with(grid, cos(x) * sin(y))

hist3D(z = z, x = x, y = y, border = "black", ticktype = "detailed", xlab = "", ylab="y", zlab="z")
text3D(2, -5, 0, labels = expression(theta[1]), add = TRUE, adj = 1)

I have found that 2,-5,0 are quite good for this example. The label is not rotated one as in case of the regular labels.

A: A workaround is to use scatterplot3d:

z <- seq(-10, 10, 0.01)
x <- cos(z)+1
y <- sin(z)+1
scatterplot3d(volcano, highlight.3d=TRUE, col.axis="blue",
                            col.grid="gray", main="scatterplot-greeks", pch=21,
                            xlab=expression(theta[1]),
                            ylab=expression(beta[2]),
                            zlab=expression(alpha[3]),cex.lab=1.5)


text:
Q: Android Fragment InterstitialAd onBackPressed I am using a navigation drawer with fragments and inside one of the fragments I have a multi level list.
In my ActionBarActivity.java I have:
 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       ...
        // returning to previous
        if (item != null && item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

and the onBackPressed(); :
public void onBackPressed() {
        // return to the previous fragment stack
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStack();
            // show the ad
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
        } else {
            super.onBackPressed();
        }
    }

I want to display InterstitialAd when the user clicks back button in the multi level list fragment. The above solution works, but it only shows the ad once on a single item.
So here is a sample run:
- user opens the app and first fragments lists a list of items
- user clicks on Item #1 and enters that item details
- user clicks back (Ad is shown) and goes back to all items
- user clicks on Item #2 and enters that item details
- user clicks back (but Ad is not shown) and goes back to all items

not sure why when the user clicks the back for the second time and so on, ad is not shown. Can someone suggest a possible solution?
update #1:
here is how I create the interstitial ads on onCreate:
    // interstitial ads
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId(AD_ID);

    mInterstitialAd.setAdListener(new AdListener() {
       @Override
       public void onAdClosed() {
       }
   });
   requestNewInterstitial();

and :
private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();
        mInterstitialAd.loadAd(adRequest);
    }

A: After showing an interstitial you need to call interstital.loadAd() again.
So call it from onAdClosed() (as well as in onCreate()).


text:
Q: The type or namespace name 'MvvmValidation' could not be found (are you missing a using directive or an assembly reference?) SO I Have the following problem when trying to built an Xamarin.Forms project.

What i have tried so far :

*

*Clean solution -> Rebuilt

*Remove MvvmValidation nugget package and reinstall it

*Remove Manage Package from VS and Reinstall it

I'm clueless now on what should I do to make it work. An other coworked got the same git branch and it compiles. It's something with my VS but have no idea what.

As you can see from picture 2 and 3 the namespace is found.

A: gonna go out on a limb and say this is for WPF not Xamarin.Forms, matter in fact it doesn't even specify x-plat in its description.
https://github.com/pglazkov/MvvmValidation/releases  - very specific on what it will work with in the release docs.

A: The problem for my was an update to Visual Studio (had to update to VS 2015 Update 3) . After the update it compiles ok.


text:
Q: how to access files of a directory with ssh i am trying to tail all the files that are located in a directory on a remote server except the file the user enters as a third argument in the command line. For that, i need to grep the type of file to avoid confusion when directing the output of tail to another file.
The directory is /path/to/a/file, inside there exists two files, one called file.log and the other file.out. I would like to grep .out & .log
Here is my code:
files=$(ssh host find /path/to/a/file -type f -name '^file')

for type in $($files | awk -F'.' '{print $2}') ; do

ssh host find . /path/to/a/file -type f ! -name "$3" | xargs 0 tail -n 20 > /destination/dir/host.$type 2>/dev/null

Unfortunately, none of this works, and i don't know why.

A: There's a lot wrong with your code, but the biggest thing is that you are taking arguments to find that should exist in the first line and passing them to tail in the last line. Specifically -type f ! -name "$3"
That will get you closer.
Build the script one step at a time. Write it as
ssh host find ...

and make sure that is outputting the right set of files. Right now it isn't.

A: This regex is the problem:
-name '^file'

-name doesn't take regex it takes shell glob pattern.
Use this should work for you:
ssh host find /path/to/a/file -type f -name 'file*'

Update: To exclude a particular file from this list
ssh host find /path/to/a/file -type f \( -name 'file*' ! -name 'file.log00001' \)


text:
Q: How do I simply refresh a view in Backbone? I'm brand new to backbone and just learning the basics. I am building an image gallery with backbone. I am displaying a large version of an image. The routing is working properly. When a url is passed with an id the appropriate JSON is loaded into the model and the html is injected into the dom. Everything displays as expected.
However, I tried entering a url for the JSON for an image that didn't exist and noticed that the view still rendered but with the previously rendered view's properties (image url) still present. How do I ensure that the view is refreshed - all empty properties? Or is it the model that needs to be refreshed?
Note: I am re-using the view to avoid the overhead of creating and dystroying the view itself.
Here is the view in question:
var ImageView = Backbone.View.extend({
    template: Handlebars.compile(
        '
'+
        '
{{title}}
' +
        '' +
        '

'+
        '
' +
        '

'
    ),

    initialize: function  () {
        this.listenTo(this.model, "change", this.render);
        //this.model.on('change',this.render,this);
    },

    fbSharePhoto: function () {
        console.log('share to fb ' + this.model.attributes.shareUrl)
    },

    close: function () {

      //this.undelegateEvents();
      this.remove();
    },

    render: function () {

        this.$el.html(this.template(this.model.attributes));
        this.delegateEvents({
            'click .fb-share'               : 'fbSharePhoto',
            'click .black-overlay'          : 'close'
        });

        return this;
    }
})

Here is the router:
    var AppRouter = Backbone.Router.extend({
    routes: {
        ""                      :           "dashboard",
        "image/:iId"            :           "showImage",
    },

    initialize: function  () {

        // this.galleriesCollection = new GalleriesCollection(); //A collection of galleries
        // this.galleriesCollection.fetch();

        this.imageModel         = new Image();
        this.imageView          = new ImageView ({  model: this.imageModel });

    },

    dashboard: function () {
        console.log('@AppRouter show dashboard - hide everything else');

        //$('#app').html(this.menuView.render().el);
    },

    showImage: function (iId) {
        console.log('@AppRouter showPhoto() ' + iId);
        this.imageModel.set('id', iId);
        this.imageModel.fetch();
        $('#imageViewer').html(this.imageView.render().el);
    }

});

Is is it that the model still has the old info or the view, or both?
For extra credit, how could I detect a failure to fetch and respond to it by not triggering the corresponding view? Or I am I coming at it wrongly?
Thanks in advance for any advice.
////////////////////////////////////////////////////////////////////////////
Looks like I found something that works. I think just the process of framing the question properly helps to answer it. (I'm not allowed to answer the question so I'll post what I found here)
It appears that its the model that needs refreshing in this case. In the app router when I call the showImage function I clear the model and reset its values to default before calling fetch and this did the trick. Ironically the trick here is showing a broken image tag.
showImage: function (iId) {
console.log('@AppRouter showPhoto() ' + iId);
this.imageModel.clear().set(this.imageModel.defaults);
this.imageModel.set('id', iId);
this.imageModel.fetch();
$('#imageViewer').html(this.imageView.render().el);
}

For my own extra credit offer: In the event of an error (if needed fetch() accepts success and error callbacks in the options hash). Still definitely open to hearing about a way of doing this thats baked in to the framework.

A: You can just update the model like this:
ImageView.model.set(attributes)


text:
Q: Python How to hide traceback in unittest guys, I have a unittest was where I don't want to throw exception when find one but wait until the end and output raise it at the end.:
from unittest import TestCase
class TestA(TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_lst(self):
        a = [1, 2, 3, 4, 5]
        b = [1, 3, 3, 5, 5]
        total_errs_count = 0
        total_errs_msg = []
        for i in range(5):
            try:
                self.assertEqual(a[i], b[i])
            except AssertionError:
                total_errs_count += 1
                total_errs_msg.append(f'Index {i}, Expected {a[i]}, Get {b[i]}')
        if total_errs_count > 0:
            for m in total_errs_msg:
                print(m)
            raise AssertionError("Test Failed")

test = TestA()
test.test_lst()

I got:
IOndex 1, Expected 2, Get 3
Number 3, Expected 4, Get 5
----------------------------------------------------
AssertionError     Traceback (most recent call last)
<ipython-input-5-b70dc996c844> in <module>
     27
     28 test = TestA()
---> 29 test.test_lst()

<ipython-input-5-b70dc996c844> in test_lst(self)
     24             for m in total_errs_msg:
     25                 print(m)
---> 26             raise AssertionError("Test Failed")
     27
     28 test = TestA()

AssertionError: Test Failed

However, the desired output is to hide the traceback:
Index 1, Expected 2, Get 3
Index 3, Expected 4, Get 5
----------------------------------------------------
AssertionError: Test Failed

How can I hide the traceback in this case? Another post suggested to catch the exception by unittest_exception = sys.exc_info(), but here I don't want to immediately throw the exceptions but wait for all test cases to finish.
Any suggestion ?
Thanks

A: Try this way
from unittest import TestCase
import unittest

class TestA(TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_lst(self):
        a = [1, 2, 3, 4, 5]
        b = [1, 3, 3, 5, 5]
        for i in range(len(a)):
            with self.subTest(i=i):
                self.assertEqual(a[i], b[i])

if __name__ == '__main__':
    unittest.main()


text:
Q: Why is "wave behavior" of EM field not observed at small frequencies? In Feynman's lectures on Physics : Volume 1, there is a table in Chapter 2 : Basic Physics that lists various frequencies in the electromagnetic field and relates them to the observed behavior (in the far right column):

This suggests that even at significant frequencies of oscillation of charges, i.e., at 100 Hz, "field behavior" of the EM field is seen and that "wave behavior" is seen only after the frequencies reach $10^5$ Hz.
Is it not true that even a small frequency of oscillation of charge should set up a wave in the EM field and that "field behavior" is seen only when charges are absolutely stationary? Also, what exactly is meant by "field behavior"?

A: "Waves behavior" are the phenomena of interference and diffraction. For humans, this is noticeable when the wavelength is on the human scale: meters, maybe kilometers.
For sound this means frequencies higher than a few cycles per second. When it is slower, we call these variations just changes in the atmospheric pressure. In oceans, the tides are too slow to be treated as water waves. In electromagnetism, human scale corresponds to frequencies of 100 MHz (FM broadcast).
Really slow variations (AC power, the teacher waving a charged rod), are much better dealt with using quasistatic models where wavelength can be disregarded.

A: You should take the words "rough behavior" with a grain of salt, I mean is very rough. Fundamentally electromagnetism or radiation is a field theory. The full description is given by QED (quantum electrodynamics) so at any frequency, radiation IS described as a field, i.e. for the case of EM a 4-vector field $A_\mu$ which is defined at all times at every point in space, hence called a field. We identify its particle behavior as the excitation modes of this field. More specifically a field can be decomposed as a sum of modes (or waves if you wish) this modes are identified as particles depending on the context and energy scale, that was perhaps what Feynman was trying to convey with such table.
The short answer is then that the more localized the energy is, the closer you are to dealing with particle behavior, namely a defined trajectory and no interference/diffraction phenomena. An example of this is given by particle-like excitations such as solitons. Or the spontaneous emission of light from an atom as an example of localization and particle behavior.


text:
Q: Send MIDI data via port on MacOS to Digital Piano I would like to send midi data from my computer (running MacOS) via a port to my digital piano.
I want to be able to play a midi file, play certain notes for certain durations and potentially change instruments.
I have literally no idea on how to achieve this and cannot find any resources online.
Please provide code with your solution as it would help greatly.
I am using USB-to-Host, to send the data --> not sure if this means anything.

A: Not sure this qualifies as a decent stack overflow question. There's lots of resources on the internet about MIDI.
The search 'Python MIDI' brings up this repo python-midi.
If you read the README it seems it can do what you wish.

A: Manually with Garageband:

*

*Connect the digital piano to the computer(MacOS) and turn both on.

*Open the midi file with Garageband, which is usually available on MacOS devices.

*Then go to Gargageband->Preferences->'Audio/Midi'->'Output Device' dropdown

*If the Digital Piano is recognized by the computer, it should be listed in the dropdown.  Select it.

*Click the 'play' icon on Garageband.  The midi file should play with output comming from the digital piano.

Programatically with Mido:

*

*Connect the digital piano to the computer(MacOS) and turn both on.

*Install the mido python package
pip install mido

*Get the list of midi ports that mido recognizes:
python -c "import mido; print(mido.get_output_names())"
The output should be something like:
['Digital Keyboard', 'IAC Driver Bus 1']
In this example 'Digital Keyboard' is your keyboard.
Your actual keyboard probably has a different name.
NOTE: The 'IAC Driver Bus 1' is a standard MacOS midi output port.

*Update the following play-midi.py script by changing 'Digital Keyboard' to the name of your keyboard which mido displayed in #3. Update the *.mid file to the name of your *.mid file.
import mido

# This will list the available ports
print(mido.get_output_names())

# Open the midi link to your keyboard
outport = mido.open_output('Digital Keyboard')

# Open the mid file to be played
mid = mido.MidiFile('my_midi_file.mid', clip=True)

# Play the file out to your keyboard
for msg in mid.play():
    outport.send(msg)

*Run the script.  The sound should play out of your keyboard.

Mido Reference resources:
https://github.com/mido/mido
https://mido.readthedocs.io/en/latest/midi_files.html


text:
Q: Error overloading () operator in a C++ template class While creating a Matrix class for easy multidimensional access to an array, i stumbled upon a weird error: If creating more than one overload for the () operator, the Visual Studio C++ optimizer (2010 and 2012) crashes.
I managed to isolate the error. Putting this as the single code file in a project will make it crash:
template <class T>
class Foo
{
    T& Foo::operator() (int i)
    {
        return 0;
    }

    // C1001 - Commenting this second overload makes the compiler work correctly
    T& Foo::operator() (char c)
    {
        return 0;
    }
};

The original code had an overload with (int x, int y), and another with (Vector2 pos), but the error is the same.
Is there a workaround for this, or is it a VS bug I'll have to live with?

A: It is not allowed to use Foo:: inside your class scope when it is as a declarator-id. Try this :
template <class T>
class Foo
{
    T& operator() (int i)
    // ^
    {
        return 0;
    }

    T& operator() (char c)
    // ^
    {
        return 0;
    }
};

Also, returning 0 will not compile as you are trying to return a reference.
And finally, the operators are private in your example ;)

A: It's your illegal use of Foo::. Remove this, and the code compiles. It looks like VC++ knows it isn't valid, but cannot report a compilation error.
template <class T>
class Foo
{
    T& operator() (int i)
    {
        return 0;
    }

    T& operator() (char c)
    {
        return 0;
    }
};


text:
Q: Javascript Animation before/after countdown I want to add a countdown, that fades in when page is fully load, and after it hits 0 to fade out and be replaced with another text (fade in as well), I want to do it by myself but, can someone give me some indications? Thanks.

A: You can use Element.animate() to animate multiple properties and .onfinish to perform task when animation is finished.

let options = {
  opacity: [0, 1],
  color: ['transparent', 'green'],
  background: ['#fff', '#cb0']
};

let settings = {
  duration: 2000,
  iterations: 1,
  fill: 'forwards'
};

const div = document.querySelector('div');

div.animate(options, settings)
.onfinish = () => {
  for (const key in options) {
    options[key].reverse();
  }
  div.animate(options, settings)
  .onfinish = () => {
    delete options.background;
    for (const key in options) {
      options[key].reverse();
    }
    div.textContent = 'done';
    div.animate(options, settings);
  }
}
body {
  height: 95vh;
}
div {
  color: transparent;
  font-size: 24px;
  text-align: center;
  display: block;
  width: 95vw;
  height: 95vh;
  background: '#fff';
}

animating