text:
Q: PHP - A Better way to call $_POST Data? Is there a better way to using post data rather then defining the variables manually?
My Current Method
<form method="POST" action="form.php">

    <input type="text" name="name" id="name" />

    <input type="submit" value="Submit">

</form>

<?php

    $name = $_POST['name'];

    function echoname ($name) {

        echo $name;

    };

    echo "This is my new" . echoname ($name);

?>

Now I know you can just go like this for my example however it is only an example:
<?php

    $name = $_POST['name']

        echo "This is my new" . $name;

?>

Is there a better way to use $_POST['value'] without having to define the post data as a variable every time?
As a note, i have looked here: PHP Manual $_POST already
Thanks!

A: If you don't want to use extract() for security purposes (even though you could simply skip variables that already exist), then you can simply loop through an array - check if the $_POST value exists, and if it does, create a variable of the key:
<?php
    $postVariablesToExtract = array("name", "password", "email");

    foreach ($postVariablesToExtract as $postVariableToExtract) {
        if (isset($_POST[$postVariableToExtract])) {
            $$postVariableToExtract = $_POST[$postVariableToExtract];
        } else {
            $$postVariableToExtract = null;
        }
    }

    var_dump($name); //null - as we don't have any POST values
    var_dump($password); //null - as we don't have any POST values
    var_dump($email); //null - as we don't have any POST values
?>

A: Yes, you can use
echo "This is my new" . $_POST['name'];

but, the better way is
if(isset($_POST['name'])) // check if this data is exsit
    echo "This is my new" . $_POST['name'];

A: Of course, you can use the variable directly i.e.:
echo "This is my new " . $_POST['name'];

However it's a good idea to check for emptiness (or validating in general). For example, in the case below, if the variable is empty I assign a default value:
$name = empty($_POST['name']) ? 'John' : $_POST['name'];
echo "This is my new $name";

A: $_POST['value'] is already a variable so its not a must for you to store it in a variable. Then again, its common practice to store it in a variable before manipulating it.
Also, $_POST is an array. Which is why you need to specify the Key, in your case ['value'] is your key. Now you can also echo out the entire $_POST if you want to see other values it holds, but then echo does not work on arrays, so you will need to use print_r($_POST);

A: I'm not sure in what way you need it, but it might be important that $_POST is normal array, so you can use foreach function.
foreach ($_POST as $item) {
  print_r($item);
}

A: There are many ways to get post data but it depends the requirement in some instances.

*

*foreach ($_POST as $key => $value)     $body .= $key . ' -> ' .
$value . '';

*If posted data has no key, but only value, use Raw Post Data:
$postdata = file_get_contents("php://input");

*You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

*You can also use simply $input_data = $_POST extract() may be
useful for you.


text:
Q: EmberJS + EmberData: how to listen to model load from server Environment:
Ember.VERSION = 1.7.1
DS.VERSION = 1.0.0-beta.14.1
Problem:
I'm trying to run some code when the view is finally rendered on initial application load, the problem is the model is not yet loaded because the client fetches it from the server.
so the flow (I guess) that happens is something like this:

*

*Ember renders the view, requests the model

*Model returns a promise but view is rendered anyhow

*After AJAX is finished model is updated and view is re rendered

I want to run some code (bootstrap init of tooltips) after step 3 is completed, but I dont really sure how to.
just to point out, after the model is fetched from server when I leave and return to the same route everything is works fine (because the model returns from the store and not from server)
what I tried so far:
How can catch event after template is rendered at EmberJS?
App.ApartmentsView = Ember.View.extend({
   didInsertElement: function () {
       $('[data-toggle="tooltip"]').tooltip();
   }
});

this didnt work, because at that point the model length is 0
listening to model change:
App.ApartmentsRoute = Ember.Route.extend({
   model: function () {
       return this.store.filter('apartment').then(function (model) {
           console.log(model);
           return model;
       });
   }
});

Again, at this point the model.content.length = 0 I guess at this point the store just creates the model and only at a later point updates it.
I've also tried listening to the arrayContentDidChange property in the controller, but at this point the model is not rendered yet, I can use a timeout but I think its a bad solution.
UPDATE1:
here is the template:

Any suggestions?

A: Your description of the lifecycle is incorrect. It should be:

*

*Ember enters the route.

*Route's model hook is invoked.

*The returned value from the model hook is resolved.

*Proceed with the transition, including rendering the template and calling its didInsertElement hook.
The problem is that your model hook is returning a promise from the filter, but at that point, as you've found, there are no records in the store yet, and thus nothing to filter. What I am missing from your question is when and how you do expect the apartments to be loaded from the server. filter will not do that for you. For our purposes, let's assume you have a routine, returning a promise, called getApartments, that ensures that the necessary models are loaded from the server. Perhaps it is something as simple as
getApartments: function() {
    return this.store.find('apartments');
}

Then replace your model hook with something like this:
model: function () {
  return this.getApartments() .
    then(function(model) {
      return this.store.filter('apartment', filterfunc);
    })
  ;
}

Now Ember will wait until the promise from getApartments is resolved, then use the filtered result as its model, and then render, so the element you want should be available for manipulation in your didInsertElement hook.
However, this will still fail when additional apartments are added to the store later, because didInsertElement has already run when the element was added. To solve, this problem, I suggest moving your logic for rendering individual apartments into a component. This is probably a good way to factor your code anyway.

components/show-apartment/template.hbs

  {{content.rating}}
  ...
  <button type="button" class="btn btn-default" aria-label="Left Align" data-toggle="tooltip" data-placement="top" title="Navigate" {{ action 'navigate' content}}>
  ...

Then, in the component's JS, initialize the tooltip in didInsertElement:

components/show-apartment/component.js

export default Ember.Component.extend({

  didInsertElement: function() {
    $(this).find('[data-toggle="tooltip"]').tooltip();
  }

});

Then in your top-level template, use the new component to display each apartment:
{{#each apartment in model}}
  {{show-apartment content=apartment navigate=navigate}}
{{/each}}

Now, each time a new apartment comes into the store, the filtered model will reflect it, the {{#each}} will generate a new entry, a new component will be created and rendered, and the didInsertElement logic on that component be run to initialize that particular tooltip.
By the way, your model hook is calling store.filter with no filter function. What are you trying to accomplish with that?
Using isLoaded is a hack and a code smell, not necessary in the land of promises.

A: If you want something to render only after its model is loaded then I guess you can check for isLoaded key in the template. Something like this

template.hbs

{{#if model.isLoaded}}
     All the HTML stuff that will be shown only if model is loaded.
{{/if}}

A: As @torazaburo already mentioned, the issue was in the filter function. Simply
model : function(){
  return this.store.filter('apartment', {}, function(item){
    return true;
  });
}

would work for you. Obviously, this is analogous to this.store.find('apartment')
Actually this is a simple hack (including empty object as query) to get data from server before filter.
But, to make sure that tooltips get initialized on newly added elements, much better approach is mentioned by @torazaburo
DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: input value that's binded with vue does not show up in the dom I'm trying to bind a property of an item that belongs to an array in the data object of vue to the value attribute of an input tag, but it does not show up if I look at it in the DOM of a web browser.
<template v-for="role in roles">

                {{ role.Name }}

                    <button type="button" class="btn-danger" @@click="RemoveRole(role)">Remove</button>

                    <input type="text" :id="role.Id" name="role[]" v-model="role.Id"/> // results in just "<input type="text" id="..." name="role[]" />"
                    // there is no value attribute visible, but the Id attribute can give the right value?

        </template>

The id attribute can give the right value so why cant the value attribute?
:value="role.Id" does not work.

Does anyone have a clue.

A: What you're seeing is normal. Vue treats the value attribute of an <input> specially and sets it as a property rather than as an attribute. Effectively the compiled template uses:
input.value = role.Id

rather than:
input.setAttribute('value', role.Id)

You can see the relevant Vue source code here:
https://github.com/vuejs/vue/blob/98b4d683f578bb09c4e56f35048e49441c590a41/src/compiler/parser/index.js#L837
with the implementation of platformMustUseProp being here:
https://github.com/vuejs/vue/blob/98b4d683f578bb09c4e56f35048e49441c590a41/src/platforms/web/util/attrs.js#L11
If you remove the hidden attribute from the surrounding  you should see that the <input> does contain the correct value. It isn't clear why you need it to have a value attribute, for most practical purposes that shouldn't matter as everything should be accessing the value using input.value instead.
If the <input> is going to be hidden you may also want to consider using type="hidden" rather than type="text".

A: <input type="text" :id="role.Id" name="role[]" :value="role.Id"/>


text:
Q: how to present a navigation controller embedded in a tab bar controller when receiving a push notification I'm working on a project with a tab bar controller and push notifications, when my app receives a push notifications depending of the alert body it will open a determinate view controller that is embedded in tab bar.
I already can present the view controller but i lost the tab bar.
For presenting the view controller this is what i do:
 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            vc5 *ivc = [storyboard instantiateViewControllerWithIdentifier:@"vc5"];
            UINavigationController *navigationController=[[UINavigationController alloc] initWithRootViewController:ivc];
            self.window.rootViewController =nil;
            self.window.rootViewController = navigationController;
            [self.window makeKeyAndVisible];

I tried this code to show the tab bar but i didn't work:
UITabBarController *tabBarController = [[UITabBarController alloc] initWithNibName:@"tabBarController" bundle:nil];
    tabBarController.selectedViewController = [storyboard instantiateViewControllerWithIdentifier:@"tabBarController"];
    tabBarController.selectedViewController = nil;
    tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:0];
    UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
    [tabBar setSelectedIndex:0];

My Storyboard consists of an Initial Login ViewController that is inside a navigation controller, after the user logins is prompt to pick a city and then i present a tab bar controller that consists o 4 tabs, the view that i need to present via push notification is in the first tab and is the fifth view inside that navigation controller.
I look out other questions here in SO but nothing works, this is the first time i develop in iOS, any help would be highly appreciated. thank you

EDIT:
 I also try to make a segue from the AppDelegate when i receive the notification but i get this error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (<TabBarController: 0x16dec150>) has no segue with identifier 'pushNotification'

This is my code for the push:
TabBarController *tabBar = [[TabBarController alloc] initWithNibName:@"tabBarController" bundle:nil];
    [tabBar performSegueWithIdentifier:@"pushNotification" sender:self];

A: Perform the segue from the initial login view controller, not from the app delegate. In order to do a push segue using storyboards you have to name your segue and view in storyboards. You can name these items by selecting them and using the property panel on the right in xCode.

A: UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

//Create view controller for Main here
UIViewController * MainNC = [storyboard instantiateViewControllerWithIdentifier:@"HomeNavigationController"];

[self presentViewController:MainNC animated:NO completion:nil];

A: I resolved this by presenting the view controller when the notification arrives and pass the necessary data to the view controller


text:
Q: navicat select number of entries in one table as value in query builder I have a current Navicat Query Builder as follows:

I want to select to select the number of records from another table that will be linked to the scoring_sections table as "num_entries" in the output results.
The table that I will be linking looks like this:

I cannot seem to figure this out as this is my first time working with navicat and couldn't find anything on Google
Thanx in advance

A: I had to group_by all the columns from the scoring_sections  that are linked to the entries table and just added COUNT(entries.id) AS num_entries in the select statement. so used MYSQL knowledge to complete this


text:
Q: scan string using nsscanner class I want to scan this string
"hello I am emp 1313 object of string class 123"

so in this I want to know if their are any integer value present and if present I want to display them for this I am using the NSScanner class and heres a view of my code
NSString *str = @" hello I am emp 1313 object of string class 123";

NSString *limit = @" object";
NSScanner *scanner = [NSScanner scannerWithString:str];

int i;
[scanner scanInt:&i];
NSString *output;
[scanner scanUpToString:limit intoString:&output];
NSLog(@"%d",i);

but the problem is that I am not able to do it and I want to use NSScanner class only so can you experts give me some suggesstions regarding this.....

A: Give this a try:
NSString *str = @" hello i am emp 1313 object of string class 123";
NSScanner *scanner = [NSScanner scannerWithString:str];

// set it to skip non-numeric characters
[scanner setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

int i;
while ([scanner scanInt:&i])
{
    NSLog(@"Found int: %d",i);
}

// reset the scanner to skip numeric characters
[scanner setScanLocation:0];
[scanner setCharactersToBeSkipped:[NSCharacterSet decimalDigitCharacterSet]];

NSString *resultString;
while ([scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&resultString]) {
    NSLog(@"Found string: %@",resultString);
}

It outputs:
2010-10-27 14:40:39.137 so[2482:a0f] Found int: 1313
2010-10-27 14:40:39.140 so[2482:a0f] Found int: 123
2010-10-27 14:40:39.141 so[2482:a0f] Found string:  hello i am emp
2010-10-27 14:40:39.141 so[2482:a0f] Found string:  object of string class


text:
Q: Atomic INSERT/SELECT in HSQLDB I have the following hsqldb table, in which I map UUIDs to auto incremented IDs:
SHORT_ID (BIG INT, PK, auto incremented) | UUID (VARCHAR, unique)
Create command:
CREATE TABLE mytable (SHORT_ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, UUID VARCHAR(36) UNIQUE)
In order to add new pairs concurrently, I want to use the atomic MERGE INTO statement. So my (prepared) statement looks like this:
MERGE INTO mytable USING (VALUES(CAST(? AS VARCHAR(36)))) AS v(x) ON mytable.UUID = v.x WHEN NOT MATCHED THEN INSERT VALUES v.x
When I execute the statement (setting the placeholder correctly), I always get a
Caused by: org.hsqldb.HsqlException: row column count mismatch
Could you please give me a hint, what is going wrong here?
Thanks in advance.

A: Epilogue
I reported this behavior as a bug, and it is today (2010-05-25) fixed in the hsqldb SVN repository, per hsqldb-Bugs-2989597.  (Thanks, hsqldb!)
Updated Answer
Neat one!  Here's what I got to work under HSQLDB 2.0.0rc9, which supports the syntax and the error message you posted:
MERGE INTO mytable
   USING (SELECT 'a uuid' FROM dual) AS v(x) -- my own "DUAL" table
   ON (mytable.UUID = v.x)
   WHEN NOT MATCHED THEN INSERT
     VALUES (NULL, x)                        -- explicit NULL for "SHORT_ID" :(

Note, I could not convince 2.0.0rc9 to accept ... THEN INSERT (UUID) VALUES (x), which is IIUC a perfectly acceptable and clearer specification than the above.  (My SQL knowledge is hardly compendious, but this looks like a bug to me.)
Original Answer
You appear to be INSERTing a single value (a 1-tuple) into a table with more than one column. Perhaps you can modify the end of your statement to read:
... WHEN NOT MATCHED INSERT ("UUID") VALUES (v.x)

A: I got same problems but solve in few minutes.
Its occur when datavalues and table structure are not same.Add explicit (NULL) in your empty column value.
Like i created table
TestCase table:
ID   TESTCASEID DESCRIPTION
but your insertion statement you donot want to add any description for any testcase description then you have to explicite in insertion statement you have to set null value for description


text:
Q: How to pass(i mean display) the index value of
*(under
* default type) to  if  is inside of that said
*? What I want to achieve here is to display the value of the index of

 (under

 default type) to the

(could be one of more, most likely just one) inside it.
MY INITIAL CODE:

First p element in div.

        Second p

A third p element in div.

A fourth p element in div.

SCRIPT:

OUTPUT:
1.1
2.Second p
3.2
4.3

EXPECTED OUTPUT:
1.1
2.Second p
3.3
4.4

A: In your code, both x[j].index and y[k].index are undefined.
What do you expect to happen when this occurs?

A: I recommend using querySelectorAll instead of getElementsByTagName - more precise. Then don't get all p elements in the document; just get all p elements in each li. Probably a more elegant way to do this but the nested loop approach works:

var li = document.querySelectorAll('ol li');

for(var i = 0; i < li.length; i++) {
  var p = li[i].querySelectorAll('p');

  for(var j = 0; j < p.length; j++) {
      p[j].innerHTML = i + 1;
  }
}

First p element in div.

        Second p

A third p element in div.

A fourth p element in div.


text:
Q: Heroku not migrating with new fields I have been working on my local machine and I recently added some field to an existant model.
I tried to push it this morning on Heroku and make the migrations and this is the message I get :

My models.py
Class Todo(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")
    content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    complete = models.BooleanField(default=False)
    recurrence = models.BooleanField(default=False)
    urgence = models.BooleanField(default=False,verbose_name="Tâche urgente")

    def __str__(self):
        return self.text
def get_absolute_url(self):
    return reverse('dashboard-home')

Todo.reccurence is the new field.
Traceback :
Environment:

Request Method: GET
Request URL:

Django Version: 2.1.7
Python Version: 3.6.7
Installed Applications:
['blog.apps.BlogConfig',
 'dashboard.apps.DashboardConfig',
 'users.apps.UsersConfig',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'storages',
 'cloudinary']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /app/blog/templates/blog/base.html, error at line 0
   column dashboard_todo.recurrence does not exist
LINE 1: ...todo"."date_posted", "dashboard_todo"."complete", "dashboard...
                                                             ^

   1 : {% load crispy_forms_tags %}
   2 : <!DOCTYPE html>
   3 : <html>
   4 : <head>
   5 :
   6 :   <!-- Global site tag (gtag.js) - Google Analytics -->
   7 : <script async src="https://www.googletagmanager.com/gtag/js?id=UA-134278636-1"></script>
   8 : <script>
   9 :   window.dataLayer = window.dataLayer || [];
   10 :   function gtag(){dataLayer.push(arguments);}

Traceback:

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

The above exception (column dashboard_todo.recurrence does not exist
LINE 1: ...todo"."date_posted", "dashboard_todo"."complete", "dashboard...
                                                             ^
) was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  156.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  154.                 response = response.render()

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  83.         content = template.render(context, self._request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
  171.                     return self._render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  166.             len_values = len(values)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __len__
  250.         self._fetch_all()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1186.             self._result_cache = list(self._iterable_class(self))

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1065.             cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  100.             return super().execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  68.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
  77.         return executor(sql, params, many, context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /
Exception Value: column dashboard_todo.recurrence does not exist
LINE 1: ...todo"."date_posted", "dashboard_todo"."complete", "dashboard...
                                                             ^

What I usually do is deleting database on my local machine and run migrate again but I really can't do that with real data.
Thanks

A: You should not be running makemigrations on Heroku. Do it locally, commit the result, then run migrate on Heroku.


text:
Q: Flutter - unboundedHeight error within ListView Flutter newbie here!
Currently, my Scaffold has 2 listview builders and the bottom one is giving me the unbounded height (!constraints.hasBoundedHeight error) issue.
I have tried using shrinkWrap on all 3 list views, as suggested in similar questions but I get the same error.
The only thing that works is wrapping the FutureBuilder in a SizedBox. But that seems unintuitive to me, as I would want it to ideally expand as needed and be scrollable.
My rough solution is to maybe dynamically calculate the height based on the number of items the FutureBuilder needs, but again, I feel there should be a better solution.
My code snippet is attached below:
return Scaffold(
      appBar: AppBar(),
      body: ListView(
        children: [
          ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 2,
              itemBuilder: (context, index) {
                return const SuggestCard(
                  indexKey: 'takt',
                );
              }),
          FutureBuilder<AnimeDetails>(
            future: _animeDetail,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: 2, //Number of anime from list
                    itemBuilder: (context, index) {
                      var anime = snapshot.data; //Get the data from the index
                      return AnimeCard(
                        anime: anime,
                      );
                    });
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ],
      ),
    );

A: As per your comment I think below link will helpful to you.
Lists

A: I just added the below lines to your code. You can try the below code.
shrinkWrap: true,
physics: const  NeverScrollableScrollPhysics(),

return Scaffold(
      appBar: AppBar(),
      body: ListView(
        children: [
          ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 2,
              shrinkWrap: true,
              physics: const  NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return const SuggestCard(
                  indexKey: 'takt',
                );
              }),
          FutureBuilder<AnimeDetails>(
            future: _animeDetail,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: 2, //Number of anime from list
                    shrinkWrap: true,
                    physics: const  NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      var anime = snapshot.data; //Get the data from the index
                      return AnimeCard(
                        anime: anime,
                      );
                    });
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ],
      ),
    );

A: The parent ListView handling scroll event for body and while second  ListView will have fixed height, you can do it like this
  return Scaffold(
        body: LayoutBuilder(
      builder: (context, constraints) => ListView(
        children: [
          SizedBox(
            height: constraints.maxHeight * .3,
            child: ListView.builder(
              itemCount: 122,
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) => Text("H $index"),
            ),
          ),
          ListView.builder(
            shrinkWrap: true,
            physics:
                const NeverScrollableScrollPhysics(), // parent controll the scroll event
            itemCount: 44,
            itemBuilder: (context, index) => Text("$index"),
          ),
        ],
      ),
    ));


text:
Q: How to calculate correlation between all columns and remove highly correlated ones using pandas? I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having  >0.8 correlation.  also it should retained the headers in reduce data..
Example data set
 GA      PN       PC     MBP      GR     AP
0.033   6.652   6.681   0.194   0.874   3.177
0.034   9.039   6.224   0.194   1.137   3.4
0.035   10.936  10.304  1.015   0.911   4.9
0.022   10.11   9.603   1.374   0.848   4.566
0.035   2.963   17.156  0.599   0.823   9.406
0.033   10.872  10.244  1.015   0.574   4.871
0.035   21.694  22.389  1.015   0.859   9.259
0.035   10.936  10.304  1.015   0.911   4.5

Please help....

A: You can use the following for a given data frame df:
corr_matrix = df.corr().abs()
high_corr_var=np.where(corr_matrix>0.8)
high_corr_var=[(corr_matrix.columns[x],corr_matrix.columns[y]) for x,y in zip(*high_corr_var) if x!=y and x<y]

A: You can test this code below ?
Load libraries import
  pandas as pd
  import numpy as np
# Create feature matrix with two highly correlated features

X = np.array([[1, 1, 1],
          [2, 2, 0],
          [3, 3, 1],
          [4, 4, 0],
          [5, 5, 1],
          [6, 6, 0],
          [7, 7, 1],
          [8, 7, 0],
          [9, 7, 1]])

# Convert feature matrix into DataFrame
df = pd.DataFrame(X)

# View the data frame
df

# Create correlation matrix
corr_matrix = df.corr().abs()

# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))

# Find index of feature columns with correlation greater than 0.95
to_drop = [column for column in upper.columns if any(upper[column] > 0.95)]
# Drop features
df.drop(df[to_drop], axis=1)

A: I found the answer provided by TomDobbs quite useful, however it doesn't work as intended. It has two problems:

*

*it misses the last pair of variables in each of correlation matrix rows/columns.

*it fails to remove one of each pair of collinear variables from the returned dataframe.

My revised version below corrects these issues:
def remove_collinear_features(x, threshold):
    '''
    Objective:
        Remove collinear features in a dataframe with a correlation coefficient
        greater than the threshold. Removing collinear features can help a model
        to generalize and improves the interpretability of the model.

    Inputs:
        x: features dataframe
        threshold: features with correlations greater than this value are removed

    Output:
        dataframe that contains only the non-highly-collinear features
    '''

    # Calculate the correlation matrix
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []

    # Iterate through the correlation matrix and compare correlations
    for i in iters:
        for j in range(i+1):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = abs(item.values)

            # If correlation exceeds the threshold
            if val >= threshold:
                # Print the correlated features and the correlation value
                print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(col.values[0])

    # Drop one of each pair of correlated columns
    drops = set(drop_cols)
    x = x.drop(columns=drops)

    return x

A: The method here worked well for me, only a few lines of code: https://chrisalbon.com/machine_learning/feature_selection/drop_highly_correlated_features/
import numpy as np

# Create correlation matrix
corr_matrix = df.corr().abs()

# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))

# Find features with correlation greater than 0.95
to_drop = [column for column in upper.columns if any(upper[column] > 0.95)]

# Drop features
df.drop(to_drop, axis=1, inplace=True)

A: Firstly, I'd suggest using something like PCA as a dimensionality reduction method, but if you have to roll your own then your question is insufficiently constrained. Where two columns are correlated, which one do you want to remove? What if column A is correlated with column B, while column B is correlated with column C, but not column A?
You can get a pairwise matrix of correlations by calling DataFrame.corr() (docs) which might help you with developing your algorithm, but eventually you need to convert that into a list of columns to keep.

A: I took the liberty to modify TomDobbs' answer. The reported bug in the comments is removed now. Also, the new function filters out the negative correlation, too.
def corr_df(x, corr_val):
    '''
    Obj: Drops features that are strongly correlated to other features.
          This lowers model complexity, and aids in generalizing the model.
    Inputs:
          df: features df (x)
          corr_val: Columns are dropped relative to the corr_val input (e.g. 0.8)
    Output: df that only includes uncorrelated features
    '''

    # Creates Correlation Matrix and Instantiates
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []

    # Iterates through Correlation Matrix Table to find correlated columns
    for i in iters:
        for j in range(i):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = item.values
            if abs(val) >= corr_val:
                # Prints the correlated feature set and the corr val
                print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(i)

    drops = sorted(set(drop_cols))[::-1]

    # Drops the correlated columns
    for i in drops:
        col = x.iloc[:, (i+1):(i+2)].columns.values
        x = x.drop(col, axis=1)
    return x

A: Here is the approach which I have used -
def correlation(dataset, threshold):
    col_corr = set() # Set of all the names of deleted columns
    corr_matrix = dataset.corr()
    for i in range(len(corr_matrix.columns)):
        for j in range(i):
            if (corr_matrix.iloc[i, j] >= threshold) and (corr_matrix.columns[j] not in col_corr):
                colname = corr_matrix.columns[i] # getting the name of column
                col_corr.add(colname)
                if colname in dataset.columns:
                    del dataset[colname] # deleting the column from the dataset

    print(dataset)

Hope this helps!

A: Plug your features dataframe in this function and just set your correlation threshold. It'll auto drop columns, but will also give you a diagnostic of the columns it drops if you want to do it manually.
def corr_df(x, corr_val):
    '''
    Obj: Drops features that are strongly correlated to other features.
          This lowers model complexity, and aids in generalizing the model.
    Inputs:
          df: features df (x)
          corr_val: Columns are dropped relative to the corr_val input (e.g. 0.8)
    Output: df that only includes uncorrelated features
    '''

    # Creates Correlation Matrix and Instantiates
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []

    # Iterates through Correlation Matrix Table to find correlated columns
    for i in iters:
        for j in range(i):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = item.values
            if val >= corr_val:
                # Prints the correlated feature set and the corr val
                print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(i)

    drops = sorted(set(drop_cols))[::-1]

    # Drops the correlated columns
    for i in drops:
        col = x.iloc[:, (i+1):(i+2)].columns.values
        df = x.drop(col, axis=1)

    return df

A: At first, thanks to TomDobbs and Synergix for their code. Below I am sharing my modifield version with some additions:

*

*Between two correlated variables this function drops a variable which has the least correlation with the target variable

*Added some useful logs (set verbose to True for log printing)

def remove_collinear_features(df_model, target_var, threshold, verbose):
    '''
    Objective:
        Remove collinear features in a dataframe with a correlation coefficient
        greater than the threshold and which have the least correlation with the target (dependent) variable. Removing collinear features can help a model
        to generalize and improves the interpretability of the model.

    Inputs:
        df_model: features dataframe
        target_var: target (dependent) variable
        threshold: features with correlations greater than this value are removed
        verbose: set to "True" for the log printing

    Output:
        dataframe that contains only the non-highly-collinear features
    '''

    # Calculate the correlation matrix
    corr_matrix = df_model.drop(target_var, 1).corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []
    dropped_feature = ""

    # Iterate through the correlation matrix and compare correlations
    for i in iters:
        for j in range(i+1):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = abs(item.values)

            # If correlation exceeds the threshold
            if val >= threshold:
                # Print the correlated features and the correlation value
                if verbose:
                    print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                col_value_corr = df_model[col.values[0]].corr(df_model[target_var])
                row_value_corr = df_model[row.values[0]].corr(df_model[target_var])
                if verbose:
                    print("{}: {}".format(col.values[0], np.round(col_value_corr, 3)))
                    print("{}: {}".format(row.values[0], np.round(row_value_corr, 3)))
                if col_value_corr < row_value_corr:
                    drop_cols.append(col.values[0])
                    dropped_feature = "dropped: " + col.values[0]
                else:
                    drop_cols.append(row.values[0])
                    dropped_feature = "dropped: " + row.values[0]
                if verbose:
                    print(dropped_feature)
                    print("-----------------------------------------------------------------------------")

    # Drop one of each pair of correlated columns
    drops = set(drop_cols)
    df_model = df_model.drop(columns=drops)

    print("dropped columns: ")
    print(list(drops))
    print("-----------------------------------------------------------------------------")
    print("used columns: ")
    print(df_model.columns.tolist())

    return df_model

A: I know that there are already a lot of answers on that but one way I found very simple and short is the following:

# Get correlation matrix
corr = X.corr()

# Create a mask for values above 90%
# But also below 100% since it variables correlated with the same one
mask = (X.corr() > 0.9) & (X.corr() < 1.0)
high_corr = corr[mask]

# Create a new column mask using any() and ~
col_to_filter_out = ~high_corr[mask].any()

# Apply new mask
X_clean = X[high_corr.columns[col_to_filter_out]]

# Visualize cleaned dataset
X_clean

A: If you run out of memory due to pandas .corr() you may find the following solution useful:
    import numpy as np
    from numba import jit

    @jit(nopython=True)
    def corr_filter(X, threshold):
        n = X.shape[1]
        columns = np.ones((n,))
        for i in range(n-1):
            for j in range(i+1, n):
                if columns[j] == 1:
                    correlation = np.abs(np.corrcoef(X[:,i], X[:,j])[0,1])
                    if correlation >= threshold:
                        columns[j] = 0
        return columns

    columns = corr_filter(df.values, 0.7).astype(bool)
    selected_columns = df.columns[columns]

A: Here is an Auto ML class I created to eliminate multicollinearity between features.
What makes my code unique is that out two features that have high correlation, I have eliminated the feature that is least correlated with the target! I got the idea from this seminar by Vishal Patel Sir - https://www.youtube.com/watch?v=ioXKxulmwVQ&feature=youtu.be
#Feature selection class to eliminate multicollinearity
class MultiCollinearityEliminator():

    #Class Constructor
    def __init__(self, df, target, threshold):
        self.df = df
        self.target = target
        self.threshold = threshold

    #Method to create and return the feature correlation matrix dataframe
    def createCorrMatrix(self, include_target = False):
        #Checking we should include the target in the correlation matrix
        if (include_target == False):
            df_temp = self.df.drop([self.target], axis =1)

            #Setting method to Pearson to prevent issues in case the default method for df.corr() gets changed
            #Setting min_period to 30 for the sample size to be statistically significant (normal) according to
            #central limit theorem
            corrMatrix = df_temp.corr(method='pearson', min_periods=30).abs()
        #Target is included for creating the series of feature to target correlation - Please refer the notes under the
        #print statement to understand why we create the series of feature to target correlation
        elif (include_target == True):
            corrMatrix = self.df.corr(method='pearson', min_periods=30).abs()
        return corrMatrix

    #Method to create and return the feature to target correlation matrix dataframe
    def createCorrMatrixWithTarget(self):
        #After obtaining the list of correlated features, this method will help to view which variables
        #(in the list of correlated features) are least correlated with the target
        #This way, out the list of correlated features, we can ensure to elimate the feature that is
        #least correlated with the target
        #This not only helps to sustain the predictive power of the model but also helps in reducing model complexity

        #Obtaining the correlation matrix of the dataframe (along with the target)
        corrMatrix = self.createCorrMatrix(include_target = True)
        #Creating the required dataframe, then dropping the target row
        #and sorting by the value of correlation with target (in asceding order)
        corrWithTarget = pd.DataFrame(corrMatrix.loc[:,self.target]).drop([self.target], axis = 0).sort_values(by = self.target)
        print(corrWithTarget, '\n')
        return corrWithTarget

    #Method to create and return the list of correlated features
    def createCorrelatedFeaturesList(self):
        #Obtaining the correlation matrix of the dataframe (without the target)
        corrMatrix = self.createCorrMatrix(include_target = False)
        colCorr = []
        #Iterating through the columns of the correlation matrix dataframe
        for column in corrMatrix.columns:
            #Iterating through the values (row wise) of the correlation matrix dataframe
            for idx, row in corrMatrix.iterrows():
                if(row[column]>self.threshold) and (row[column]<1):
                    #Adding the features that are not already in the list of correlated features
                    if (idx not in colCorr):
                        colCorr.append(idx)
                    if (column not in colCorr):
                        colCorr.append(column)
        print(colCorr, '\n')
        return colCorr

    #Method to eliminate the least important features from the list of correlated features
    def deleteFeatures(self, colCorr):
        #Obtaining the feature to target correlation matrix dataframe
        corrWithTarget = self.createCorrMatrixWithTarget()
        for idx, row in corrWithTarget.iterrows():
            print(idx, '\n')
            if (idx in colCorr):
                self.df = self.df.drop(idx, axis =1)
                break
        return self.df

    #Method to run automatically eliminate multicollinearity
    def autoEliminateMulticollinearity(self):
        #Obtaining the list of correlated features
        colCorr = self.createCorrelatedFeaturesList()
        while colCorr != []:
            #Obtaining the dataframe after deleting the feature (from the list of correlated features)
            #that is least correlated with the taregt
            self.df = self.deleteFeatures(colCorr)
            #Obtaining the list of correlated features
            colCorr = self.createCorrelatedFeaturesList()
        return self.df

A: A small revision to the solution posted by user3025698 that resolves an issue where the correlation between the first two columns is not captured and some data type checking.
def filter_df_corr(inp_data, corr_val):
    '''
    Returns an array or dataframe (based on type(inp_data) adjusted to drop \
        columns with high correlation to one another. Takes second arg corr_val
        that defines the cutoff

    ----------
    inp_data : np.array, pd.DataFrame
        Values to consider
    corr_val : float
        Value [0, 1] on which to base the correlation cutoff
    '''
    # Creates Correlation Matrix
    if isinstance(inp_data, np.ndarray):
        inp_data = pd.DataFrame(data=inp_data)
        array_flag = True
    else:
        array_flag = False
    corr_matrix = inp_data.corr()

    # Iterates through Correlation Matrix Table to find correlated columns
    drop_cols = []
    n_cols = len(corr_matrix.columns)

    for i in range(n_cols):
        for k in range(i+1, n_cols):
            val = corr_matrix.iloc[k, i]
            col = corr_matrix.columns[i]
            row = corr_matrix.index[k]
            if abs(val) >= corr_val:
                # Prints the correlated feature set and the corr val
                print(col, "|", row, "|", round(val, 2))
                drop_cols.append(col)

    # Drops the correlated columns
    drop_cols = set(drop_cols)
    inp_data = inp_data.drop(columns=drop_cols)
    # Return same type as inp
    if array_flag:
        return inp_data.values
    else:
        return inp_data

A: The question here refers to a HUGE dataset.  However, all of the answers I see are dealing with dataframes. I present an answer for a scipy sparse matrix which runs in parallel.  Rather than returning a giant correlation matrix, this returns a feature mask of fields to keep after checking all fields for both positive and negative Pearson correlations.
I also try to minimize calculations using the following strategy:

*

*Process each column

*Start at the current column + 1 and calculate correlations moving to the right.

*For any abs(correlation) >= threshold, mark the current column for removal and calculate no further correlations.

*Perform these steps for each column in the dataset except the last.

This might be sped up further by keeping a global list of columns marked for removal and skipping further correlation calculations for such columns, since columns will execute out of order.  However, I do not know enough about race conditions in python to implement this tonight.
Returning a column mask will obviously allow the code to handle much larger datasets than returning the entire correlation matrix.
Check each column using this function:
def get_corr_row(idx_num, sp_mat, thresh):
    # slice the column at idx_num
    cols = sp_mat.shape[1]
    x = sp_mat[:,idx_num].toarray().ravel()
    start = idx_num + 1

    # Now slice each column to the right of idx_num
    for i in range(start, cols):
        y = sp_mat[:,i].toarray().ravel()
        # Check the pearson correlation
        corr, pVal = pearsonr(x,y)
        # Pearson ranges from -1 to 1.
        # We check both positive and negative correlations >= thresh using abs(corr)
        if abs(corr) >= thresh:
            # stop checking after finding the 1st correlation > thresh
            return False
            # Mark column at idx_num for removal in the mask
    return True

Run the column level correlation checks in parallel:
from joblib import Parallel, delayed
import multiprocessing

def Get_Corr_Mask(sp_mat, thresh, n_jobs=-1):

    # we must make sure the matrix is in csc format
    # before we start doing all these column slices!
    sp_mat = sp_mat.tocsc()
    cols = sp_mat.shape[1]

    if n_jobs == -1:
        # Process the work on all available CPU cores
        num_cores = multiprocessing.cpu_count()
    else:
        # Process the work on the specified number of CPU cores
        num_cores = n_jobs

    # Return a mask of all columns to keep by calling get_corr_row()
    # once for each column in the matrix
    return Parallel(n_jobs=num_cores, verbose=5)(delayed(get_corr_row)(i, sp_mat, thresh)for i in range(cols))

General Usage:
#Get the mask using your sparse matrix and threshold.
corr_mask = Get_Corr_Mask(X_t_fpr, 0.95)

# Remove features that are >= 95% correlated
X_t_fpr_corr = X_t_fpr[:,corr_mask]

A: If you wanted to return a breakdown of correlated columns you could use this function to look at them to see what you are dropping and adjust your threshold
def corr_cols(df,thresh):
    # Create correlation matrix
    corr_matrix = df.corr().abs()
    # Select upper triangle of correlation matrix
    upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool_))

    dic = {'Feature_1':[],'Featur_2':[],'val':[]}
    for col in upper.columns:
        corl = list(filter(lambda x: x >= thresh, upper[col] ))
        #print(corl)
        if len(corl) > 0:
            inds = [round(x,4) for x in corl]
            for ind in inds:
                #print(col)
                #print(ind)
                col2 = upper[col].index[list(upper[col].apply(lambda x: round(x,4))).index(ind)]
                #print(col2)
                dic['Feature_1'].append(col)
                dic['Featur_2'].append(col2)
                dic['val'].append(ind)
    return pd.DataFrame(dic).sort_values(by="val", ascending=False)

And then remove them by calling the df
    corr = corr_cols(star,0.5)
    df.drop(columns = corr.iloc[:,0].unique())

A: This is the approach I used on my job last month. Perhaps it is not the best or quickest way, but it works fine. Here, df is my original Pandas dataframe:
dropvars = []
threshold = 0.95
df_corr = df.corr().stack().reset_index().rename(columns={'level_0': 'Var 1', 'level_1': 'Var 2', 0: 'Corr'})
df_corr = df_corr[(df_corr['Corr'].abs() >= threshold) & (df_corr['Var 1'] != df_corr['Var 2'])]
while len(df_corr) > 0:
    var = df_corr['Var 1'].iloc[0]
    df_corr = df_corr[((df_corr['Var 1'] != var) & (df_corr['Var 2'] != var))]
    dropvars.append(var)
df.drop(columns=dropvars, inplace=True)

My idea is as follows: first, I create a dataframe containing columna Var 1, Var 2 and Corr, where I keep only those pairs of variables whose correlation is higher than or equal my threshold (in absolute value). Then, I iteratively choose the first variable (Var 1 value) in this correlations dataframe, add it to dropvar list, and remove all lines of the correlations dataframe where it appears, until my correlations dataframe is empty. In the end, I remove the columns in my dropvar list from my original dataframe.

A: I had a similar question today and came across this post. This is what I ended up with.
def uncorrelated_features(df, threshold=0.7):
    """
    Returns a subset of df columns with Pearson correlations
    below threshold.
    """

    corr = df.corr().abs()
    keep = []
    for i in range(len(corr.iloc[:,0])):
        above = corr.iloc[:i,i]
        if len(keep) > 0: above = above[keep]
        if len(above[above < threshold]) == len(above):
            keep.append(corr.columns.values[i])

    return df[keep]

A: I write my own way without any for loop to delete high covariance data from pandas dataframe
#get co variance of data
coVar = df.corr() # or df.corr().abs()
threshold = 0.5 #
"""
1. .where(coVar != 1.0) set NaN where col and index is 1
2. .where(coVar >= threshold) if not greater than threshold set Nan
3. .fillna(0) Fill NaN with 0
4. .sum() convert data frame to serise with sum() and just where is co var greater than threshold sum it
5. > 0 convert all Series to Boolean
"""

coVarCols = coVar.where(coVar != 1.0).where(coVar >=threshold).fillna(0).sum() > 0

# Not Boolean Becuase we need to delete where is co var greater than threshold
coVarCols = ~coVarCols

# get where you want
df[coVarCols[coVarCols].index]

I hope that's can help to use own pandas function to work with out any for loop, That's can help Improve your speed in big dataset

A: correlatedColumns = []
corr = df.corr()
indices = corr.index
columns = corr.columns
posthreshold = 0.7
negthreshold = -0.7

for c in columns:
    for r in indices:
        if c != r and (corr[c][r] > posthreshold or corr[c][r] < negthreshold):
            correlatedColumns.append({"column" : c , "row" : r , "val" :corr[c][r] })

print(correlatedColumns)

A: in my code i need to remove low correlated columns with the dependent variable, and i got this code
to_drop = pd.DataFrame(to_drop).fillna(True)
to_drop = list(to_drop[to_drop['SalePrice'] <.4 ].index)
df_h1.drop(to_drop,axis=1)

df_h1 is my dataframe and SalePrice is the dependent variable... i think changing the value may suit for all other problems

A: The below snippet drop the most correlated features recursively.
def get_corr_feature(df):
    corr_matrix = df.corr().abs()
    # Select upper triangle of correlation matrix
    upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool_))
    upper['score']= upper.max(axis=1)
    upper.sort_values(by=['score'],ascending=False)
    #Find the most correlated feature and send return it for drop
    column_name=upper.sort_values(by=['score'],ascending=False).index[0]
    max_score=upper.loc[column_name,'score']
    return column_name, max_score

max_score=1
while max_score>0.5:
    column_name, max_score=get_corr_feature(df)
    df.drop(column_name,axis=1,inplace=True)

A: I wrote a notebook that uses partial correlations
https://gist.github.com/thistleknot/ce1fc38ea9fcb1a8dafcfe6e0d8af475
the gist of it (pun intended)
for train_index, test_index in kfold.split(all_data):
    #print(iteration)
    max_pvalue = 1

    subset = all_data.iloc[train_index].loc[:, ~all_data.columns.isin([exclude])]

    #skip y and states
    set_ = subset.loc[:, ~subset.columns.isin([target])].columns.tolist()

    n=len(subset)

    while(max_pvalue>=.05):

        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
        p_values = pd.DataFrame(2*dist.cdf(-abs(subset.pcorr()[target]))).T
        p_values.columns = list(subset.columns)

        max_pname = p_values.idxmax(axis=1)[0]
        max_pvalue = p_values[max_pname].values[0]

        if (max_pvalue > .05):

            set_.remove(max_pname)
            temp = [target]
            temp.extend(set_)
            subset = subset[temp]

    winners = p_values.loc[:, ~p_values.columns.isin([target])].columns.tolist()
    sig_table = (sig_table + np.where(all_data.columns.isin(winners),1,0)).copy()

    signs_table[all_data.columns.get_indexer(winners)]+=np.where(subset.pcorr()[target][winners]<0,-1,1)

significance = pd.DataFrame(sig_table).T
significance.columns = list(all_data.columns)
display(significance)

sign = pd.DataFrame(signs_table).T
sign.columns = list(all_data.columns)
display(sign)

purity = abs((sign/num_folds)*(sign/significance)).T.replace([np.inf, -np.inf, np.NaN], 0)
display(purity.T)

A: I believe this has to be done in an iterative way:
uncorrelated_features = features.copy()

# Loop until there's nothing to drop
while True:
    # Calculating the correlation matrix for the remaining list of features
    cor = uncorrelated_features.corr().abs()

    # Generating a square matrix with all 1s except for the main axis
    zero_main = np.triu(np.ones(cor.shape), k=1) +
        np.tril(np.ones(cor.shape), k=-1)

    # Using the zero_main matrix to filter out the main axis of the correlation matrix
    except_main = cor.where(zero_main.astype(bool))

    # Calculating some metrics for each column, including the max correlation,
    # mean correlation and the name of the column
    mertics = [(except_main[column].max(), except_main[column].mean(), column) for column in except_main.columns]

    # Sort the list to find the most suitable candidate to drop at index 0
    mertics.sort(key=lambda x: (x[0], x[1]), reverse=True)

    # Check and see if there's anything to drop from the list of features
    if mertics[0][0] > 0.5:
        uncorrelated_features.drop(mertics[0][2], axis=1, inplace=True)
    else:
        break

It's  worth mentioning that you might want to customize the way I sorted the metrics list and/or how I detected whether I want to drop the column or not.

A: I manage to do it using this way. Kindly have a try. However, the way I did is just reached display purposes as I want to capture the result in my report. If you want to drop it, you can choose any columns from the dataframe below to drop it since can just choose either 1.
row_index = 0
corrDict = {}
row_name = []
col_name = []
corr_val = []

while row_index < len(df.corr().index.tolist()):
    for index, x in enumerate(df.corr().iloc[row_index, :]):
        if abs(x) >= 0.8 and index != row_index:
            if abs(x) in corr_val:
                if (df.corr().index.tolist()[row_index] in col_name) and (df.corr().columns.tolist()[index] in row_name):
                    continue
            row_name.append(df.corr().index.tolist()[row_index])
            col_name.append(df.corr().columns.tolist()[index])
            corr_val.append(x)
    row_index += 1

corrDict ={"First Feature (FF)": row_name, "Second Feature (SF)": col_name, "Correlation (FF x SF)": corr_val}
corr_df2=pd.DataFrame(corrDict)
corr_df2

This is my output:

You can choose either First Feature (FF) or Second Feature (SF).
To drop highly correlated features from your original dataset:
your_df.drop(corr_df2['First Feature (FF)'].tolist(), axis=1, inplace=True)

A: There are three challenges to this problem. First, if features x and y are correlated, you don't want to use an algorithm that drops both. Second, if x and y are pairwise correlated and features y and z are also pairwise correlated, you want the algorithm to only remove y. In this sense, you want it to remove the minimum number of features so that no remaining features have correlations above your threshold. Third, from an efficiency standpoint, you do not want to have to compute the correlation matrix more than once.
Here's an option:
def corr_cleaner(df,corr_cutoff):
    '''
    df: pandas dataframe with column headers.
    corr_cutoff: float between 0 and 1.
    '''
    abs_corr_matrix = df.corr().abs()
    filtered_cols = []
    while True:
        offenders = []
        for i in range(len(abs_corr_matrix)):
            for j in range(len(abs_corr_matrix)):
                if i != j:
                    if abs_corr_matrix.iloc[i,j] > corr_cutoff:
                        offenders.append(df.columns[i])

        if len(offenders) > 0: # if at least one high correlation remains
            c = Counter(offenders)
            worst_offender = c.most_common(1)[0][0]  # var name of worst offender
            del df[worst_offender]
            filtered_cols.append(worst_offender)
            abs_corr_matrix.drop(worst_offender, axis=0, inplace=True) #drop from x-axis
            abs_corr_matrix.drop(worst_offender, axis=1, inplace=True) #drop from y-axis
        else: # if no high correlations remain, break
            break

    return df, filtered_cols

A: You could use the following function, you'll also gets the elements sorted:
def correlation(dataset, threshold = 0.3):
  c = dataset.corr().abs()
  s = c.unstack()
  so = s.sort_values(kind="quicksort")
  results = []
  for index, row in so.items():
    if index[0] != index[1] and row > threshold:
      results.append({index: row})
  return results

You could invoke the function sending a pandas dataset that you want to find the correlation and the threshold as follows:
highly_correlated_features = correlation(dataset=data_train_val_without_label, threshold=0.35)
highly_correlated_features

It would result in something like this for a dataset with the following columns and the default threshold:
Input columns:
 0   HighBP                202944 non-null  float64
 1   HighChol              202944 non-null  float64
 2   CholCheck             202944 non-null  float64
 3   BMI                   202944 non-null  float64
 4   Smoker                202944 non-null  float64
 5   Stroke                202944 non-null  float64
 6   HeartDiseaseorAttack  202944 non-null  float64
 7   PhysActivity          202944 non-null  float64
 8   Fruits                202944 non-null  float64
 9   Veggies               202944 non-null  float64
 10  HvyAlcoholConsump     202944 non-null  float64
 11  AnyHealthcare         202944 non-null  float64
 12  NoDocbcCost           202944 non-null  float64
 13  GenHlth               202944 non-null  float64
 14  MentHlth              202944 non-null  float64
 15  PhysHlth              202944 non-null  float64
 16  DiffWalk              202944 non-null  float64
 17  Sex                   202944 non-null  float64
 18  Age                   202944 non-null  float64
 19  Education             202944 non-null  float64
 20  Income                202944 non-null  float64

Output:
[{('Income', 'Education'): 0.38083797089605675},
 {('Education', 'Income'): 0.38083797089605675},
 {('DiffWalk', 'PhysHlth'): 0.38145172573435343},
 {('PhysHlth', 'DiffWalk'): 0.38145172573435343},
 {('DiffWalk', 'GenHlth'): 0.385707943062701},
 {('GenHlth', 'DiffWalk'): 0.385707943062701},
 {('PhysHlth', 'GenHlth'): 0.3907082729122655},
 {('GenHlth', 'PhysHlth'): 0.3907082729122655}]

A: Can use statsmodels's varianve_inflation_factor to detect multicollinearity in the dataframe.
from statsmodels.stats.outliers_influence import variance_inflation_factor

def vif(X):
    vif = pd.DataFrame()
    vif['Variables'] = X.columns
    vif["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
    return vif

Where X is the DataFrame. VIF for columns that involve multicollinearity will be more than 10. For columns that can be perfectly reproduced by linear combination of other available columns, then its vif value will be infinity. So remove columns now by one, until all infinity values and higher vif values are removed.

A: You can use the Following code:
l=[]
corr_matrix = df.corr().abs()

for ci in corr_matrix.columns:
    for cj in corr_matrix.columns:
        if (corr_matrix[ci][cj]>0.8 and ci!=cj):
            l.append(ci)

l = np.array(l)
to_drop = np.unique(l)
df.drop(to_drop, axis=1, inplace=True)


text:
Q: Reset input field after record save I want to clear the input text fields after the record save. But the values remains. How can I clear the values of the text fields of the form? plz help thanks in advance.
my sponsor.xhtml is
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
   <style type="text/css">
            .ui-growl{
                left:20px;
            }
        </style>

</h:head>
<body>
    <ui:composition template="#{localeControllerBean.path}">
    <ui:define name="head">
        <style>.ui-growl{ #{msg['msg']}: 20px; }</style>
        </ui:define>
        <ui:define name="content">

            <h:form enctype="multipart/form-data" dir="#{localeControllerBean.direction}" id="form1">
                <div id="add">
                <p:growl  id="msgs" autoUpdate="true" display="icon" style="left:20px"></p:growl>

                </div>
                <p:panel header="#{msg['sponsor_detail']}" style="font-size:small">
                    <h:panelGrid columns="2">
                <f:event listener="#{localeControllerBean.islang}" type="preRenderView" />

                        <p:outputLabel for="sname" value="#{msg['sponsor_name']}"
                            styleClass="label" />
                        <p:inputText id="sname" value="#{sponsorBean.sponsor_name}"
                            required="true" requiredMessage="#{msg['sponsor_name_msg']}"
                            styleClass="input">
                            <f:validator validatorId="sponsorValidator" />
                        </p:inputText>

                        <p:outputLabel for="sadd" value="#{msg['sponsoraddress']}:"
                            styleClass="label" />
                        <p:inputText id="sadd" value="#{sponsorBean.s_address}"
                            required="true" requiredMessage="#{msg['Sponsor_address_msg']}"
                            styleClass="input" />

                        <p:outputLabel for="smb" value="#{msg['sponsor_mbno']}:"
                            styleClass="label" />
                        <p:inputText id="smb" value="#{sponsorBean.s_mobile_no}"
                            required="true" requiredMessage="#{msg['sponsor_mbno_msg']}"
                            styleClass="input" />

                        <p:outputLabel for="ss" value="#{msg['sponsor_status']}:" styleClass="label" />
                        <p:inputText id="ss" value="#{sponsorBean.status}" required="true"
                            requiredMessage="#{msg['sponsor_mbno_msg']}" styleClass="input" />
                    </h:panelGrid>

                    <h:panelGrid columns="2" cellpadding="8" style="margin-left:6%">
                    <p:commandButton id="submit" value="#{msg['save']}" ajax="false"
                        action="#{sponsorBean.save}"  style=""
                        update="msgs" icon="ui-icon-disk"/>

                    <p:commandButton type="reset" value="#{msg['reset']}"
                        style="" ajax="false" icon="ui-icon-arrowrefresh-1-e" actionListener="#{sponsorBean.reset}/>
 </h:panelGrid>
                </p:panel>
            </h:form>
        </ui:define>
    </ui:composition>
</body>
</html>

and sponsorbeam.java file is
package com.pms.main;

import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.validation.ConstraintViolationException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.ColumnResizeEvent;
import pojo.TblSponsor;
import com.pms.hmb.Tbl_company;
import com.pms.hmb.Tbl_companydocs;
import com.pms.hmb.Tbl_employee;
import com.pms.hmb.Tbl_sponsor;
import com.pms.util.HibernateUtil;
@ManagedBean
@SessionScoped
public class SponsorBean {
    private int s_id;
    private String sponsor_name;
    private String s_address;
    private String s_mobile_no;
    private String status;
    private Set<Tbl_company> tbl_companies=null;
    Tbl_sponsor selectsponsor=new Tbl_sponsor();

 public Set<Tbl_company> getTbl_companies() {
        return tbl_companies;
    }
    public void setTbl_companies(Set<Tbl_company> tbl_companies) {
        this.tbl_companies = tbl_companies;
    }

    public Tbl_sponsor getSelectsponsor() {
        return selectsponsor;
    }
    public void setSelectsponsor(Tbl_sponsor selectsponsor) {
        this.selectsponsor = selectsponsor;
    }
    public int getS_id() {
        return s_id;
    }
    public void setS_id(int s_id) {
        this.s_id = s_id;
    }
    public String getSponsor_name() {
        return sponsor_name;
    }
    public void setSponsor_name(String sponsor_name) {
        this.sponsor_name = sponsor_name;
    }
    public String getS_address() {
        return s_address;
    }
    public void setS_address(String s_address) {
        this.s_address = s_address;
    }
    public String getS_mobile_no() {
        return s_mobile_no;
    }
    public void setS_mobile_no(String s_mobile_no) {
        this.s_mobile_no = s_mobile_no;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;

    }

    public void onResize(ColumnResizeEvent event) {
        FacesMessage msg = new FacesMessage("Column " + event.getColumn().getClientId() + " resized", "W:" + event.getWidth() + ", H:" + event.getHeight());

        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public String save()
    {
    Tbl_sponsor tbl_sponsor=new Tbl_sponsor();
    tbl_sponsor.setName(this.sponsor_name);
    tbl_sponsor.setS_address(s_address);
    tbl_sponsor.setS_mobile_no(s_mobile_no);
    tbl_sponsor.setStatus(status);

//      tbl_company.setComapany(tbl_company);
        Tbl_company tbl_company1=new Tbl_company();
//      tbl_company1.setComapnyname("a");
//      tbl_company1.setAddress("b");
//      tbl_company1.setEmail("c");
//      tbl_company1.setMobileNumber("66");
//      tbl_company1.setLogoAlt(name);
//      tbl_company1.setImageType(type);
//      tbl_company1.setLogo(byteslogo);
//      tbl_company1.setEmail(email);
//      tbl_company1.setComapany(tbl_company1);
//      tbl_company.setComapany(null);
//tbl_company.setComapany(tbl_company1);

//  tbl_company.setTbl_companies(tbl_company);
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            session.save(tbl_company1);
            session.save(tbl_sponsor);

//          session.save(tblemployee);
//          session.save(tblikama);
            tx.commit();
            FacesContext context = FacesContext.getCurrentInstance();
            String value = context.getApplication().evaluateExpressionGet(context, "#{msg['sponsor_added']}", String.class);

            context.addMessage(null, new FacesMessage(value));

        }
        catch(ConstraintViolationException e)
        {
//  logger.error("error code 409 while creating employee:Constraintvoilation Exception:"+e.getMessage());
            e.printStackTrace();

        }
        catch(Exception e)
        {
//          logger.error("error code 500 while creating employee: Exception:"+e.getMessage());
            e.printStackTrace();

        }
        finally
        {

            session.close();

        }

        return "";
    }

A: Try to clear all String fields of SponsorBean object after saving:
At the end of save method:
    ...
    this.sponsor_name = null;
    this.s_address = null;
    this.s_mobile_no = null;
    return "";
}

Did you consider using request or conversation scoped beans instead of session scoped? They might solve your problem.

A: @SessionScoped beans stores its data through a user session, that is why values of session data members are seen in the page.
Data members should be set to their default values in the action method so that submited values will not be seen in the page again.
this.s_id = 0;
this.sponsor_name = null;
this.s_address = null;
this.s_mobile_no = null;
this.status = null;
return "";

Or you can change scope of managed bean to @RequestScoped. @RequestScoped beans are created from starch for each request.
Furthermore, accessing database in managed beans is not a good practice. You should separate data access from managed beans for the principle  low coupling high cohesion
See also
DAO tutorial - the data layer


text:
Q: If-block not entered, not sure why This function is supposed to read each line of a file and compare it to a user-input string and check if they match. It basically prevents duplicate information in the file. Anyway, the program doesn't go into my "if (loginsFile.is_open())" statement and I don't understand why.
fstream loginsFile;
loginsFile.open("C:/logins.txt", ios::in | ios::out | ios::trunc | ios :: app | ios:: ate);

string username;
string password;
string info;
bool exists = true;
CheckingAccount cA;
SavingsAccount sA;

do {
    cout << "Enter Username: ";
    cin >> username;
    cout << "Enter Password: ";
    cin >> password;
    cout << endl;
    info = username + " " + password;
    if (loginsFile.is_open()){
        while (loginsFile.good()){
            string line;
            getline(loginsFile, line);
            cout << "line is " << line.substr(line.find_last_of(" ")) << "\n" << "info is " << line.substr(line.find_last_of(" "));
            if (line.substr(line.find_last_of(" ")) == info.substr(0, info.find_last_of(" "))){
                exists = false;
                cout << "Username already exists!" << endl << "Program is not case sensitive!";
            } //end if
        } //end while
    } //end if
} while (exists == true); //end do while

loginsFile << info << endl;
loginsFile.close();
logins[info] = make_pair(cA, sA);
cout << info.substr(0, info.find(' ')) << " Has Been Successfully Registered!" << "\n" << "\n";
return logins;

A: Your if-statement isn't being entered because the file isn't open. The file isn't opening because you cannot combine "std::ios::trunc" (truncate file removing all contents) and "std::ios::app" (append to end of file) because they contradict each other.

A: Check failbit after you call open(). If it's set, then the open op failed. Is the forward slash in your path causing a problem, perhaps?

A: Check this link: http://www.cplusplus.com/reference/fstream/fstream/open/
In section mode, it says:
If the mode has both trunc and app set, the opening operation fails. It also fails if either is set but out is not, or if both app and in are set.


text:
Q: Configuring htaccess file for self hosted CDN I am trying to set up a self hosted cdn for my site, but I am having problems with the rules in the htaccess file and I can't get it to work.
At the moment the ftp server that will act as CDN has the following filesystem structure:
/
www/
www/htaccess
www/index.html
www/cdn/*
incremental/*
full/*

My .htaccess looks like this right now:
Options All -Indexes

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

#This snippet basically stops anyone viewing any file on your site that begins with "hta", this will protect it and make it somewhat safer.
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

<Files /cdn>
   Options +Indexes
   Satisfy Any
   Allow from all
</Files>

I want to allow access to the cdn folder and disallow any other access to the other folders, because in incremental and full there are backups of my main server.
I've been searching for rules for achieve this behaviour but nothing work.
I have to allow Indexes in the cdn folder?
Regards and thank you in advance (And sorry for my english)

A: Not to be a jerk but this doesn't sound at all like you're building a CDN. The whole concept of a CDN hinges on delivering your users content from a node closest to them vs. your users having to trudge through the internet to a single box.
It's possible in your research you're having trouble finding out what to do because you're adding this "CDN" concept when it's really not pertinent.
I'll echo the previous advice of moving your backups out of the web accessible folder!
Given what I believe you're trying to accomplish I'd advise that you setup separate vhosts that point requests for a given FQDN to a folder.  This will give you more control over your configuration and ensure that data is only available to certain domains.  So you'd add a new file (myconfig.conf, anything really) in your apache2/conf.d directory that looked something like this:
<VirtualHost *:80>
DocumentRoot /mnt/www/DOMAIN_NAME/cdn
ServerName cdn.DOMAIN_NAME
</VirtualHost>

Obviously you can use whatever you want for your document route, the above is just my personal style.  Create the directory path /mnt/www/DOMAIN_NAME/cdn replacing the DOMAIN_NAME with whatever you're using.  Then anytime you hit cdn.DOMAIN_NAME it will ONLY serve up files in the /mnt/www/DOMAIN_NAME/cdn directory.  Obviously this requires some adjustments to DNS to ensure the cdn subdomain of the DOMAIN_NAME used is pointed to this box.
EDIT: Don't forget to restart apache after you add the new .conf file!
Hopefully this helps.  Though if a true CDN is what you need, I'd advise you to use a service like s3/cloudfront or Rackspace Cloudfiles rather than a DIY solution.  They're VERY affordable options.


text:
Q: Segmentation Fault Accessing Singleton C++ Overview
I am writing a helper class to make calls to Redis easier with the xRedis drivers in C++, but I am continually receiving a segmentation fault upon requesting or sending any information to the instance.
I think this has to do with the way I'm storing the xRedis and RedisDBIdx instances, and possibly the way I'm storing the RedisAdmin instance within the main application, but I'm unable to see the right way to set these up after several attempts.
Relevant Code is below, and a few notes on debugging steps I have taken myself.
Debugging Notes

*

*Redis Server is started successfully, and log output shows successful connection to server on instance startup

*The call fails whether a set or exists command is sent to the server

*GDB Output shows below, and logs show the same happenning on either exists or set calls:
Program received signal SIGSEGV, Segmentation fault.
RedisPool::GetConnection (this=0x0, cahcetype=0, dbindex=0, ioType=0) at src/xRedisPool.cpp:124
124        || (ioType>SLAVE)

Code
redis_admin.h
#include "xredis/xRedisClient.h"
#include <string.h>
#include <string>

class xRedisAdmin
{
xRedisClient xRed;
public:
    xRedisAdmin(RedisNode conn_list[], int conn_list_size);
    ~xRedisAdmin();
    const char * load ( const char * key );
    bool save ( const char * key, const char * msg );
    bool exists ( const char * key );
    bool del ( const char * key );
};

redis_admin.cpp
xRedisAdmin::xRedisAdmin(RedisNode conn_list[], int conn_list_size)
{
enum {
CACHE_TYPE_1,
CACHE_TYPE_2,
CACHE_TYPE_MAX,
};

xRed.Init(CACHE_TYPE_MAX);
bool bret = xRed.ConnectRedisCache(conn_list, conn_list_size, CACHE_TYPE_1);
//Log results
}

//Exists
bool xRedisAdmin::exists(const char * key)
{
RedisDBIdx d(&xRedis);
char szKey[256] = {0};
sprintf(szKey, key);
return xRed.exists(d, szKey);
}

//Save
bool xRedisAdmin::save(const char * key, const char * val)
{
RedisDBIdx d(&xRed);
char szKey[256] = {0};
sprintf(szKey, key);
bool ret_val = xRed.set(d, szKey, val);
//Log output
return ret_val;
}

Main.cpp
xRedisAdmin *xRed;

void example_callback() {
    bool bRet = xRed->save("key", "c_str");
}

int main()
{
    xRedisAdmin x (RedisList1, conn_list_size);
    xRed = &x;

    example_callback();
    return 0;
}

A: As it turns out, this is what I get for violating the Rule of Threes.
I did not have a copy constructor for the Redis Admin, and the xRed object inside it became null on assignment because of this.  Use of new & delete, rather than creating in the main method, did resolve the issue. proved the solution to the issue
Thanks all who commented and gave me answers & support!
Alex


text:
Q: como mostrar imagenes que tengo en una base de datos que tal amigos pido su ayuda , tengo una tabla en mi base de datos donde guardo las imagenes y quiero mostrarlas en mi pagina html , pero que estas  al momento de mostrarlas se vayan acomodando horizontalmente en hilera , en lugar de mostrarlas hacia abajo
$query = mysqli_query($mysqli, "SELECT n.id_not,n.titulo_not, n.desc_not, p.*  FROM noticias as n INNER JOIN foto as p ON n.id_not=p.id_not WHERE n.id_not='$id'")
                                                    or die('Hubo un error en la consulta : '.mysqli_error($mysqli));

                    while($row=mysqli_fetch_array($query)){

                    if($row['titulo_not']!=$noticia){

                    ?>

<?php echo $row['titulo_not']; ?>

<?php echo $row['desc_not']; ?>

                        <?php

                        $noticia=$row['titulo_not'];

                         } ?>

                            <a href="<?php echo $row['ubicacion']; ?>" target="_blank"> <img class="thumbnail img-responsive" id="image" src="<?php echo $row['ubicacion']; ?>" style="  margin:10px; width: 300px; height:230px;" title="<?php echo $row['titulo_not']; ?>"/>

                    <?php

                      }

                     ?>

A: Bienvendio Jeovani, Me parece que estás utilizando bootstrap, intenta cambiando las clases de tu etiqueta div padre
Cómo la tienes es así

Cómo debería ser es así

De esta forma en dispositivos a partir de tablets en adelante se verán tres imágenes por fila si cambias a col-md-3 se verán 4 por fila.
Te recomiendo que lo hagas así pues col-sm-12 hace que sólo se vea una imagen por fila en dispositivos embebidos, es más cómodo a la vista.


text:
Q: Is it correct to write $\nabla\times(\nabla\times\textbf{E})$ as $\nabla\times(\nabla\times)\cdot\textbf{E}$? Is it correct to write $\nabla\times(\nabla\times\textbf{E})$ as $\nabla\times(\nabla\times)\cdot\textbf{E}$ ?
 I read this kind of expression on a book, but I wonder if it is correct to write it like this.
A
B


text:
Q: No mapping found for HTTP request with URI [/CalorieTracker/] in DispatcherServlet with name 'dispatcher' This is my application configuration class:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.spring")
public class AppConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

}

This is my application configuration initializer class.
public class AppConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return new Class[] {AppConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
    // TODO Auto-generated method stub
    return null;
}

@Override
protected String[] getServletMappings() {
    // TODO Auto-generated method stub
    return new String[] {"/"};
}

}
This is my rest controller class.
@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<UserResource> createUser(@RequestBody UserResource userDetails) {
        try {
            User createdUser = userService.createUser(userDetails.toUser());
            UserResource res = new UserResourceAsm().toResource(createdUser);
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(URI.create(res.getLink("self").getHref()));
            return new ResponseEntity<UserResource>(res, headers,  HttpStatus.CREATED);
        } catch (UserExistsException e) {
            throw new ConflictException(e);
        }
    }
}

In the console I am getting this warning
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/CalorieTracker/] in DispatcherServlet with name 'dispatcher'

I believe because of this warning when I tried to call my rest api "http://localhost:8080/CalorieTracker/user", I am getting status 404.
Can anyone help what is wrong while configuring the program?

A: change
@RequestMapping("/user")
public class UserController

to
@RequestMapping("/")
public class UserController


text:
Q: How to configure rabbitmq with mongo? How to configure rabbitmq with mongo?
how to configure rabbitmq image (https://hub.docker.com/_/rabbitmq/) for save messages in mongo and not in files.
It is possible?

A:
It is possible?

no.
RabbitMQ does not provide a way to change it's internal storage


text:
Q: How to apply Chisq.test on levels of different categorical variables? I want to perform chisq.test() on each level of the categorical variable.
Currently, I have managed to do it on each categorical variable using below code.
# Random generation of values for categorical data
set.seed(12)
x <- data.frame(col1 = sample( LETTERS[1:4], 100, replace=TRUE ),
                col2 = sample( LETTERS[3:6], 100, replace=TRUE ),
                col3 = sample( LETTERS[2:5], 100, replace=TRUE ),
                out = sample(c(1,2),100, replace=TRUE))

# performing chisq.test
pval <- as.data.frame(sapply(c(1:3),function(i)chisq.test(x[,i],x[,'out'])$p.value ))

#output
    p.value
1 0.33019256
2 0.08523487
3 0.79403367

I am interested to compare the levels at different outcomes.
# for col1 levels different outcomes
table(x$col1,x$out)

#output
     1  2
  A  8 12
  B 18 10
  C 12 11
  D 18 11

For example, to compare level B in col1 for different outcomes 1,2 in out.
I would like to know how can this be extended(or in another smart way) to each level of a categorical variable ?
# Expected output
       p.value

col1.A  *****
col1.B  *****
col1.C  *****
.
.
.
col3.E  *****

Thanks for your attention.

A: This is how you would do it if you wanted to do a Chi-squared test for given probabilities (with p = rep(0.5, 2)).
I've broken this down to make it easier to understand:
getP <- function(lev, x, i) {
  tab <- table(x$out[x[, i] == lev])
  chisq.test(tab)$p.value
}
pvalList <- lapply(1:3, function(i) {
  df <- data.frame(Column = i, Category = levels(x[, i]))
  df$p.value <- sapply(df$Category, getP, x, i)
  df
})
pval <- do.call("rbind", pvalList) # Convert to single data frame

Alternatively, if what you want is actually A vs not A, B vs not B, etc., you could substitute the definition of getP with:
getP <- function(lev, x, i) {
  tab <- table(x$out, x[, i] == lev)
  chisq.test(tab)$p.value
}


text:
Q: How to properly do a "bind" in angular2 typescript? I want to use a javascript library that requires creating an object and binding to it like this:
this.mystr = "hello";
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = function(evt) {
    console.log(this.mystr); // this is undefined, even though I do have it defined
}

I would usually do a .bind(this)
Though in typescript I want to do this:
this.mystr = "hello"
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = onresult;

onresult(event) {
    console.log(this.mystr) // this is undefined, even though I do have it defined
}

The .bind(this) does not work in this example. How do I get around this? Are there alternatives to just doing .bind(this)? Or whatever works for typescript functions?

A: In TypeScript as well as in ES6 the most convenient way to bind a function is to use arrow function which preserves the context:
this.webkitspeech.onresult = ($event) => { this.onresult($event) };

Or use bind like this:
this.webkitspeech.onresult = this.onresult.bind(this);

Or you can use TS instance arrow function (ES class property) like this:
class MyClass() {
   onresult = ($event) => {...}
   ...
   this.webkitspeech.onresult = onresult;
}

Class properties is stage 2 ES7 proposal which is supported in TS today.
See the documentation for some comparison between the methods.


text:
Q: Take a list of coordinates and plot them on a graph Right now I have a list of coordinates that are in the following format:
(1,12),(2,3),(3,9)....

All the coordinates are in brackets as above, and the format is exactly the same for the rest of the string (the list is in string format). The x-values of the coordinates increase by one throughout the string (and could continue on to even 100000. The y-values are random and could range from 1 to 2048 or even higher numbers. I want to find a way to take that string (which is a list of coordinates in the above format) and turn it into a picture or virtual graph, with each point plotted on it. I am currently using Python 2.7 in visual studio, but am open to using other programs, as the string itself is stored in a .txt file in the above format.
Once that is done, I'd like to be able to take that graph and using only it as a base point, be able to regenerate the entire string again.

A: You can use matplotlib to plot and ast.literal_eval to evaluate your string:
import matplotlib.pylab as plt
from ast import literal_eval
from operator import itemgetter

with open("your_file") as f:
    lst = literal_eval(f.read())
    x,y = map(itemgetter(0),lst), map(itemgetter(1),lst)
    plt.plot(x,y)
    plt.show()


text:
Q: Using webdriver and testng with apache metamodel for multiple excel sheets data as test input Is there a possiblity of using primary key and foreign key for excel sheets using metamodel api to cook data for the testng tests in selenium webdriver

A: There is a possibility for this using in the above mentioned context as Excel sheets can be queried by SQL/more-like SQL commands in Fillo


text:
Q: Does average value always exist? If $a_i \in {\mathbb R}_+$ for all $i \in {\mathbb Z_+}$, and
\begin{align}
\limsup_{n \rightarrow \infty} \frac{1}{n} \sum_{i=1}^{n} a_i < \infty,
\end{align}
then does the $\lim$ exist? In other words, is there any $c \in {\mathbb R}$ such that
\begin{align}
\lim_{n \rightarrow \infty} \frac{1}{n} \sum_{i=1}^{n} a_i =c.
\end{align}
Notes: $(1/n)\sum_{i=1}^{n}a_i$ does not increase with $n$, even though $\sum_{i=1}^{n}a_i$ does. Hence, the Monotone Convergence Theorem cannot be applied.

A: No, there are plenty of examples where this fails. Let $a_i=1$ whenever $i$ does not have a 1 in it's decimal expansion. You'll see plenty of such $i$ for $i<1000$ but then suddenly no $i$ in $1000<i<2000$. Then it will jump again. The limsup exists since it is bounded above by $1$. But the average will oscillate forever. To prove this, notice that the average drops below $1/2$ whenever $i\in [10^x,2\cdot 10^x]$ but then is above $1/2$ when $i\in [2\cdot 10^x,3\cdot 10^x]$.

A: Consider the sequence:
$$0,1,-1,2,-2,3,-3,4,-4,\dots$$
The average of the first $n$ numbers are:
$$0,\,\frac12,\,0,\,\frac12,\,0,\,\frac12,\,0,\,\frac12,\,0\dots$$

A: Of course not.  See if you can make $\frac{1}{n} \sum_{i=1}^{n} a_i$ remain between $0$ and $1$, but take value ${} \gt 9/10$ infinitely often and value ${} \le 1/10$ infinitely often.

A: Firstly, thanks to you all!
With your help, I think I can find an counterexample such that $c_n := 1/n \sum_{i=1}^n a_i$ goes between $1/2$ and $1$ infinitely times.
$a_1 = 1$, $a_2=a_3=\varepsilon$, $a_4 = 1-2\varepsilon$, $a_5 =3$, $a_6=a_7=a_8=a_9=a_{10}=a_{11}=\varepsilon$,$a_{12}=1-6\varepsilon$,...
The main idea is
\begin{align}
\frac {1}{1} = 1,c_2,c_3,\frac {2}{4} = \frac {1}{2},\frac {5}{5} =1,c_6,c_7,c_8,c_9,c_{10},c_{11},\frac {6}{12},\ldots
\end{align}


text:
Q: What evaluates to false in Ruby? false and nil evaluate to false in Ruby. Anything else? Please provide links to official/authoritative references.
2.0.0p247 :001 > if true ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE

2.0.0p247 :002 > if false ; puts 'TRUE' ; else puts 'FALSE' ; end
FALSE

2.0.0p247 :003 > if nil ; puts 'TRUE' ; else puts 'FALSE' ; end
FALSE

2.0.0p247 :004 > if 0 ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE

2.0.0p247 :005 > if [] ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE

2.0.0p247 :006 > if {} ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE

2.0.0p247 :007 > if '' ; puts 'TRUE' ; else puts 'FALSE' ; end
(irb):616: warning: string literal in condition
TRUE

A: You just found them all

In Ruby, false and nil are "falsy", while all other values are "truthy"

as Yehuda Katz mentioned in his blog post in 2009

A: false and nil are the only ones:
http://www.ruby-doc.org/core-2.1.1/FalseClass.html
Rails provides present? which also includes empty strings and empty arrays:  http://api.rubyonrails.org/classes/Object.html#method-i-present-3F

A: The only false-y values in Ruby are false and nil, as attested to by the book "The Ruby Programming Language", by David Flanagan and Yukihiro Matsumoto (the Matz):

Predicates typically return one of the Boolean values true or false, but this is not required, as any value other than false or nil works like true when a Boolean value is required. (The Numeric method nonzero?, for example, returns nil if the number it is invoked on is zero, and just returns the number otherwise.)

(emphasis mine)
This quote can be found on page 180 of the book.

A: I can only agree, that nil and false are indeed the only two values, that evaluate to false in Ruby. I just wanted to point to another useful resource:
True and False vs. "Truthy" and "Falsey" (or "Falsy") in Ruby, Python, and JavaScript

A: Note that even though false and nil are the only objects that result in false in a Boolean context, that's when tested directly in a Boolean context, e.g., the object in question corresponds to the expression being tested in an if.
In particular, an object can still customize the logical not operator. That is, how the unary ! operator and the keyword not behave, and this can lead to surprises.
class FakeFalsy
    def !
        true
    end
end

FakeFalsy above defines a ! method customizing this way the behaving of the logical not. Note that an instance of FakeFalsy isn't either false or nil:
>> obj = FakeFalsy.new
...
>> obj.equal? false
=> false
>> obj.equal? nil
=> false

Yet it may still look that the object being tested is either false or nil:
>> puts "It seems to be false or nil" if !obj
It seems to be false or nil
=> nil
puts "It seems to be false or nil" if not obj
It seems to be false or nil
=> nil


text:
Q: Monitoring Springboot 2.0 Tomcat server Thread utilization I have started my springboot application with following tomcat parameters
-Dserver.tomcat.max-threads=400
-Dserver.tomcat.max-connections=4000

I want to monitor busy thread and busy connection size?
Is there a built-in solution inside springboot? Otherwise Do I need to get mbeans?
Found similar  question but solution is not given yet.
Thanks.

A: At first, I use Spring Boot Actuator and Micrometer. But It does not show tomcat thread utilization. So I configured the application.yml like this.
server:
  port: 3200
  address: 0.0.0.0
  tomcat:
    max-threads: 4000
    mbeanregistry:
      enabled: true

I set server.tomcat.mbeanregistry.enabled to true. Then Tomcat threads utilization is shown in /actuator/metrics.
This is my output.
{
  "names": [
    "http.server.requests",
    "http.server.requests.histogram",
    "jvm.buffer.count",
    "jvm.buffer.memory.used",
    "jvm.buffer.total.capacity",
    "jvm.classes.loaded",
    "jvm.classes.unloaded",
    "jvm.gc.live.data.size",
    "jvm.gc.max.data.size",
    "jvm.gc.memory.allocated",
    "jvm.gc.memory.promoted",
    "jvm.gc.pause",
    "jvm.memory.committed",
    "jvm.memory.max",
    "jvm.memory.used",
    "jvm.threads.daemon",
    "jvm.threads.live",
    "jvm.threads.peak",
    "jvm.threads.states",
    "logback.events",
    "process.cpu.usage",
    "process.files.max",
    "process.files.open",
    "process.start.time",
    "process.uptime",
    "system.cpu.count",
    "system.cpu.usage",
    "system.load.average.1m",
    "thread.pool.core.size",
    "thread.pool.max.size",
    "thread.pool.pool.size",
    "thread.pool.thread.count",
    "tomcat.cache.access",
    "tomcat.cache.hit",
    "tomcat.global.error",
    "tomcat.global.received",
    "tomcat.global.request",
    "tomcat.global.request.max",
    "tomcat.global.sent",
    "tomcat.servlet.error",
    "tomcat.servlet.request",
    "tomcat.servlet.request.max",
    "tomcat.sessions.active.current",
    "tomcat.sessions.active.max",
    "tomcat.sessions.alive.max",
    "tomcat.sessions.created",
    "tomcat.sessions.expired",
    "tomcat.sessions.rejected",
    "tomcat.threads.busy",
    "tomcat.threads.config.max",
    "tomcat.threads.current"
  ]
}

A: One easy to do this is by using Spring Actuator with Micrometer on top of it. You get instant JMX metrics and you can also declare your own custom ones.

A: You can use Spring Boot Actuator (/metrics endpoint) that gives information about memory, heap, processors, threads, classes loaded, classes unloaded, thread pools, etc.
For example, this endpoint returns:
"threads.peak" : ...,
"threads.daemon" : ...,
"threads" : ...,

Also, you can get a thread dump in case if you need to by using /threaddump endpoint.