Merge Insert Into TABLE with an PHP ARRAY and for loop

Question: i have an php array, coming from an database. This array i want to insert into a different db/table. Two fields (WEBINV_ID,HOSTNAME) are unique. I will update these table daily per script. If the entry exist, they must skip the insert and should use update. That's working very well. But if i run this in an php for loop, it will only insert or update the first entry of the array into the new table
I use
MERGE INTO TABLE ...

for that.
That is my input array:
[0] => Array
    (
        [CI_ID] => 39778
        [NODEALIAS] => rt-2
        [NODE] => 10.1.2.3
        [SERIALNUMBER] => 8374378584
        [VENDORNAME] => Cisco
        [STATUS] => active
    )

[1] => Array
    (
        [CI_ID] => 72909
        [NODEALIAS] => rt-1
        [NODE] => 10.1.1.3
        [SERIALNUMBER] => 1276731237
        [VENDORNAME] => Cisco
        [STATUS] => active
    )...

Here is my for loop where i try to insert or update all of my devices.
for ($i = 0; $i < count($router); $i++) {

    $sql = "MERGE INTO DEVICES USING ( SELECT "
            . "'" . $router[$i]['CI_ID'] . "' AS WEBINV_ID,"
            . "'" . $router[$i]['NODEALIAS'] . "' AS DEVICE_NAME,"
            . "'" . $router[$i]['NODE'] . "' AS NODE,"
            . "'" . $router[$i]['SERIALNUMBER'] . "' AS SERIALNUMBER,"
            . "'" . $router[$i]['VENDORNAME'] . "' AS VENDORNAME,"
            . "'" . $router[$i]['STATUS'] . "' AS STATUS,"
            . "CURRENT_TIMESTAMP AS DEVICE_INSERT FROM DUAL
    ) S ON ('" . $router[$i]['CI_ID'] . "' = S.WEBINV_ID
         OR '" . $router[$i]['NODEALIAS'] . "' = S.DEVICE_NAME)
    WHEN MATCHED THEN UPDATE SET STATUS = '" . $router[$i]['STATUS'] . "', DEVICE_UPDATE = CURRENT_TIMESTAMP
    WHEN NOT MATCHED THEN INSERT(WEBINV_ID,DEVICE_NAME,NODE,SERIALNUMBER,VENDORNAME,STATUS,DEVICE_INSERT)
    VALUES ('" . $router[$i]['CI_ID'] . "',"
            . "'" . $router[$i]['NODEALIAS'] . "',"
            . "'" . $router[$i]['NODE'] . "',"
            . "'" . $router[$i]['SERIALNUMBER'] . "',"
            . "'" . $router[$i]['VENDORNAME'] . "',"
            . "'" . $router[$i]['STATUS'] . "',"
            . "CURRENT_TIMESTAMP)";

    $stid = oci_parse($gnedb, $sql);
    oci_execute($stid);  // executes and commits
}

I've tried the same code with "oci_bind_by_name", but the result was the same, only the first entry was used from the array. Any idea?
Comment: The fact that one record was merged shows that the sql statement is correct. Add an echo $sql; statement just before the oci_execute statement. There might be something within the data that is causing the problem. An alternative - test if the statement was actually executed by placing the necessary oci error statement after the oci_execute.
Comment: Are you sure that array contains what you think it contains?
Answer: If you are using oci_bind_by_name I understand you use Oracle database.
Maybe you should do something like this:
$insert_query = "insert all ";
foreach($router as $record) {
  $fields = "";
  $values = "";
  foreach($record as $field => $value) {
    $fields .= $field . ($field != 'STATUS' ? ',' : ""); // this is only if in the array the last field is STATUS - if it is not you might try to figure out last column diferently or remove last ',' differently
    $values .= "'" . $value . "'" . ($field != 'STATUS' ? ',' : ""); // this is only if in the array the last field is STATUS - if it is not you might try to figure out last column diferently or remove last ',' differently
  }
  $insert_query .= " into devices (" . $fields . ") values (" . $values . ") ";
}

The above will create a query into $insert_query and you just need to send it to database.
The only additional thing you need to figure out is which fields should be quoted and which doesn't. I quoted all of them, since Oracle should be able to cast values correctly - but you need to double check that (I have no Oracle available to check it :) )
The SQL construction I use can be found here.
Answer: I've found a solution, i will add my working code only that this post is complete and i hope that helps other guys.
here is the code:
for ($i = 0; $i < count($router); $i++) {
    $query = "MERGE INTO CORE_INTERFACES USING dual ON "
      // The next row is the match criteria, like If "HOSTNAME" AND "IFINDEX" exist, Then Update else INSERT NEW HOSTNAMES!
      . "( HOSTNAME = '" . $hostname . "' AND IFINDEX = '" .    t trim($router_interface[0]) . "')"
      . "WHEN MATCHED THEN UPDATE SET "
      . "IFNAME = '" . trim($router_interface[1]) . "',IFTYPE = '" . trim(clean_iftype($router_interface[2])) . "',IFADMINSTATUS = '" . trim(clean_output($router_interface[3])) . "',"
      . "LAST_UPDATE = CURRENT_TIMESTAMP "
. "WHEN NOT MATCHED THEN INSERT ("
      . "IF_ID,HOSTNAME,IFINDEX,IFNAME,IFTYPE,IFADMINSTATUS,"
      . "FIRST_SEEN "
      . ") VALUES ("
      . " core_interfaces_seq.nextval, "
      . "'" . $hostname . "',"        //$HOSTNAME
      . "'" . trim($router_interface[0]) . "',"       //ifIndex
      . "'" . trim($router_interface[1]) . "',"       //ifName
      . "'" . trim(clean_iftype($router_interface[2])) . "',"         //ifType
      . "'" . trim(clean_output($router_interface[3])) . "',"         //ifAdminState
      . " CURRENT_TIMESTAMP )";
   $stid = oci_parse($gnedb, $sql);
}


How to compute the standard error of a simple yes/no survey?

Question: I surveyed 100 voters and found 53% voted for candidate A and 47% voted for candidate B.  I am trying to compute the t-statistic from first principles (testing the null hypothesis that the true result is $\theta = 0.42$).
How do I compute the standard error from my sample?
Comment: @Tilefish could be asking about the standard error of the number voting for A.  Could be asking for the standard error of the difference in votes or the difference in vote proportions. Could be asking about the standard error of the sample standard deviation, counting A votes as 1 and B votes as 0. We should not be guessing. Yes, OP probably means the most obvious thing but asking clear unambiguous questions is important, for several reasons
Comment: @lebel What formulas do you have that relate to this? - presumably you have notes and textbook. What [searches and reasearch](https://meta.stackexchange.com/help/how-to-ask) did you do and what did you find by doing them? See [help/on-topic] relating to homework-style questions and adjust your question appropriately
Comment: the *survey* doesn't have a [standard error](https://en.wikipedia.org/wiki/Standard_error). What statistic from the survey are you trying to compute the standard error of? There's several possibilities.
Comment: @Glen_b I mean what are the chances he's not asking about the mean (or the proportion of successful trials since this is bernoulli)
Comment: To help clarify, I've included my hypothesis-testing motivation.  My textbook (Wooldridge's _Introductory Economics_) says the _t_-statistic can be computed as (0.53 - 0.42) over the standard error, where standard error = standard deviation over square root of _n_ (or 10, in my case).
Answer: I'm kicking myself now because this is really basic stuff, but I'll leave it up because none of the other websites which helped me look as clean and ad-free as this one.  I'm trying to compute a $t$-statistic
$$t = \sqrt{n}(\bar{y}-\mu_0)/s=(\bar{y}-\mu_0)/se(\bar{y})$$
I couldn't quite put my finger on $se(\bar{y})$, the standard error, except that my Introductory Econometrics textbook (by Wooldridge) said $se(\bar{y}) = s / \sqrt{n}$.
The answer to calculating the standard deviation $s$ from the experiment is, of course:
$$s^2 = \frac{p(1-p)}{{n}}$$
In my case, $s = \sqrt{\frac{0.53(1-0.53)}{100}} = 0.0499$.  Hence a $t$-statistic of 2.204.
Comment: t=22 cannot be correct. It's way too large.
Comment: @amoeba Is there something wrong with my calc?  Or logic? Or understanding of basic statistics?
Comment: Well, how did you get 22?
Comment: It looks like a calculation error to me.
Comment: $s^2$ should not have a $\sqrt{}$ in it (I have removed it for you, since you are correct later on when you give a figure for $s$). Your final figure (the t-statistic) is not correct. You made a small calculation error in computing $\frac{0.53-0.42}{0.04991}$.
Comment: \[Additionally many people would use the null value for the proportion in the standard error (i.e. 0.42) and compute a $Z$ rather than a $t$ -- though this is not an error - just a slightly different version of the test ... e.g. see [here](http://sphweb.bumc.bu.edu/otlt/mph-modules/bs/sas/sas6-categoricaldata/SAS6-CategoricalData2.html) or [here](https://onlinecourses.science.psu.edu/statprogram/node/164) \]
Comment: @Glen_b That's $\frac{0.53 - 0.42}{0.04991}$ times $\sqrt{n}$, no?
Comment: No. You've already done the $\sqrt{n}$ in there.


What is causing Unknown field error in EntityFieldQuery API?

Question: I am attempting to use the entity-field-query API to see if any node of referee content type has custom field that equals x. I've looked at dozens of code examples and references. (Included below)
If it is relevant I am executing this code as a custom PHP action in Drupal rules.
My problem is when the code is executed I get the below error:
EntityFieldQueryException: Unknown field: field_referee_id in EntityFieldQuery->addFieldCon
dition() (line 817 of /home/scienceorg/public_html/includes/entity.inc).

(The field does exist on the referee content type.)
My code:
<?php
error_reporting(E_ALL);

$query = new EntityFieldQuery();
    $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'referee')
    ->fieldCondition('field_referee_id', 'value', '1', '=');
    $result = $query->execute();
?>

Further information: If I remove the field condition line from the above code it works perfectly. So the problems seems to be around finding the field_referee_id.
Code references and examples
EntityFieldQuery condition
https://www.drupal.org/node/1343708
Alternative answer:
If you don't know what is causing the above problem I will accept alternative methods of achieving the same outcome as the correct answer.
Comment: You could try running this efq in à custom module, to make sure that the efq itself is working (might be a rules problem) Also, wat type is that field? If its annentityreference field you will need to replace value with target_id.
Comment: I might have to go the custom module route if I can't work it out. The field type is Integer and the widget is marked as a text field. Is the column still "value" for integers?
Answer: The code above seems right only problem here might be the machine name of the field is not same as the one given in
->fieldCondition('field_referee_id', 'value', '1', '=');
or the field might be multivalued field, for multivalued field in place of '=' 'IN' should be used.
Comment: I've switched it to IN and still the same PHP error. I've copied the machine name directly from the content type fields page so that has to be right.

Do you know of any other methods for seeing if any nodes of a certain content have have a custom field value of x?
Comment: It works as it is written. You can query the field table directly for checking the value of the field and can get entity id out of that table having the referee_id and check for the bundle within the same query.
Comment: How would I go about that?
Comment: $query = db_select('field_data_field_referee_id'); $query->condition('field_referee_id_value', 1); $query->condition('bundle', 'referee'); $query->fields('field_data_field_referee_id', array('entity_id')); This query might help you.
Comment: When I do a var_dump($result) that code isn't showing me anything on the referee content types. Would you be able to explain what $query->fields('field_data_field_referee_id', array('entity_id'));  is doing differently to ->fieldCondition('field_referee_id', 'value', '1', '=');? (It doesn't look like it's comparing it with the value 1)


Facebook login button disabled on localhost

Question: I'm testing the sample Run with Friends Google App Engine Facebook app.  When running on localhost:8888, clicking the login button brings up a new small window, which disappears almost instantly, and doesn't actually log in.  How can I test logging into Facebook on localhost?  I saw this question, but the accepted answer doesn't seem applicable to Google App Engine.
Answer: I'm using a local Nginx instance in front of dev server. Nginx really easy to configure for proxying reguest from domain like mylocalapp.dev to your app.
Configuration looks like:
server {
    listen [::]:80; #it's for ipv6
    #listen 80; #for ipv4
    server_name mylocalapp.dev;

    location / {
            proxy_pass http://127.0.0.1:8080;
    }
}

And also, don't use suffix like .local for domain, it doesn't work for FB too.
Comment: Is mylocalapp.dev an actual domain that you can configure, or is it a fake domain?
Comment: fake domain, that you can configure in your `/etc/hosts` file
Comment: I'm developing on Windows, sorry I didn't mention that.  Is the code you posted the entire nginx.conf file?  What else do I have to configure on Windows?
Comment: On Windows the file is located in `system` directory (google for full path, I don't remember). My configuration example you have to append to existing `nginx.conf` (or use as a standalone file and include into main config)
Comment: It looks like it's `%SystemRoot%\system32\drivers\etc\hosts` on Windows.  Thanks, I'll try this out again now.
Comment: btw, i'm not sure that you should use ipv6 on Window. So try to use `listen 80` intead
Comment: Alright, I managed to get it working without resorting to Nginx.  Thanks for your help anyway, and I may use this later.


How do I get Facebook latest uploaded images for an account?

Question: I am new in Drupal, I want to get all the images from my Facebook account and want to display them into front end.
I tried Facebook Album Fetcher module but this module give me the facility to get images only for a particular album not for overall. I want to get and display only the latest uploaded images from my whole account (Images will be anywhere like profile images or timeline images or album images etc).
So can anyone please tell me, is there any module which can fill my above requirement? If not then how can i get all the latest uploaded images to display them into front end?
Please help.
Thanks in advance.
Answer: I have resolved this in two ways.

First I use Facebook FQL query to get the image of Facebook page posts image. You can find the code from here. Facebook Platform API versions after 2.0 will not support FQL. So I get the images using Facebook graph API.
Then I get Facebook post images using Facebook graph API. Here is my code: Firstly you should have to get page id from where you want to get post images. From here you can get the Facebook page id.

After that use the code:
$data = file_get_contents("https://graph.facebook.com/page_id/photos/uploaded");
$results = json_decode($data);
foreach ($results as $value) {
  echo 'source .'">';
}

Answer: According to this answer on SO (to a 'similar' question posted 'after' this question ...), there seems to be another (better?) solution to this issue. Below is (part of) what that answer says ...
= = = Start = = =
Firstly I got the page id where all the images uploaded. To get the Facebook page id just go through the below two link:
https://graph.facebook.com/
https://graph.facebook.com/testpage.
Here is my code by which i got all the images for testpage page:
<?php
include_once "facebook/facebook.php";
$facebook = new Facebook(array(
    'appId'     => 'YOUR_API',
    'secret'    => 'YOUR_API_SECRET',
    'cookie' => true
));
$accessToken = $facebook->getAccessToken();
$photoQuery = urlencode('SELECT pid,owner,src_small,src_big FROM photo WHERE aid IN (SELECT aid  FROM album  WHERE owner = "YOUR_PAGE_ID")');
$photoFQL = 'https://api.facebook.com/method/fql.query?query='.$photoQuery .'&access_token='.$accessToken.'&format=json';
$photoResults = file_get_contents($photoFQL);
$photo12 = json_decode($photoResults);
foreach ($photo12 as $value) {
    echo 'src_big .'">';
}
?>

= = = Stop = = =


php nao reconhece o comando mysqli_connect()

Question: estou executando um coigo via cmd e ele começou a apresentar esse erro
PHP Fatal error:  Uncaught Error: Call to undefined function mysqli_connect() in /opt/lampp/htdocs/php/futebol/crawler/php/crud/Conect.php:6
Stack trace:
0 /opt/lampp/htdocs/php/futebol/crawler/php/crud/Conect.php(13): conn('root', '', '127.0.0.1', 'futebol')
1 /opt/lampp/htdocs/php/futebol/crawler/autoload.php(3): require_once('/opt/lampp/htdo...')
2 /opt/lampp/htdocs/php/futebol/crawler/instatscout/Rastrear_metchs_tournament.php(7): autoload('php/crud/Conect...')
3 {main}
thrown in /opt/lampp/htdocs/php/futebol/crawler/php/crud/Conect.php on line 6
codigo
if (!function_exists('conn')) {
    function conn($usuario,$senha,$host,$bd)
    {

        $conn = mysqli_connect($host, $usuario, $senha, $bd);
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }
        return $conn;
    }
}
$conn = conn( "root",'',"127.0.0.1","futebol");

Answer: Se instalou o lamp baixando do site Xampp então é só ir no php.ini e descomentar a linha:
;extension=mysqli.so

Para (remove o ;):
 extension=mysqli.so

Se for php7 provavelmente pode estar assim:
;extension=mysqli

Para (remove o ;):
 extension=mysqli

Salve a edição, após salvar o php.ini reiniciei o lamp:
sudo /opt/lampp/lampp stop
sudo /opt/lampp/lampp start

Eu não lembro se tem um restart a muito tempo não uso xampp, só uso o que vem pelo repositório, mas você pode experimentar:
sudo /opt/lampp/lampp restart

Só pra constar, o Xampp se eu não me engano tem um painel que dá pra reiniciar o Apache, mysql e outros por ele mesmo, sem precisar de comandos.
Comment: Sim o xampp tem o xampp control panel para abrir o painel, cujo nome do ficheiro não me lembro mas fica na mesma pasta da instalação. De qualquer forma também da para iniciar por comando com ./xampp start ou até indicando o que pretende iniciar com ./xampp startapache


Variance of precision in conjugate prior

Question: How can I calculate the variance of the precision in a normal distribution, knowing I used a conjugate prior?
Answer: The conjugate prior for the precision of a normal distribution is a Gamma distribution.  If you use this, the posterior will be a Gamma distribution.  Then you apply the known formula for the variance of a Gamma distribution (on the linked page) to get the variance of the posterior.


Avoid no-shadow eslint error with mapDispatchToProps

Question: I have the following component that triggers a no-shadow ESlint error on the FilterButton props.
import { setFilter } from '../actions/filter';

function FilterButton({ setFilter }) {
  return (
    <button onClick={setFilter}>Click</button>
  );
}

export default connect(null, { setFilter })(FilterButton);

How can I avoid the warning while keeping both the concise syntax of mapDispatchToProps and the ESlint rule?
I know I can add a comment to suppress the warning but doing it for every components seems redundant and tedious.
Comment: Can't you just reassign when passing it in to the function on the export line? So, `export default connect(null, {filter: setFilter})(FilterButton);` and then above that just `function FilterButton ({filter}) {` (or whatever new variable name you prefer). This way you're not shadowing the variable in the upper scope, and that's clear when looking at the code.
Comment: You can rename `setFilter` (`FilterButton({ setFilter })` to `FilterButton({ setFilter })`). It makes sense (sort of) because the functions that's in `FilterButton`'s props is actually the original `setFilter` with the `dispatch` function bound to it.
Comment: Before and after rename are the same.
Comment: I meant renaming only in `function FilterButton({ setFilter }) {` and `Click`. Can you update your question with the edited code?
Comment: I can't rename it in `function FilterButton({ setFilter })` because it has to match the name of the prop which is `setFilter` actually.
Comment: In this case I'd lose the ES6's concise syntax..
Comment: Would be great if there was a forked eslint plugin that disabled no-shadow just for this particular use-case. I like no-shadow in principle but this code is much nicer than the alternatives.
Comment: A similar problem (with similar solutions) exists for `mapStateToProps` when using `createStructuredSelector` from [reselect](https://github.com/reduxjs/reselect) with identical names for props and selectors. Example: `connect(createStructuredSelector({ filter }), null)(Component)`
Answer: There are four options here:
1. Disable the rule.
Why?
It's the easiest way to avoid the ESLint error.
Why Not?
The no-shadow rule helps to prevent a very common bug when using react-redux. That is, attempting to invoke the raw, unconnected action (which does not automatically get dispatched).
In other words, if you were not using destructuring and grabbing the action from props, setFilter() would not dispatch the action (because you'd be invoking the imported action directly, as opposed to invoking the connected action through props via props.setFilter(), which react-redux automatically dispatches for you).
By cleaning up variable shadowing, you and/or your IDE are more likely to pick up on the error.
How?
Adding a eslintConfig property to your package.json file is one way to do this.
"eslintConfig": {
    "rules": {
      "no-shadow": "off",
    }
  }

2. Reassign the variable when passing it into connect().
Why?
You benefit from the safety of the no-shadow rule, and, if you choose to adhere to a naming convention, it's very explicit.
Why Not?
It introduces boilerplate.
If you do not use a naming convention, you now have to come up with alternate names (that still make sense) for every action. And chances are that the same actions will be named differently across components, making it harder to become familiar with the actions themselves.
If you do use a naming convention, names become long and repetitive.
How?
Without naming convention:
import { setFilter } from '../actions/filter';

function FilterButton({ filter }) {
  return (
    <button onClick={filter}>Click</button>
  );
}

export default connect(null, { filter: setFilter })(FilterButton);

With naming convention:
import { setFilter, clearFilter } from '../actions/filter';

function FilterButton({ setFilterConnect, clearFilterConnect }) {
  return (
    <button onClick={setFilterConnect} onBlur={clearFilterConnect}>Click</button>
  );
}

export default connect(null, {
  setFilterConnect: setFilter,
  clearFilterConnect: clearFilter,
})(FilterButton);

3. Don't destructure actions off of props.
Why?
By explicitly using the method off of the props object, you don't need to worry about shadowing to begin with.
Why Not?
Prepending all of your actions with props/this.props is repetitive (and inconsistent if you're destructuring all of your other non-action props).
How?
import { setFilter } from '../actions/filter';

function FilterButton(props) {
  return (
    <button onClick={props.setFilter}>Click</button>
  );
}

export default connect(null, { setFilter })(FilterButton);

4. Import the entire module.
Why?
It's concise.
Why Not?
Other developers (or your future self) may have trouble understanding what's going on. And depending on the style guide you're following, you might be breaking the no-wildcard-imports rule.
How?
If you're simply passing in action creators from one module:
import * as actions from '../actions/filter';

function FilterButton({ setFilter }) {
  return (
    <button onClick={setFilter}>Click</button>
  );
}

export default connect(null, actions)(FilterButton);

If you're passing in multiple modules, use object destructuring with rest syntax:
import * as filterActions from '../actions/filter';
import * as otherActions from '../actions/other';

// all exported actions from the two imported files are now available as props
function FilterButton({ setFilter, clearFilter, setOther, clearOther }) {
  return (
    <button onClick={setFilter}>Click</button>
  );
}

export default connect(null, { ...filterActions, ...otherActions })(FilterButton);

And since you mentioned a preference for ES6's concise syntax in the comments, might as well throw in the arrow function with an implicit return:
import * as actions from '../actions/filter';

const FilterButton = ({ setFilter }) => <button onClick={setFilter}>Click</button>;

export default connect(null, actions)(FilterButton);

Comment: Very well written answer. Although, one should stop reading after `Disable the rule` :)
Comment: How exactly does `no-shadow` help prevent invoking the raw action? It throws an error when you get it right (assuming destructured props) and does NOT when you call the raw action. The answer by @GollyJer is a great addition and should be appended to this answer's first part. It is very likely to be the best practice, all things considered.
Comment: I'm using the #2 Reassign the variable when passing it into connect().
I'm adding an Action suffix (i.e., setFilter is setFilterAction).

Thank you for other options and your insights to each of them.
Comment: Thank you! This should be the accepted answer for sure.
Comment: As a convention, I'm tempted to just prepend `$` to the names of the actions and use the mapDispatchToProps shorthand, but I've always found `$` a little jarring, even with jQuery.
Comment: #3 makes even more sense for class-style components, because the props are already given to you in a namespace. The shadowing happens after you *intentionally remove it*.
Comment: #3: An addition to "Why not?": It violates [react/destructuring-assignment](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/destructuring-assignment.md).
Comment: This is the type of answer that makes SO the exceptional resource that it is.
Comment: IMHO #3 can be improved with [react/jsx-handler-names](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md) `onClick={onFilter}` (and maybe something like `connect(null, { onFilter: (ev) => setFilter() })` to make it explicit `onFilter` takes an event as an argument, but `setFilter` shouldn't, but that sounds like too much overthinking)
Comment: I have used rule #2 with a suffix of "_" for the prop, which is concise and clear. Thanks so much for your well thought out and written answer.
Comment: #2 I think I will use this convetion: `connect(null, { setFilter: setFilter_ })(FilterButton)` and rename actions on import. I have many components written and it will be easiest way to fix this error for me (except disabling the rule)
Answer: A fifth option:
5. Allow a specific exception via eslintrc rules.
module.exports = {
  rules: {
    'no-shadow': [
      'error',
      {
        allow: ['setFilter'],
      },
    ],
  }
}

Why?
You don't want variable shadowing but can't get around it in certain cases.
Why Not?
You really don't want variable shadowing in your code base.
Comment: I like this option, but it is not working for me
I still see the error
Answer: Option number six.
6. Disable the es-lint rule for the specific line(s) of code
import { setFilter } from '../actions/filter';

// eslint-disable-next-line no-shadow
function FilterButton({ setFilter }) {
  return (
    <button onClick={setFilter}>Click</button>
  );
}

export default connect(null, { setFilter })(FilterButton);

or
import { setFilter } from '../actions/filter';

/* eslint-disable no-shadow */
function FilterButton({ setFilter }) {
/* es-lint-enable */
  return (
    <button onClick={setFilter}>Click</button>
  );
}

export default connect(null, { setFilter })(FilterButton);

The second way to temporarily disable the es-lint rule can be used for multiple lines of code, unlike the first one. It can be useful if you pass more arguments and divide them into multiple lines of code.
Why?
This is an easy and suitable option for some use-cases (for example, your team/organization uses specific es-lint settings and it is discouraged/forbidden to modify those settings).
It disables the es-lint error in the line(s) of code but does not influence on mapDispatchToProps syntax and the rule is still completely active outside the line(s) of code.
Why not?
You do not want or you are forbidden to bloat your code with such kind of comments.
You do not want or you are forbidden to influence es-lint behaviour.
Answer: I tweaked 4. and achieved what I would like to call option 8.
8. Import methods under a different name
Why?
It has the same benefits as importing the entire module but without conflicting with other rules, e.g. Do not use wildcard imports(airbnb).
Why not?
It's adding an unnecessary variable declaration that might cause confusion.
How?
For the single method case
import { setFilter as setFilterConnect } from '../actions/filter';

function FilterButton({ setFilter }) {
  return <button onClick={setFilter}>Click</button>;
}

export default connect(
  null,
  { setFilter: setFilterConnect }
)(FilterButton);

Answer: With the new Hooks API added in v7.1.0, you can get rid of the variable and mapDispatchToProps  altogether:
import { useDispatch } from 'react-redux'
import { setFilter } from '../actions/filter';

function FilterButton() {
  const dispatch = useDispatch()
  return (
    <button onClick={() => dispatch(setFilter())}>Click</button>
  );
}

export default FilterButton;

Answer: Option 7...
7. Use container components
Why?
It's a known pattern and you get the added benefit of decoupling your components from the redux store, making them easier to be reused.
Why not?
You now need two files per component.
How?
// FilterButton.jsx

export default function FilterButton({ setFilter }) {
  return (
    <button onClick={setFilter}>Click</button>
  );
}

// FilterButtonRedux.jsx

import FilterButton from './FilterButton';
import { setFilter } from '../actions/filter';

export default connect(null, { setFilter })(FilterButton);

Comment: Another point to "why not": it's now possible to import a component with a very similar name to the intended one that is not connected to redux.
Comment: @tao_oat put these files inside a `FilterButton/` directory with an `index.js` exporting only the connected component. It makes for a clear public API, and it's then easier to unit test the isolated unconnected component, e.g. inside `FilterButton/FilterButton.test.jsx`
Comment: This works well for simple components (Yes, I hear you all that all of the components _should_ be simple). For more complex components (= more props) you will get a lot of repetition in prop types


$10$-sheeted covering of $S^1 \times S^2$

Question: Does there exists a $10$-sheeted covering of $S^1 \times S^2$.
I think so, the Galois Correspondence for covering map show that there is a covering space with fundamental group $10 \mathbb{Z}$ and this is actually an index $10$ subgroup,  so I can conclude that such a $10$ sheeted covering space exists.
Is it sufficent?
Answer: That's a correct argument, but such a cover is also not hard to describe explicitly. If $p \colon S^1 \to S^1$ is a $10$-sheeted cover, then so is $(p \times \mathrm{id}) \colon S^1 \times S^2 \to S^1 \times S^2$.


Next.js custom error component doesn't show

Question: I'm having problem with Next.js custom error component.
I followed documentation and made 404.js component in my /pages but it looks like it isn't recognized, it still shows me default error page. Thanks for anyone who opened this question anyway!
export default function Custom404() { return
404 - Page Not Found
 }

Comment: Please [show the code](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: export default function Custom404() {
  return 404 - Page Not Found
}

pages/404.js
Comment: which nextjs version are you using?
Comment: version is 13.5.4
Answer: Custom error page is available for Next.js 9.3 and afterward, so maybe you are using an older version which has not supported yet
Comment: version is 13.5.4
Comment: are you using app router or page router?
Comment: im using page router
Comment: @FreedomFighter Maybe you have `cache` problem (delete your .next folder and try to build again)
Comment: Did that already :/
Comment: Can you show the `next.config.js` file?
Comment: /** @type {import('next').NextConfig} */
const nextConfig = {}

module.exports = nextConfig


Sanity draft preview not working with block content

Question: I've made two iterations of a blog creation experience. The first consisted of an array of different object and document types such as paragraph, gallery, quote, etc while the second, and most recent one, takes advantage of block content to streamline the process. However, I can't get a draft preview using block content to work while it works just fine with the array of components.
Here is the template used for the draft preview:
import React from 'react';
import BlockContent from '@sanity/block-content-to-react';

export default ({ pageContext, location }) => {
  const { blogPost = {} } = pageContext;

  return (
    <React.Fragment>
      <BlockContent blocks={blogPost.content} serializers={serializers} />
    </React.Fragment>
  );
};

const serializers = {
  types: {
    block(props) {
      const { style = 'normal' } = props.node;

      if (/^h\d/.test(style)) {
        let className = '';
        const level = style.replace(/[^\d]/g, '');
        switch (level) {
          case '1':
            className = 'domaine--medium-large mt1 mb2';
            break;
          case '2':
            className = 'sans--large mt2 mb1';
            break;
        }

        return (

              {React.createElement(style, { className }, props.children)}

        );
      }

      return (

            {React.createElement(
              style,
              { className: 'sans--medium color--gray-text db mb1 mt1' },
              props.children,
            )}

      );
    },
  },
};

And then the setup for the blog content in Sanity:
import React from 'react';

/**
 * Defines the structure of a blog post.
 */
export default {
    name: 'blogPost',
    title: 'Blog Post',
    type: 'document',
    fields: [
        {
            name: 'content',
            title: 'Blog Content',
            type: 'blogPortableText'
        },
    ],
};

Now if I go to create a new blog post and populate the Blog Content with anything and press on draft preview, It shows the template from the front end but without the content and in the inspector I get Warning: Failed prop type: The prop blocks is marked as required in SanityBlockContent, but its value is undefined. which is because the block content isn't being passed to the template. Now if I replace the block content with anything else such as just a text component the preview works fine and it seems the problem is just the block content.
Comment: You question description lacks detail. How is your `Preview` component connected with `blogPost` schema? I skim through the doc and from my understanding at least the `preview` property should present in the schema, am I right?
Comment: The `sanity` framework looks quite neat, but it's quite far away from being a popular framework. I for one hear of it for the first time. So it'd be a lot easier if you can provide a code repo to show case your problem, with minimal setup, so people can `npm install` and `npm start` and start diagnosing. Currently I can only guess.
Comment: Can you somehow reproduce this issue on http://codesandbox.io? @Mr.Smithyy
Answer: @hackape is definitely asking a question I'd like the answer to as well. How is the pageContext being supplied?
One thing I'm seeing is the it looks like in your destructuring of pageContext, blogPost might not be defined and you're providing a default value of an empty object.
This would mean that blogPost.content would be undefined which explains your error.
You could provide a better default value such as { content: '' } or you could choose to not render the <BlockContent /> until you have a content value:
const { blogPost = { content: '' } } = pageContext

if (blogPost.content !== undefined) {
    return <BlockContent blocks={blogPost.content} serializers={serializers} />
}

return null

Comment: Sorry that this isn't actually a complete answer to your question. It's just that there's a character limit on the comments...

If you provide further details, I'll work on editing my answer to help provide a more thorough solution


Exchange authorizational code works only once - Oauth2.0

Question: I'm trying to implement this code. https://developers.google.com/drive/web/credentials#retrieve_oauth_20_credentials
I have my client id and client_secrets json for webapps, because I'm extracting some values from a spreadsheet, everything is ok and I already have spreadsheet's data in my application. But my question is How can I make to re-use that authorization code multiple times?, because I have to extract more data from that spreadsheet, my URL is http://localhost:8080/cluster/?state=/profile&code=xxxxxxx but for example when I try to refresh that page this error appears.
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Code was already redeemed."
}
I have the same implementation of the url, but the only difference is I changed this methods storeCredentials(userId, credentials) - getStoredCredentials(userId) and put that values into a db table.
So, How can I implement 'exchange authorization code'? and how can I link my application to the new url?
Thanks for your help! :D
Answer: First at all, following the protocol the authorization code MUST BE used once, so the auth server must invalidate it after the first use.
If you want to use it for another part of your implementation, you can save it, use it and send a 302 redirect to your other page witch use your getStoredCredentials method
Comment: For the moment I don't need a redirect, because I need to extract the same information for the same page like 'refresh page' but if I do that I got a 'Code was already redeemed'. I already stored the userId, accessToken and refreshToken, but I don't know how to use it to re-send it to exchangeCode method. :\


Executo a consulta PHP mas ela não exibe resultado da soma no MySQL

Question: Estou com dificuldades de exibir a seguinte soma.
require_once("config_acesso.php");

$consultar = "SELECT SUM('valor') FROM vendascalc WHERE valor";
$resulta = mysqli_query($mysqli,$consultar);

echo "Total a pagar: " . $resulta;

Não obtenho nenhum resultado. Porém no phpMyAdmin o resultado flui tranquilo.
Comment: $consultar = "SELECT SUM('valor') FROM vendascalc WHERE valor"; ...valor o que?
Comment: http://php.net/manual/en/mysqli-result.fetch-row.php
Comment: Não dá erro algum?
Answer: Primeiro acerte a consulta, remova as aspas simples da coluna valor, defina um alias para o campo calculado dessa forma fica mais legível para recuperar os valores no php, caso não seja especificado nenhum apelido, o php assumirá que 'nome' é a expressão utilizada, no caso sum(valor) ou 0(zero) se utilizar mysqli_fetch_array()
$consultar = "SELECT SUM('valor') FROM vendascalc WHERE valor";

Mude para:
$consultar = "SELECT SUM(valor) as total FROM vendascalc WHERE valor";

Depois do mysqli_query() recupere o valor da consulta com mysqli_fetch_assoc() e faça uma laço para obter todas as linhas retornadas pela consulta.
$resulta = mysqli_query($mysqli, $consultar);

while($item = mysqli_fetch_assoc($resulta)){
   echo $item['total'] .'
';
}

Comment: `WHERE valor` retorna as linhas onde `valor` não for `NULL`, `0` ou `''`; é válido e talvez seja a intenção.
Comment: @bfavaretto, hehe não conhecia essa sintaxe, parece ser melhor que usar `where valor is not null or valor <> ''` e afins vou alterar a resposta, \o valeu pela explicação.
Answer: Sua query está errada, você precisa ter um valor depois de WHERE:
SELECT SUM('valor') FROM vendascalc WHERE valor = <algum numero>

Comment: Eventualmente, o guia [answer] pode alguma dica de por que alguém votou negativo.
Comment: Obrigado @perdeu, foi na mosca sua dica. Valeu.


Picking the first group of regex map as a new column

Question: I have a dataframe 'df', with many column, I am trying to extract the ZIP code from the column called "ADDRESS" and create a new columns called "ZIP" and "ZIP1"
Now I am accounting for two possibility (may expand to more later), where ZIP is a continuous six digit number(non US) and ZIP is split by a '-'
I am using the following script to do this:
df['ZIP'] = df['ADDRESS'].str.extract('\d\d\d\d\d\d')
df['ZIP1']= df['ADDRESS'].str.extract('\d\d\d-\d\d\d')

But I get the following error:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/strings.py", line 1393, in extract
    result, name = str_extract(self._data, pat, flags=flags)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/strings.py", line 477, in str_extract
    raise ValueError("This pattern contains no groups to capture.")
ValueError: This pattern contains no groups to capture.

I understand that this is because the Address may have other numbers, thus regex leads to multiple matches, is there a way I have specify which group to select and insert in the new columns called 'ZIP'

CODE NEEDS MODIFICATION
import re
a="results_item12345"
pattern=re.compile(r"(\D+)(\d+)")
x=pattern.match(a).groups()
print x[1]

The code if its is modified for a data frame, then thats exactly what I am looking for
P.S: Using Mac and Python 3.5
Thanks in advance
Comment: Fixed it! Thanks for pointing it out, no impact on the code though
Comment: Do you really need `.str` in `df['ADDRESS'].str`? because `df['ADDRESS']` seems to be the string
Comment: FYI, `\d\d\d\d\d\d` can be written as `\d{6}` and same for other `\d{3}-\d{3}`
Comment: Not sure, I am pretty new to Python, I picked this in one of the guides
Comment: @Tushar Thanks for this, no your FYI, just made the code more readable
Comment: I got the following warning: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead, it worked!
Comment: @user3875610: Please post your solution if it worked.
Answer: The following the solution that worked for me, although it gave me some warning, hope this helps. Basically it does not solve the 'group' problem but so far this is the best I have
#******************************************************************************************#
#*                        IMPORTING THE NECESSARY LIBRARIES                               *#
#******************************************************************************************#

import pandas as pd
import re
#******************************************************************************************#
#*                         IMPORTING THE .CSV                               *#
#******************************************************************************************#

print (" \n Importing the .csv from folder \n")

df_input = pd.read_csv('/Users/one/input.csv',
    encoding = "ISO-8859-1")

#******************************************************************************************#
#*        CREATING A REGEX TO GET THE PIN CODE FROM THE ADDRESS COLUMN                    *#
#******************************************************************************************#

# Any continous six digit number
df_input['ZIP'] = df_input['ADDRESS'].str.extract(r'(\d{6})')

# Any six digit number separated by space
df_input['ZIP1'] = df_input['ADDRESS'].str.extract(r'(\d{3}\s\d{3})')

#******************************************************************************************#
#*        EXPORTING TO THE LOCAL DRIVE                                  *#
#******************************************************************************************#
# Output
df_input.to_csv('/Users/one/output/df_mapped.csv', sep=',', index=False)


Distributions of peaks on $S_n$

Question:
I'm ultimately trying to compute the second moment of $X$, or $E[X^2]$. I don't see another way to do this other than to determine the probability distribution $P(X = k)$.
It seems to me that for each $U_i$ and its neighbors, it can take on $4$ positions being $1)\cdot ^{\cdot} \cdot$ $2) ^\cdot . ^\cdot$ $3) ^\cdot \cdot .$ and $4) .\cdot ^\cdot$. Basically peak, valley, middle decreasing and middle increasing. Therefore I think that $p(U_i \space is \space peak) = \frac14$. It is therefore my reasoning that $X$ is binomially distributed with parameter $p = \frac14$ of success, but I feel that there is something wrong as you can have at most $\frac{n}2$ peaks.
Can someone either point out my mistake, or point out a better way to calculate variance? Thank you
Answer: I think there are actually 6 positions.  In your nomenclature of High (H), Medium (M), and Low (L), there are 3! = 6 ways of permuting the letters $H$, $M$ and $L$.  Arguing by symmetry, the probability that $U_i$ is a peak is 1/3 since there's an equal chance that $U_{i-1}$, $U_{i}$, or $U_{i+1}$ is the largest of the 3.
Also, it's not binomially distributed with $p=1/3$ either since whether $U_i$ is a peak or not is not independent of $U_{i-1}$ and $U_{i+1}$.  Conditioning on $U_{i-1}$ and $U_{i+1}$ large, the probability that $U_{i}$ is a peak is much less than 1/3.
As you suspected, you do not have to actually compute the distribution of $X$ to find $\mathbb{E}[X^2]$.  Instead, you can exploit the linearity of expectation to bypass all the joint distribution intricacies.  Write $X = \sum_{i=1}^N \mathbf{1}_i$ where $\mathbf{1}_i$ indicates whether $U_i$ is a peak or not.  Then expanding, you end up having to compute terms like  $\mathbb{E}[\mathbf{1}_i\mathbf{1}_j]$.
Comment: So can I possibly condition on every other $U_i$ then at the end multiply by $2$ as to account for conditioning on the random variables of opposite parity?
Comment: Hm...possibly, although that still sounds complicated.  Also, what if $N$ is odd? (I updated my answer a bit.)
Comment: I actually just saw the edit. Thanks!

Distributions of peaks on $S_n$


Dreamy musical phenomenon

Question: It happens mainly when I am relaxed, about to sleep or near to wake up, but it also happens other times but less often, generally on quiet environments, then I start to listen a music on my head, most of the times it is a song I know, but it also happens to listen a unknown melody, maybe it is a composition of several songs I have listened before mixed together within something pleasurable but new for me.
The song is played so sharp it seems to be going from my ears, the bass are so loud it shivers my body, and it seems I have no control about what is being played, sometimes it is played different songs one after another.
When it have vocals I listen the original singer voice, even on songs I have never memorized the lyrics, and I also happen to listen some Japanese songs out of this state, and sometimes this phenomenon happens to play Japanese music that I would never be able to sing, but not only the melody but also the lyrics seems to be correct on the original idiom.
I want to know if there are more people had already gone through this phenomenon and if it has name?
Comment: It sounds like you have a good memory for music. I often listen to music in my head; it is a reason for disliking piped music in supermarkets.
Comment: I think I have something similar, but the most I could come up with it was EHS, since most of the time it's not really music, it's more like a loud static and pressure, but sometimes it evolves into music.
Answer: Yeah, this is actually a real thing (nothing to worry about) that a lot of people experience. Its called a Musical hallucination (oOh.) Its basically where you randomly remember bits and parts of a song or tune, and your brain starts playing them like they're actually there. They are a specific kind of Auditory Hallucinations, where people hear the noise as if it were happening right there in front of them. People have been known to even "hear" people talking to them from previous conversations, and they respond, just talking to themselves. Musical hallucinations aren't really anything to be worried about, but if it starts getting worse, that could be a sign of tinnitus or paracusia. All of these conditions are still being studied because they are so complex and interesting.

Dreamy musical phenomenon


Electronic keyboard terms: Aftertouch vs Pressure-sensitive

Question: I was reading a review of the Akai Miniak which said

The 37 half-weighted keys are velocity and aftertouch but not pressure sensitive.

I thought aftertouch was MIDI signals of continuing pressure levels on a keyboard-key after the initial striking of the key?
I understand this is usually per-keyboard (max over all keys held down) rather than per-key.
Can someone explain the difference between "aftertouch" and "pressure-sensitive" in the review phrase? How can you have aftertouch without pressure-sensitivity?

Edit:
The way I read it, the reviewer mentions three distinct attributes of the keyboard

Velocity (sensitive) and
Aftertouch (sensitive) but not
Pressure sensitive

However, from Alex's answer and other subsequent research about MIDI messages, It seems that one of these three attributes must be just an alternative name for one of the others.
The Akai web page says it is velocity sensitive but makes no mention of aftertouch (or of pressure-sensitive).
So is this just an error in the review?

Edit2
The Miniak manual says

Modulation sources
  -  Aftertch: Polyphonic (per-note) Aftertouch, MIDI only
  -  Pressure: Monophonic (per-MIDI Channel) Aftertouch, MIDI only

So I guess the Miniak's keyboard is Velocity-sensitive (AKA pressure of initial impact) but does not have Aftertouch (sometimes AKA pressure-sensitivity post impact) but that you can plug into it's MIDI-In port an expensive MIDI keyboard controller that does has Aftertouch and the miniak's synth engine can use it.
I conclude the reviewer made a poor job of expressing this.
Comment: I would have assumed aftertouch and pressure meant the same thing.
Comment: Yes, the reviewer was not using the terms correctly. After-touch and pressure-sensitivity are the same thing.
Answer: I know this is an old question but I think I can clear up the confusion here:
Two Entities: Keyboard and Sound Engine
You have to distinguish between two things:
1) The capability of a (here: Miniak's) keyboard to react to key velocity and pressure (aka Aftertouch) and generate internal modulation sources and MIDI messages from these.
2) The capability of the Miniak's sound engine to be modulated by the velocity in note on/off messages and Aftertouch messages received by either MIDI or from its own keyboard.
Definitions

Velocity is the speed with which a key is pressed down (note-on velocity) or with which the finger is lifted (note-off velocity). In the MIDI protocol this is expressed as the second data byte to note-on/off messages.
Aftertouch comes in two flavours:

monophonic aka Mono Pressure: applies globally to all notes played at the same time with the same amount. In the MIDI protocol this is expressed as the status byte 0xDn with one data byte (the amount).
polyphonic aka Poly Pressure: can be applied to each individual note.  In the MIDI protocol this is expressed as the status byte 0xAn with two data bytes (the note number and the amount).

Keyboard
The Miniak's keyboard generates:

note-on velocity and
note-off velocity (not many keyboards do!)

... but does not generate mono- or polyphonic Aftertouch. Polyphonic Aftertouch is generated by very few of all keyboard models ever produced.
Sound Engine
The Miniak's sound engine can use all of these as modulation sources:

note-on velocity
note-off velocity (called VelociUp in the list of modulation sources)
mono pressure (called Pressure in the list of modulation sources)
poly pressure (called Aftertch in the list of modulation sources)

Mono and poly pressure will originate from incoming MIDI messages (or the second modwheel, see below), since, as stated above, the keyboard does not generate these.
Additional notes

The second modwheel of the Miniak generates mono pressure messages (internally and over MIDI) and any modulation whose amount is controlled by the second modwheel will also be controlled by incoming mono pressure MIDI messages.
@Alex Coplan - pressure sensitivity certainly does not mean velocity sensitivity, this usage is just plain wrong.
I also disagree with the notion that Aftertouch isn't very useful. It is elemental if you want to play expressive lead lines with just one hand without having to use a second hand for the modwheel.
Comment: Usually, when somebody says just "Aftertouch", without qualification, they mean "Mono Pressure", and that's what I meant in my last note as well. Most good Masterkeyboards and many top-level keyboards generate Mono Pressure. Like I said, only very few keyboards generate Poly Pressure, but quite a few synths can react to incoming Poly Pressure MIDI data. So Poly Pressure can be useful as well but you don't expect to find it often in keyboards. Though the recent emergence of new types of MIDI controllers (iPad, Eigenharp, DIY projects, etc.) may change things...
Comment: Yes, that's what I would expect. I have yet to come accross a keyboard that actually generates poly aftertouch, though. Here's a (prob. incomplete) list of keyboard models I know of, which can generate poly aftertouch. I haven't used any of these myself. VAX77; Kurzweil: MIDIBoard; Roland: A80/50; Ensoniq: SQ-80, VFX(-SD), ASR-10, TS-10; Sequential Circuits: Prophet-T8; Yamaha: DX1; SynthAxe; GEM: S Series workstations; Elka: MK88 Master Controller
Comment: Thanks for this, Chris. So you disagree that "aftertouch isn't very useful" but... how COMMON is it? I mean, how much expectation is there that I will offer poly-pressure on a keyboard MIDI controller? It seems like the answer is "none at all." Right? Thanks!
Comment: Thanks for responding, Chris. How do you expect Poly Pressure to be generated from the keys on a keyboard? As the user applies different amounts of pressure after the initial strike, there are poly pressure messages being sent out with each change in pressure?
Answer: Aftertouch is when you have played a note, you're holding it, and then you vary the pressure whilst holding it (effectively bending the key).
Pressure-sensitive Velocity Sensitive is when the keyboard will record a different MIDI velocity depending on how hard you initially hit the key.
Apparently pressure sensitivity, is the force with which the note is held down after the initial impact. - Although presure sensitivity is loosely associated with velocity sensitivity.
See this wiki article.
Comment: The article said "**velocity** and aftertouch **but not pressure sensitive**" - If "pressure-sensitive" = midi-velocity how can it be veolicity sensitive but not pressure sensitive? I'm still confused
Comment: @RedGrittyBrick just looked it up on wikipedia - many people will loosely called velocity sensitivity pressure sensitivity... including myself - I thought they were one and the same, but [obviously not](http://en.wikipedia.org/wiki/Keyboard_expression#Velocity_sensitivity)... I'm pretty sure aftertouch is what I said it is though
Comment: Thanks Alex, so is the reviewer writing nonsense when they list three things rather than two? Perhaps it is an editing error or something?
Comment: @RedGrittyBrick - I think that they didn't need to mention that it didn't have "pressure sensitivity" - you only really need velocity sensitivity, aftertouch is nice but not hugely useful


Rental Problem between tenants

Question: Okay, first of all, I'm writing this while I am battling a major cold so please don't laugh if the Answer jumps out at you.
Let's call this the rental problem.
Both Mark and Pat rent a place together, they each submit $\$775.00$ for the damage deposit for a total of $\$1550.00$.
Mark decides to leave early and break the rental agreement, he suggests that Pat Gives him  $\$775.00$ and simply recovers the $\$1550.00$ from the landlord at the end of the lease (assuming Pat decided to live at the same place but with no roommate). One month after Mark leaves, Pat also decides to break the lease which means he must forfeit the whole $\$1550.00$ from the damage deposit account (per the bylaws) In this case, Is Pat out only $ \$1550$ or $\$1550+\$775$ for a total of $\$2325.00$ ?
Thanks in advance :)
Answer: Pat initially paid the landlord $\$775$ for his half of the damage deposit.  After paying Mark $\$775$, Pat owns the whole damage deposit of $\$1550$.
If he doesn't get anything back, Pat has lost that $\$1550$.
But maybe Pat should have consulted a lawyer rather than mathematicians.

Rental Problem between tenants


How to Concatenate or Merge columns in a jagged array of type object[][]

Question: I am having a jagged array of type object[][] with 10 rows and 5 columns. I want to merge last two columns into one (last but one column) and remove the last column.
For example:
Row 1 has below Columns
sampleData[0]  - "110"
sampleData[1]  - "ABC"
sampleData[2]  - "Google"
sampleData[3]  - "{object[2]}"
             [0] - "{object[3]}"
                 [0]  - "01"
                 [1]  - "apple"
                 [2]  -  "Fruit"
             [1] - "{object[3]}"
                 [0]  - "02"
                 [1]  - "Mango"
                 [2]  -  "Fruit"
sampleData[4]  - "{object[1]}"
             [0] - "{object[3]}"
                 [0]  - "03"
                 [1]  - "Banana"
                 [2]  -  "Fruit"

Now I want sampleData[4] to be copied to sampleData[3] and remove sampleData[4].
So it should be like below
Row 1:
sampleData[0]  - "110"
sampleData[1]  - "ABC"
sampleData[2]  - "Google"
sampleData[3]  - "{object[3]}"
             [0] - "{object[3]}"
                 [0]  - "01"
                 [1]  - "apple"
                 [2]  -  "Fruit"
             [1] - "{object[3]}"
                 [0]  - "02"
                 [1]  - "Mango"
                 [2]  -  "Fruit"
             [2] - "{object[3]}"
                 [0]  - "03"
                 [1]  - "Banana"
                 [2]  -  "Fruit"

Can someone suggest me how to achieve this?
Here is the code which I tried:
    public static object[][] MergeResults(object[][] sampleData)
    {

    object[] mergedArray, actualData;
    object[][]results;
    if(sameplData != null && samepleData.Any())
    {
    int row = 0;
    int totalNoOfColumns = sampleData[0].length;
    int noOfColumns = totalNoOfColumns;
    results = new object[sampleData.Count()][];
    int objectCount = sampleData[0].Where(x=>x.GetType().Name == "object[]").Count();

        foreach(var item in sampleData)
    {
        mergedArray = new object[totalNoOfColumns -1];
        actualData = new object[objectCount];
        int j = 0;

        for (int i= 0; i < (item.Length - 1); i++)
        {
          if(item[i].GetType().Name == "object[]")
        {
        int k = 0;
        while (i < totalNoOfColumns)
        {
        actualData[k] = item[i];
        i++;k++;
        }
        mergedArray[noOfColumns- 2] = actualData;
        }
        else
        {
        mergedArray[j] = item[i];
        j++
        }
        }
        results[row] = mergedArray;
        row++;
        }
        }
        return results;
        }

I see the results for column 3 is coming as
sampleData[3]         {object[2]}
            [0]       {object[1]}
              [0]     {object[3]}
               [0]   "01"
               [1]   "apple"
               [2]   "Fruit"
            [1]          {object[1]}
              [0]     {object[3]}
                [0]     - "02"
                [1]  - "Mango"
                [2]  -  "Fruit"

Here I want to avoid {object[1]} in every set.
Comment: What have you already tried? Please post code
Comment: FYI: Just to clarify terminology, a two-dimensional array would be `object[,]`. `object[][]` is called a [jagged array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays)
Comment: Seriously could have you not provided valid C# code for your data? Now to write up and test a solution we need to do that work. Could you please do it? And if the expected output could be as C# code too then we can properly test.
Answer: // Copy the contents of sampleData[4] to sampleData[3]
sampleData[3] = sampleData[4];

// Remove sampleData[4]
sampleData.splice(4, 1);

Use this format in your code.
Answer: Given the data in valid C# form:
var sampleData = new object[]
{
    "110",
    "ABC",
    "Google",
    new object[]
    {
        new object[]
        {
            new object[] { "01", "apple", "Fruit",  }
        },
        new object[]
        {
            new object[] { "02", "Mango", "Fruit",  }
        },
    },
    new object[]
    {
        new object[]
        {
            new object[] { "03", "Banana", "Fruit",  }
        },
    }
};

Then this works:
var output =
    sampleData
        .Take(3)
        .Concat(new object[]
        {
            sampleData
                .Skip(3)
                .Cast<object[]>()
                .SelectMany(x => x)
                .ToArray()
        })
        .ToArray();

I wrote this formatter to test it:
IEnumerable<string> Output(string prefix, object data)
{
    if (data is object[] array)
    {
        for (var i = 0; i < array.Length; i++)
        {
            foreach (var x in Output($"{prefix}[{i}]", array[i]))
                yield return x;
        }
    }
    else if (data is string text)
    {
        yield return $"{prefix} = {text}";
    }
}

Now the sampleData is:
[0] = 110
[1] = ABC
[2] = Google
[3][0][0][0] = 01
[3][0][0][1] = apple
[3][0][0][2] = Fruit
[3][1][0][0] = 02
[3][1][0][1] = Mango
[3][1][0][2] = Fruit
[4][0][0][0] = 03
[4][0][0][1] = Banana
[4][0][0][2] = Fruit

And the output is:
[0] = 110
[1] = ABC
[2] = Google
[3][0][0][0] = 01
[3][0][0][1] = apple
[3][0][0][2] = Fruit
[3][1][0][0] = 02
[3][1][0][1] = Mango
[3][1][0][2] = Fruit
[3][2][0][0] = 03
[3][2][0][1] = Banana
[3][2][0][2] = Fruit


Weird sound playing on an backing track in A

Question: I have a hard time figuring out what is wrong with my playing when trying some impro stuff in blues. I am fairly new to playing guitar on a more serious level now. Just started with blues because I love it so much.
I did the following:

Find a blues backing track in A
Connecting it via Bluetooth to my Blackstar Fly 3 mini amp
Connecting my guitar made sure the tuning is in E (standard)
Put my Shure SM57 mic in front of the amp
Recording with Cubase LE (without any effects)
Playing along the backing track with the A Blues Scale

When playing I do not hear much wrong to be honest. But as I start listening to the recording it sounds very odd to me like I was playing a wrong scale or whatever. But I really am sure I used the A Blues scale here I swear ;)
Can anybody might figure out what the actual problem is? Here is the link to listen to the track (sorry for having to listen to it!): https://vocaroo.com/i/s0ZBPQsOMs12
Comment: You should have added an open chord that we could check your tuning. it sounds as the g- and b-string are not well tuned. or are you pulling with your fingers on the frets? or manipulatingon the tremolo system?
Comment: Hm actually none mentioned. I have no tremolo and I don't think I mess with the frets. I gonna try to re-record it and this time double check the tuning if you really think that might be the issue here.
Comment: Welcome to the wonder world of hearing yourself recorded. It truly is the best for pointing out issues you don't hear when you are playing. They exist. And recording yourself just lets you hear them without being distracted by playing. Is your action very high? Sound like you are bending the strings slightly. If they truly are in tune and intonated.
Answer: I suspected it was a tuning problem at first, and after listening to your recording I could confirm it. You are using the right scale, but the higher notes are a bit out of tune. Some possibilities:

The E string, and maybe the B string are not well tuned. You said you made sure the tuning is right, so it's probably not that.
You guitar is not well intonated. The tuning of the open string is right, but the fretted notes are out of tune. You can easily test this one by tuning the open E string, and checking if the 12th fret is also a perfectly tuned E, for example.
If you are using very light gauge, the pressure of your finger on the fret could be stretching the strings, making them sound sharper. You can test this by playing any fret really gently and gradually increasing pressure.  If the sound gets gradually sharper, that's it.


Are all convex hulls polytopes too?

Question: A convex hull of a set $X$ of points is defined as:

the smallest convex set that contains $X$.

Does this definition imply that all convex hulls of a convex set are in fact, polytopes of their respective dimensions?
Comment: The convex hull of a convex set is the set itself !
Comment: Did you try a 2d example?
Answer: Your question seems to me to indicate several confusions.
Here are some facts you should understand. They follow from the definition of "convex hull".

A set has just one convex hull, so you needn't ask about "all convex
hulls".
If a set is convex then it is its convex hull (as @YvesDaoust
comments).
The convex hull of a finite set will be a polytope. Its dimension may be lower than the dimension of the containing space - for an example think about the convex hull of two points in the plane (or even the convex hull of one point on the line).
Any polytope is the convex hull of the (finite) set of its vertices.
The convex hull of (the circumference of) a circle in the plane is
the circle together with its interior. Clearly that's not a polytope.
Comment: @toric_actions Whether or not every polytope is convex depends on the definition of "polytope". Some definitions allow for nonconvexity. Then the assertion is false.  If a polytope is an intersection of half spaces then the assertion is true.
Comment: Great! You explained it better than most of the sources I'm reading off. Just to clarify, in the third point, why have you mentioned "perhaps of dimension lower than containing space"? Thanks!
Comment: @UnimpressedLemur You're welcome. See my edit.
Comment: Ohh I get it now. Thanks a lot
Comment: @EthanBolker By the fourth fact do you mean to imply that every polytope is a convex polytope?

Are all convex hulls polytopes too?


Quantification of the extent of periodicity in a time series using fractal analyses

Question: I need metrics to quantify the extent of periodicity between of a time series (for comparison with other time series), considering the time series is almost periodic. By almost periodic I mean: if I were to take one time series and segment (consider it is possible and allowed to do this) its periods, there would be a fairly strong cross-correlation (say >8) between any two of these segmented periods within one time series.
The simplest metric I can think of is average of cross-correlations between pairs of segmented periods within the time series. I would expect the time series with a higher average cross-correlation to be more periodic than a time series with a lower average cross-correlation measure. This seems intuitively fair, because if we were to take the average cross-correlation measure for a perfectly periodic time series say a sinusoid, I would expect the cross-correlation between any two of this periodic segments to be one (as they are the same) and hence find the average cross-correlation among a set of such segmented periods to be 1 (which is the maximum value in this metric).
I would also like to know if there is a way to do it using fractal analyses, considering only one time-scale resolution (self similarity i.e. of the periods in one time scale and not in multiple time scale resolutions)? I understand that the point of use of fractal analysis is that it considers multiple time-scales, but I want to understand its use and where it stands from the perspective of single time-scale resolution. I also want to see if there is a generalization of the the measurement of self similarity when time scales are varied differently (single time scale being an extreme case where it is not varied at all).
I am currently using fractal dimension measures as heuristics to quantify the smoothness/roughness of a time series. If I could find a metric using fractal analysis to also quantify extents of periodicity of time series, it would complement the other time series analyses I am performing.
Here's a link to a csv with two vectors that I would like to compare the extent of periodicity of, for example.
Comment: Can you please address the following to make your question answerable? 1) Do you want to compare two time series or evaluate one time series? 2) The cross correlation is always between −1 and 1, unless you do not normalise, in which case the value itself is meaningless. 3) The whole point of fractal analysis is that it considers multiple scales. If you consider a single scale, you can use simpler methods. Why are you so keen on fractal analysis anyway? 4) Can you roughly say, why you want to do this?
Comment: @Wrzlprmft I have improved the problem description as you suggested.
Answer: Consider the following methods:

The autocorrelation of a time series for a given time delay $τ$ is nothing but the cross-correlation of a time series with a respectively delayed version of itself. The autocorrelation is 1 for $τ=0$ and also for $τ=θ$, if the time series is perfectly periodic with a period length $θ$.
To quantify the periodicness of a time series, consider the height of the highest non-trivial maximum of the autocorrelation function. (Non-trivial means $τ≠0$.)
Periodograms such as the discrete Fourier transform yield, roughly speaking, to which extent certain frequencies (in sinusoidal form) are present in the time series.
To quantify the periodicness of a time series, you can measure the area under the most prominent peak in the periodogram and the corresponding subharmonics. (Without the latter your measure would be biased, yielding higher periodicness for sinusoidal time series.)

Periodogram-based approaches are more robust to certain effects like frequency drifts (which only broaden the peaks in the periodogram but may destroy the autocorrelation). Whether that's a good thing for your application is something you have to decide.
Note that the above methods come with all sorts of caveats and open parameters and thus I would strongly advise against blindly applying them and for looking into the literature.


AlarmManeger setExact is not working

Question: setExact method is not working on my project
Log.d("Alarm","Fire");

that is in AlarmManagerBroadcastReceiver is not showing up after 1 minute!
    public class MainActivity extends AppCompatActivity {
    .
    .
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            .
            .

            Calendar alarm = Calendar.getInstance();
            alarm.setTimeInMillis(System.currentTimeMillis());
            alarm.add(Calendar.MINUTE,1);

            Intent myIntent = new Intent(MainActivity.this, AlarmManagerBroadcastReceiver.class);
            PendingIntent  pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), pendingIntent);
            .
            .
}
}

AlarmManagerBroadcastReceiver:
public class AlarmManagerBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("Alarm","Fire");

       }
}

I have tried to extend BroadcastReceiver instead of WakefulBroadcastReceiver. I also tried to set diffrenet hard coded times.  However, nothing works.
Please help
Comment: Hoping you have not missed declaring the receiver and adding the wake lock permission in manifest file.
Comment: @RickSanchez Thanks so much. Problem solved. I can't believe that I made that dumb mistake. Thanks a lot Rick
Answer: This link (Scheduling Repeating Alarms) helps you. You must add
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<receiver android:process=":remote" android:name=".AlarmManagerBroadcastReceiver"></receiver>

AlarmManeger setExact is not working


Find the limit of the function

Question: Function: $e^{-2x}x\cos(x^2)$ if x tends to +infinity. I've tried to calculate it but I got 0*infinity, it's indeterminate.
Comment: Do you mean $$\lim_{x \to \infty}e^{-2x}xcos(x^2)=?$$
Comment: hint $\cos(x)\leq 1$
Answer: Since $\cos(x^2)$ is bounded and $\lim_{x\to\infty}xe^{-2x}=0$:
$$\lim_{x\to\infty}x\cos(x^2)e^{-2x}=0$$
Answer: Since $-1\leq\cos(x^2)\leq 1$ for all $x$ we have $$0 = \lim_{x\rightarrow\infty}-xe^{-2x}\leq \lim_{x\rightarrow\infty}\cos(x^2)x e^{-2x}\leq \lim_{x\rightarrow\infty}xe^{-2x} = 0$$ so $\lim_{x\rightarrow\infty}\cos(x^2)x e^{-2x} = 0$ by the squeeze theorem

Find the limit of the function


Advice on creating specific data type in CakePHP

Question: I have a model called Company which contains a field called type. Based on that type, I'd like to offer the user a list of checkboxes to select to add more data about their type. To be more specific, based on their business type, I'd like to offer a range of services which they can check off if they provide.
What would be the best method to achieve this? Do I add a new field called services and implode/explode the options there? Or do I set up a database relation?
The list of business types and services is fairly static, something I would typically use an array for as opposed to a database table.
Any input would be super.
Comment: It depends on the scale (ie, how many business types there are, and how many services there are for each type), and also on how often they'll change. If they'll change often, and there are lots of them, use a database relation. If there's only a few and they won't change often, it's easier to hard-code it. Update your question to give an indication of the number of services and types.
Comment: Thanks @joshua.paling. Answer updated, but to repeat, fairly static list of business types and services.
Comment: OK, the data is static. What about quantity? How many 'services' are there in total? 5? 20? 100? And what about how many 'services' for a particular business 'type'?
Comment: About 4 services for each business type.
Comment: You forgot to add - how many 'services' are there in total (ie, across all business types)? (and if I were you I'd add all that info; ie, number of services total, number of services per business, is there any overlap - ie, is any one service relevant to multiple business types?, and lastly, number of business types, to your original question. This info is important to know in deciding on the best solution.
Answer: Starts from the beginning adding field name services in the existing table wouldn't be create problem because of low data in the table, but when more and more data would be inserted in the table that will effect communication goes to decreases that's means your data execution time will getting more when type and services lives in common table, It would better when both stay differently, in this case for queue data execution time will be less, and performance would be increase.
Note:- My English is poor so please feel free for editing and also suggest me my mistakes :)


wpf DataGridComboBoxColumn GroupStyle

Question: Is there anyway to set a groupstyle to DataGridComboBoxColumn
any help please
thanks
Answer: I believe you need to set the GroupStyle for the DataGrid that contains the DataGridComboBoxColumn.
<DataGrid.GroupStyle>
    <GroupStyle>
      <GroupStyle.HeaderTemplate>
        <DataTemplate>
          <TextBlock FontWeight="Bold" FontSize="15"
                     Text="{Binding Path=Name}"/>
        </DataTemplate>
      </GroupStyle.HeaderTemplate>
    </GroupStyle>
  </DataGrid.GroupStyle>

Answer: Jon's answer can be further explored here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/6e463473-4cb3-486f-ac2b-c2ee2c844cf4/setting-the-group-style-for-a-datagridcomboboxcolumn?forum=wpf
I don't think this will actually produce a combobox with groups in the collection.  The closest I have found is:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/6edb400e-c29e-4cb9-badc-424fd4b20bef/datagrid-combobox-column-and-grouping-question-using-databinding?forum=wpf
This however is flawed too unless you want to override a lot of the functionality and be fairly meticulous about the current state of it all.  I don't think there is any built in way to style a datagridcomboboxcolumn in wpf with group headers.

wpf DataGridComboBoxColumn GroupStyle


Spring Boot 1.4: Spring Data Cassandra 1.4.2 is incompatible with Cassandra 3.0?

Question: I'm facing a problem when I try to use Spring Data Cassandra in the most version of Spring Boot (1.4).
It seems to be a maven dependencies problem, which does not load the latest version of Cassandra driver. Is there any solutions please to fix that problem?
Thanks in advance!
[

Edit After the integration of the proposed solution by mp911de

]
Thanks for your reply, I set cassandra-driver as you suggest, but I still have errors,  this the full stack trace.
08:46:41.691| ERROR | Application startup failed                                                                                | org.springxxamework.boot.SpringApplication.handleRunFailure(SpringApplication.java:827)
org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraMapping' defined in class path resource [xx/xxx/xxx/cap/web/config/CasssandraConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springxxamework.beans.BeanInstantiationException: Failed to instantiate [org.springxxamework.data.cassandra.mapping.CassandraMappingContext]: Factory method 'cassandraMapping' threw exception; nested exception is java.lang.NoSuchMethodError: com.datastax.driver.core.DataType.asJavaClass()Ljava/lang/Class;
    at org.springxxamework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springxxamework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springxxamework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springxxamework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springxxamework.context.support.AbstractApplicationContext.rexxesh(AbstractApplicationContext.java:538)
    at org.springxxamework.boot.context.embedded.EmbeddedWebApplicationContext.rexxesh(EmbeddedWebApplicationContext.java:118)
    at org.springxxamework.boot.SpringApplication.rexxesh(SpringApplication.java:766)
    at org.springxxamework.boot.SpringApplication.createAndRexxeshContext(SpringApplication.java:361)
    at org.springxxamework.boot.SpringApplication.run(SpringApplication.java:307)
    at xx.xxx.xxx.cap.web.Application.main(Application.java:66)
Caused by: org.springxxamework.beans.BeanInstantiationException: Failed to instantiate [org.springxxamework.data.cassandra.mapping.CassandraMappingContext]: Factory method 'cassandraMapping' threw exception; nested exception is java.lang.NoSuchMethodError: com.datastax.driver.core.DataType.asJavaClass()Ljava/lang/Class;
    at org.springxxamework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springxxamework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 16 common xxames omitted
Caused by: java.lang.NoSuchMethodError: com.datastax.driver.core.DataType.asJavaClass()Ljava/lang/Class;
    at org.springxxamework.data.cassandra.mapping.CassandraSimpleTypeHolder.<clinit>(CassandraSimpleTypeHolder.java:62)
    at org.springxxamework.data.cassandra.mapping.BasicCassandraMappingContext.<init>(BasicCassandraMappingContext.java:73)
    at xx.xxx.xxx.cap.web.config.CasssandraConfiguration.cassandraMapping(CasssandraConfiguration.java:36)
    at xx.xxx.xxx.cap.web.config.CasssandraConfiguration$$EnhancerBySpringCGLIB$$9133c12d.CGLIB$cassandraMapping$3(<generated>)
    at xx.xxx.xxx.cap.web.config.CasssandraConfiguration$$EnhancerBySpringCGLIB$$9133c12d$$FastClassBySpringCGLIB$$ec58ee73.invoke(<generated>)
    at org.springxxamework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springxxamework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at xx.xxx.xxx.cap.web.config.CasssandraConfiguration$$EnhancerBySpringCGLIB$$9133c12d.cassandraMapping(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springxxamework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 17 common xxames omitted
08:46:41.709| ERROR | Error handling failed                                                                                | org.springxxamework.boot.SpringApplicationRunListeners.callFinishedListener(SpringApplicationRunListeners.java:86)
org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springxxamework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Initialization of bean failed; nested exception is org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'org.springxxamework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Initialization of bean failed; nested exception is org.springxxamework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springxxamework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springxxamework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springxxamework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:228)
    at org.springxxamework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:185)
    at org.springxxamework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at org.springxxamework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:121)
    at org.springxxamework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111)
    at org.springxxamework.boot.context.event.EventPublishingRunListener.finished(EventPublishingRunListener.java:98)
    at org.springxxamework.boot.SpringApplicationRunListeners.callFinishedListener(SpringApplicationRunListeners.java:79)
    at org.springxxamework.boot.SpringApplicationRunListeners.finished(SpringApplicationRunListeners.java:72)
    at org.springxxamework.boot.SpringApplication.handleRunFailure(SpringApplication.java:833)
    at org.springxxamework.boot.SpringApplication.run(SpringApplication.java:318)
    at xx.xxx.xxx.cap.web.Application.main(Application.java:66)
Caused by: org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'org.springxxamework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Initialization of bean failed; nested exception is org.springxxamework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springxxamework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined
    at org.springxxamework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springxxamework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springxxamework.beans.factory.support.ConstructorResolver.resolvePreparedArguments(ConstructorResolver.java:786)
    at org.springxxamework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:123)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1034)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springxxamework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springxxamework.aop.xxamework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
    at org.springxxamework.aop.xxamework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101)
    at org.springxxamework.aop.xxamework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87)
    at org.springxxamework.aop.xxamework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
    at org.springxxamework.aop.xxamework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:346)
    at org.springxxamework.aop.xxamework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    ... 16 common xxames omitted
Caused by: org.springxxamework.beans.factory.BeanCreationException: Error creating bean with name 'org.springxxamework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Initialization of bean failed; nested exception is org.springxxamework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springxxamework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springxxamework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springxxamework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springxxamework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springxxamework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    ... 36 common xxames omitted
Caused by: org.springxxamework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springxxamework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined
    at org.springxxamework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springxxamework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springxxamework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor.postProcessBeforeInitialization(ConfigurationClassPostProcessor.java:439)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    at org.springxxamework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    ... 51 common xxames omittedende

Comment: @mp911de you should post your comment as an answer. It's very helpful and you are even working in Pivotal
Comment: @mp911de what should I do in order to play with it, please?
Comment: You're right, Spring Boot 1.4 with Spring Data Cassandra 1.4.2 is incompatible with Cassandra 3.0. Spring Data 1.5 is (will) be compatible with Cassandra 3.0. We already shipped a milestone release.
Answer: You're right, Spring Boot 1.4 with Spring Data Cassandra 1.4.2 is incompatible with Cassandra 3.0.
Spring Data 1.5 is (will) be compatible with Cassandra 3.0. We already shipped a milestone release (Ingalls M1). The stable release is targeted later this year. Depending on your other dependencies, you need to declare netty as an additional dependency because it's currently excluded in Spring Data Cassandra.
How to upgrade
Spring Boot Users
Set the spring-data-releasetrain.version property in your pom.xml file to Ingalls-M1 and make sure to include the milestone repository declaration:
<properties>
    <spring-data-releasetrain.version>Ingalls-M1</spring-data-releasetrain.version>
</properties>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

Maven Users (Without Spring Boot Dependency management)
Include Spring Data Cassandra 1.5.0.M1 in your pom.xml:
<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-cql</artifactId>
        <version>1.5.0.M1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-cassandra</artifactId>
        <version>1.5.0.M1</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

Here's the link to the announcement post: https://spring.io/blog/2016/07/27/spring-data-release-train-ingalls-m1-released
Comment: I don't have "spring-data-releasetrain.version" in my "pom.xml", should I add it, if so, how? please. I do it like that :  Ingalls-M1
Comment: If you don't have it (which is fine), simply create it the way you wrote it.
Comment: I still Have the same error : org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraMapping' defined in class path resource [xx/xx/xx/cap/web/config/CasssandraConfiguration.class]: Bean instantiation via factory method failed; nested ex
Comment: Do you have the full stack trace somewhere? If the Cassandra driver version still 2.x? If so, then please override the version with the property `3.0.3`.
Comment: `cassandra-driver-mapping` is not used by Spring Data Cassandra. The driver has the right version number but I see from the stack trace that Spring Data Cassandra is still 1.4.x and not 1.5.0.M1.